2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1998
6 This module contains definitions for the IdInfo for things that
7 have a standard form, namely:
11 - method and superclass selectors
12 - primitive operations
16 mkDictFunId, mkDictFunTy, mkDictSelId,
19 mkPrimOpId, mkFCallId, mkTickBoxOpId, mkBreakPointOpId,
21 mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
22 wrapFamInstBody, unwrapFamInstScrut,
23 mkUnpackCase, mkProductBox,
25 -- And some particular Ids; see below for why they are wired in
26 wiredInIds, ghcPrimIds,
27 unsafeCoerceName, unsafeCoerceId, realWorldPrimId,
28 voidArgId, nullAddrId, seqId, lazyId, lazyIdKey,
31 -- Re-export error Ids
35 #include "HsVersions.h"
39 import TysWiredIn ( unitTy )
45 import CoreUtils ( exprType, mkCoerce )
56 import Var ( mkExportedLocalVar )
62 import BasicTypes hiding ( SuccessFlag(..) )
71 %************************************************************************
73 \subsection{Wired in Ids}
75 %************************************************************************
79 There are several reasons why an Id might appear in the wiredInIds:
81 (1) The ghcPrimIds are wired in because they can't be defined in
82 Haskell at all, although the can be defined in Core. They have
83 compulsory unfoldings, so they are always inlined and they have
84 no definition site. Their home module is GHC.Prim, so they
85 also have a description in primops.txt.pp, where they are called
88 (2) The 'error' function, eRROR_ID, is wired in because we don't yet have
89 a way to express in an interface file that the result type variable
90 is 'open'; that is can be unified with an unboxed type
92 [The interface file format now carry such information, but there's
93 no way yet of expressing at the definition site for these
94 error-reporting functions that they have an 'open'
95 result type. -- sof 1/99]
97 (3) Other error functions (rUNTIME_ERROR_ID) are wired in (a) because
98 the desugarer generates code that mentiones them directly, and
99 (b) for the same reason as eRROR_ID
101 (4) lazyId is wired in because the wired-in version overrides the
102 strictness of the version defined in GHC.Base
104 In cases (2-4), the function has a definition in a library module, and
105 can be called; but the wired-in version means that the details are
106 never read from that module's interface file; instead, the full definition
113 ++ errorIds -- Defined in MkCore
116 -- These Ids are exported from GHC.Prim
119 = [ -- These can't be defined in Haskell, but they have
120 -- perfectly reasonable unfoldings in Core
128 %************************************************************************
130 \subsection{Data constructors}
132 %************************************************************************
134 The wrapper for a constructor is an ordinary top-level binding that evaluates
135 any strict args, unboxes any args that are going to be flattened, and calls
138 We're going to build a constructor that looks like:
140 data (Data a, C b) => T a b = T1 !a !Int b
143 \d1::Data a, d2::C b ->
144 \p q r -> case p of { p ->
146 Con T1 [a,b] [p,q,r]}}
150 * d2 is thrown away --- a context in a data decl is used to make sure
151 one *could* construct dictionaries at the site the constructor
152 is used, but the dictionary isn't actually used.
154 * We have to check that we can construct Data dictionaries for
155 the types a and Int. Once we've done that we can throw d1 away too.
157 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
158 all that matters is that the arguments are evaluated. "seq" is
159 very careful to preserve evaluation order, which we don't need
162 You might think that we could simply give constructors some strictness
163 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
164 But we don't do that because in the case of primops and functions strictness
165 is a *property* not a *requirement*. In the case of constructors we need to
166 do something active to evaluate the argument.
168 Making an explicit case expression allows the simplifier to eliminate
169 it in the (common) case where the constructor arg is already evaluated.
171 Note [Wrappers for data instance tycons]
172 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
173 In the case of data instances, the wrapper also applies the coercion turning
174 the representation type into the family instance type to cast the result of
175 the wrapper. For example, consider the declarations
177 data family Map k :: * -> *
178 data instance Map (a, b) v = MapPair (Map a (Pair b v))
180 The tycon to which the datacon MapPair belongs gets a unique internal
181 name of the form :R123Map, and we call it the representation tycon.
182 In contrast, Map is the family tycon (accessible via
183 tyConFamInst_maybe). A coercion allows you to move between
184 representation and family type. It is accessible from :R123Map via
185 tyConFamilyCoercion_maybe and has kind
187 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
189 The wrapper and worker of MapPair get the types
192 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
193 $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v)
196 MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
198 This coercion is conditionally applied by wrapFamInstBody.
200 It's a bit more complicated if the data instance is a GADT as well!
202 data instance T [a] where
203 T1 :: forall b. b -> T [Maybe b]
205 Hence we translate to
208 $WT1 :: forall b. b -> T [Maybe b]
209 $WT1 b v = T1 (Maybe b) b (Maybe b) v
210 `cast` sym (Co7T (Maybe b))
213 T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
215 -- Coercion from family type to representation type
216 Co7T a :: T [a] ~ :R7T a
219 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
220 mkDataConIds wrap_name wkr_name data_con
221 | isNewTyCon tycon -- Newtype, only has a worker
222 = DCIds Nothing nt_work_id
224 | any isBanged all_strict_marks -- Algebraic, needs wrapper
225 || not (null eq_spec) -- NB: LoadIface.ifaceDeclSubBndrs
226 || isFamInstTyCon tycon -- depends on this test
227 = DCIds (Just alg_wrap_id) wrk_id
229 | otherwise -- Algebraic, no wrapper
230 = DCIds Nothing wrk_id
232 (univ_tvs, ex_tvs, eq_spec,
233 other_theta, orig_arg_tys, res_ty) = dataConFullSig data_con
234 tycon = dataConTyCon data_con -- The representation TyCon (not family)
236 ----------- Worker (algebraic data types only) --------------
237 -- The *worker* for the data constructor is the function that
238 -- takes the representation arguments and builds the constructor.
239 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
240 (dataConRepType data_con) wkr_info
242 wkr_arity = dataConRepArity data_con
243 wkr_info = noCafIdInfo
244 `setArityInfo` wkr_arity
245 `setStrictnessInfo` Just wkr_sig
246 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
249 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
250 -- Note [Data-con worker strictness]
251 -- Notice that we do *not* say the worker is strict
252 -- even if the data constructor is declared strict
253 -- e.g. data T = MkT !(Int,Int)
254 -- Why? Because the *wrapper* is strict (and its unfolding has case
255 -- expresssions that do the evals) but the *worker* itself is not.
256 -- If we pretend it is strict then when we see
257 -- case x of y -> $wMkT y
258 -- the simplifier thinks that y is "sure to be evaluated" (because
259 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
261 -- When the simplifer sees a pattern
262 -- case e of MkT x -> ...
263 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
264 -- but that's fine... dataConRepStrictness comes from the data con
265 -- not from the worker Id.
267 cpr_info | isProductTyCon tycon &&
270 wkr_arity <= mAX_CPR_SIZE = retCPR
272 -- RetCPR is only true for products that are real data types;
273 -- that is, not unboxed tuples or [non-recursive] newtypes
275 ----------- Workers for newtypes --------------
276 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
277 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
278 `setArityInfo` 1 -- Arity 1
279 `setInlinePragInfo` alwaysInlinePragma
280 `setUnfoldingInfo` newtype_unf
281 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
282 newtype_unf = ASSERT2( isVanillaDataCon data_con &&
283 isSingleton orig_arg_tys, ppr data_con )
284 -- Note [Newtype datacons]
285 mkCompulsoryUnfolding $
286 mkLams wrap_tvs $ Lam id_arg1 $
287 wrapNewTypeBody tycon res_ty_args (Var id_arg1)
290 ----------- Wrapper --------------
291 -- We used to include the stupid theta in the wrapper's args
292 -- but now we don't. Instead the type checker just injects these
293 -- extra constraints where necessary.
294 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
295 res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
296 ev_tys = mkPredTys other_theta
297 wrap_ty = mkForAllTys wrap_tvs $
299 mkFunTys orig_arg_tys $ res_ty
301 ----------- Wrappers for algebraic data types --------------
302 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
303 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
304 `setArityInfo` wrap_arity
305 -- It's important to specify the arity, so that partial
306 -- applications are treated as values
307 `setInlinePragInfo` alwaysInlinePragma
308 `setUnfoldingInfo` wrap_unf
309 `setStrictnessInfo` Just wrap_sig
311 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
312 wrap_sig = mkStrictSig (mkTopDmdType wrap_arg_dmds cpr_info)
313 wrap_stricts = dropList eq_spec all_strict_marks
314 wrap_arg_dmds = map mk_dmd wrap_stricts
315 mk_dmd str | isBanged str = evalDmd
316 | otherwise = lazyDmd
317 -- The Cpr info can be important inside INLINE rhss, where the
318 -- wrapper constructor isn't inlined.
319 -- And the argument strictness can be important too; we
320 -- may not inline a contructor when it is partially applied.
322 -- data W = C !Int !Int !Int
323 -- ...(let w = C x in ...(w p q)...)...
324 -- we want to see that w is strict in its two arguments
326 wrap_unf = mkInlineUnfolding (Just (length ev_args + length id_args)) wrap_rhs
327 wrap_rhs = mkLams wrap_tvs $
330 foldr mk_case con_app
331 (zip (ev_args ++ id_args) wrap_stricts)
333 -- The ev_args is the evidence arguments *other than* the eq_spec
334 -- Because we are going to apply the eq_spec args manually in the
337 con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
338 Var wrk_id `mkTyApps` res_ty_args
340 `mkCoApps` map (mkReflCo . snd) eq_spec
341 `mkVarApps` reverse rep_ids
343 (ev_args,i2) = mkLocals 1 ev_tys
344 (id_args,i3) = mkLocals i2 orig_arg_tys
348 :: (Id, HsBang) -- Arg, strictness
349 -> (Int -> [Id] -> CoreExpr) -- Body
350 -> Int -- Next rep arg id
351 -> [Id] -- Rep args so far, reversed
353 mk_case (arg,strict) body i rep_args
355 HsNoBang -> body i (arg:rep_args)
356 HsUnpack -> unboxProduct i (Var arg) (idType arg) the_body
358 the_body i con_args = body i (reverse con_args ++ rep_args)
359 _other -- HsUnpackFailed and HsStrict
360 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
361 | otherwise -> Case (Var arg) arg res_ty
362 [(DEFAULT,[], body i (arg:rep_args))]
364 mAX_CPR_SIZE :: Arity
366 -- We do not treat very big tuples as CPR-ish:
367 -- a) for a start we get into trouble because there aren't
368 -- "enough" unboxed tuple types (a tiresome restriction,
370 -- b) more importantly, big unboxed tuples get returned mainly
371 -- on the stack, and are often then allocated in the heap
372 -- by the caller. So doing CPR for them may in fact make
375 mkLocals :: Int -> [Type] -> ([Id], Int)
376 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
381 Note [Newtype datacons]
382 ~~~~~~~~~~~~~~~~~~~~~~~
383 The "data constructor" for a newtype should always be vanilla. At one
384 point this wasn't true, because the newtype arising from
387 newtype T:D a = D:D (C a)
388 so the data constructor for T:C had a single argument, namely the
389 predicate (C a). But now we treat that as an ordinary argument, not
390 part of the theta-type, so all is well.
393 %************************************************************************
395 \subsection{Dictionary selectors}
397 %************************************************************************
399 Selecting a field for a dictionary. If there is just one field, then
400 there's nothing to do.
402 Dictionary selectors may get nested forall-types. Thus:
405 op :: forall b. Ord b => a -> b -> b
407 Then the top-level type for op is
409 op :: forall a. Foo a =>
413 This is unlike ordinary record selectors, which have all the for-alls
414 at the outside. When dealing with classes it's very convenient to
415 recover the original type signature from the class op selector.
418 mkDictSelId :: Bool -- True <=> don't include the unfolding
419 -- Little point on imports without -O, because the
420 -- dictionary itself won't be visible
421 -> Name -- Name of one of the *value* selectors
422 -- (dictionary superclass or method)
424 mkDictSelId no_unf name clas
425 = mkGlobalId (ClassOpId clas) name sel_ty info
427 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
428 -- We can't just say (exprType rhs), because that would give a type
430 -- for a single-op class (after all, the selector is the identity)
431 -- But it's type must expose the representation of the dictionary
432 -- to get (say) C a -> (a -> a)
434 base_info = noCafIdInfo
436 `setStrictnessInfo` Just strict_sig
437 `setUnfoldingInfo` (if no_unf then noUnfolding
438 else mkImplicitUnfolding rhs)
439 -- In module where class op is defined, we must add
440 -- the unfolding, even though it'll never be inlined
441 -- becuase we use that to generate a top-level binding
444 info | new_tycon = base_info `setInlinePragInfo` alwaysInlinePragma
445 -- See Note [Single-method classes] in TcInstDcls
446 -- for why alwaysInlinePragma
447 | otherwise = base_info `setSpecInfo` mkSpecInfo [rule]
448 `setInlinePragInfo` neverInlinePragma
449 -- Add a magic BuiltinRule, and never inline it
450 -- so that the rule is always available to fire.
451 -- See Note [ClassOp/DFun selection] in TcInstDcls
453 n_ty_args = length tyvars
455 -- This is the built-in rule that goes
456 -- op (dfT d1 d2) ---> opT d1 d2
457 rule = BuiltinRule { ru_name = fsLit "Class op " `appendFS`
458 occNameFS (getOccName name)
460 , ru_nargs = n_ty_args + 1
461 , ru_try = dictSelRule val_index n_ty_args }
463 -- The strictness signature is of the form U(AAAVAAAA) -> T
464 -- where the V depends on which item we are selecting
465 -- It's worth giving one, so that absence info etc is generated
466 -- even if the selector isn't inlined
467 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
468 arg_dmd | new_tycon = evalDmd
469 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
472 tycon = classTyCon clas
473 new_tycon = isNewTyCon tycon
474 [data_con] = tyConDataCons tycon
475 tyvars = dataConUnivTyVars data_con
476 arg_tys = dataConRepArgTys data_con -- Includes the dictionary superclasses
478 -- 'index' is a 0-index into the *value* arguments of the dictionary
479 val_index = assoc "MkId.mkDictSelId" sel_index_prs name
480 sel_index_prs = map idName (classAllSelIds clas) `zip` [0..]
482 the_arg_id = arg_ids !! val_index
483 pred = mkClassPred clas (mkTyVarTys tyvars)
484 dict_id = mkTemplateLocal 1 $ mkPredTy pred
485 arg_ids = mkTemplateLocalsNum 2 arg_tys
487 rhs = mkLams tyvars (Lam dict_id rhs_body)
488 rhs_body | new_tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
489 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
490 [(DataAlt data_con, arg_ids, Var the_arg_id)]
492 dictSelRule :: Int -> Arity
493 -> IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
494 -- Tries to persuade the argument to look like a constructor
495 -- application, using exprIsConApp_maybe, and then selects
497 -- sel_i t1..tk (D t1..tk op1 ... opm) = opi
499 dictSelRule val_index n_ty_args id_unf args
500 | (dict_arg : _) <- drop n_ty_args args
501 , Just (_, _, con_args) <- exprIsConApp_maybe id_unf dict_arg
502 = Just (con_args !! val_index)
508 %************************************************************************
512 %************************************************************************
515 -- unbox a product type...
516 -- we will recurse into newtypes, casting along the way, and unbox at the
517 -- first product data constructor we find. e.g.
519 -- data PairInt = PairInt Int Int
520 -- newtype S = MkS PairInt
523 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
524 -- ids, we get (modulo int passing)
526 -- case (e `cast` CoT) `cast` CoS of
527 -- PairInt a b -> body [a,b]
529 -- The Ints passed around are just for creating fresh locals
530 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
531 unboxProduct i arg arg_ty body
534 result = mkUnpackCase the_id arg con_args boxing_con rhs
535 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
536 ([the_id], i') = mkLocals i [arg_ty]
537 (con_args, i'') = mkLocals i' tys
538 rhs = body i'' con_args
540 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
541 -- (mkUnpackCase x e args Con body)
543 -- case (e `cast` ...) of bndr { Con args -> body }
545 -- the type of the bndr passed in is irrelevent
546 mkUnpackCase bndr arg unpk_args boxing_con body
547 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
549 (cast_arg, bndr_ty) = go (idType bndr) arg
551 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
552 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
553 = go (newTyConInstRhs tycon tycon_args)
554 (unwrapNewTypeBody tycon tycon_args arg)
555 | otherwise = (arg, ty)
558 reboxProduct :: [Unique] -- uniques to create new local binders
559 -> Type -- type of product to box
560 -> ([Unique], -- remaining uniques
561 CoreExpr, -- boxed product
562 [Id]) -- Ids being boxed into product
565 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
567 us' = dropList con_arg_tys us
569 arg_ids = zipWith (mkSysLocal (fsLit "rb")) us con_arg_tys
571 bind_rhs = mkProductBox arg_ids ty
574 (us', bind_rhs, arg_ids)
576 mkProductBox :: [Id] -> Type -> CoreExpr
577 mkProductBox arg_ids ty
580 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
583 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
584 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
585 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
587 wrap expr = wrapNewTypeBody tycon tycon_args expr
590 -- (mkReboxingAlt us con xs rhs) basically constructs the case
591 -- alternative (con, xs, rhs)
592 -- but it does the reboxing necessary to construct the *source*
593 -- arguments, xs, from the representation arguments ys.
595 -- data T = MkT !(Int,Int) Bool
597 -- mkReboxingAlt MkT [x,b] r
598 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
600 -- mkDataAlt should really be in DataCon, but it can't because
601 -- it manipulates CoreSyn.
604 :: [Unique] -- Uniques for the new Ids
606 -> [Var] -- Source-level args, *including* all evidence vars
610 mkReboxingAlt us con args rhs
611 | not (any isMarkedUnboxed stricts)
612 = (DataAlt con, args, rhs)
616 (binds, args') = go args stricts us
618 (DataAlt con, args', mkLets binds rhs)
621 stricts = dataConExStricts con ++ dataConStrictMarks con
623 go [] _stricts _us = ([], [])
625 -- Type variable case
626 go (arg:args) stricts us
628 = let (binds, args') = go args stricts us
629 in (binds, arg:args')
631 -- Term variable case
632 go (arg:args) (str:stricts) us
633 | isMarkedUnboxed str
634 = let (binds, unpacked_args') = go args stricts us'
635 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
637 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
639 = let (binds, args') = go args stricts us
640 in (binds, arg:args')
641 go (_ : _) [] _ = panic "mkReboxingAlt"
645 %************************************************************************
647 Wrapping and unwrapping newtypes and type families
649 %************************************************************************
652 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
653 -- The wrapper for the data constructor for a newtype looks like this:
654 -- newtype T a = MkT (a,Int)
655 -- MkT :: forall a. (a,Int) -> T a
656 -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
657 -- where CoT is the coercion TyCon assoicated with the newtype
659 -- The call (wrapNewTypeBody T [a] e) returns the
660 -- body of the wrapper, namely
661 -- e `cast` (CoT [a])
663 -- If a coercion constructor is provided in the newtype, then we use
664 -- it, otherwise the wrap/unwrap are both no-ops
666 -- If the we are dealing with a newtype *instance*, we have a second coercion
667 -- identifying the family instance with the constructor of the newtype
668 -- instance. This coercion is applied in any case (ie, composed with the
669 -- coercion constructor of the newtype or applied by itself).
671 wrapNewTypeBody tycon args result_expr
672 = ASSERT( isNewTyCon tycon )
673 wrapFamInstBody tycon args $
674 mkCoerce (mkSymCo co) result_expr
676 co = mkAxInstCo (newTyConCo tycon) args
678 -- When unwrapping, we do *not* apply any family coercion, because this will
679 -- be done via a CoPat by the type checker. We have to do it this way as
680 -- computing the right type arguments for the coercion requires more than just
681 -- a spliting operation (cf, TcPat.tcConPat).
683 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
684 unwrapNewTypeBody tycon args result_expr
685 = ASSERT( isNewTyCon tycon )
686 mkCoerce (mkAxInstCo (newTyConCo tycon) args) result_expr
688 -- If the type constructor is a representation type of a data instance, wrap
689 -- the expression into a cast adjusting the expression type, which is an
690 -- instance of the representation type, to the corresponding instance of the
691 -- family instance type.
692 -- See Note [Wrappers for data instance tycons]
693 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
694 wrapFamInstBody tycon args body
695 | Just co_con <- tyConFamilyCoercion_maybe tycon
696 = mkCoerce (mkSymCo (mkAxInstCo co_con args)) body
700 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
701 unwrapFamInstScrut tycon args scrut
702 | Just co_con <- tyConFamilyCoercion_maybe tycon
703 = mkCoerce (mkAxInstCo co_con args) scrut
709 %************************************************************************
711 \subsection{Primitive operations}
713 %************************************************************************
716 mkPrimOpId :: PrimOp -> Id
720 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
721 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
722 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
723 (mkPrimOpIdUnique (primOpTag prim_op))
725 id = mkGlobalId (PrimOpId prim_op) name ty info
728 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
730 `setStrictnessInfo` Just strict_sig
732 -- For each ccall we manufacture a separate CCallOpId, giving it
733 -- a fresh unique, a type that is correct for this particular ccall,
734 -- and a CCall structure that gives the correct details about calling
737 -- The *name* of this Id is a local name whose OccName gives the full
738 -- details of the ccall, type and all. This means that the interface
739 -- file reader can reconstruct a suitable Id
741 mkFCallId :: Unique -> ForeignCall -> Type -> Id
742 mkFCallId uniq fcall ty
743 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
744 -- A CCallOpId should have no free type variables;
745 -- when doing substitutions won't substitute over it
746 mkGlobalId (FCallId fcall) name ty info
748 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
749 -- The "occurrence name" of a ccall is the full info about the
750 -- ccall; it is encoded, but may have embedded spaces etc!
752 name = mkFCallName uniq occ_str
756 `setStrictnessInfo` Just strict_sig
758 (_, tau) = tcSplitForAllTys ty
759 (arg_tys, _) = tcSplitFunTys tau
760 arity = length arg_tys
761 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
763 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
764 -- except for the type:
766 -- a plain HPC tick box has type (State# RealWorld)
767 -- a breakpoint Id has type forall a.a
769 -- The breakpoint Id will be applied to a list of arbitrary free variables,
770 -- which is why it needs a polymorphic type.
772 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
773 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
775 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
776 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
777 where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
779 mkTickBox' :: Unique -> Module -> TickBoxId -> Type -> Id
780 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info
782 tickbox = TickBox mod ix
783 occ_str = showSDoc (braces (ppr tickbox))
784 name = mkTickBoxOpName uniq occ_str
789 %************************************************************************
791 \subsection{DictFuns and default methods}
793 %************************************************************************
795 Important notes about dict funs and default methods
796 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
797 Dict funs and default methods are *not* ImplicitIds. Their definition
798 involves user-written code, so we can't figure out their strictness etc
799 based on fixed info, as we can for constructors and record selectors (say).
801 We build them as LocalIds, but with External Names. This ensures that
802 they are taken to account by free-variable finding and dependency
803 analysis (e.g. CoreFVs.exprFreeVars).
805 Why shouldn't they be bound as GlobalIds? Because, in particular, if
806 they are globals, the specialiser floats dict uses above their defns,
807 which prevents good simplifications happening. Also the strictness
808 analyser treats a occurrence of a GlobalId as imported and assumes it
809 contains strictness in its IdInfo, which isn't true if the thing is
810 bound in the same module as the occurrence.
812 It's OK for dfuns to be LocalIds, because we form the instance-env to
813 pass on to the next module (md_insts) in CoreTidy, afer tidying
814 and globalising the top-level Ids.
816 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
817 that they aren't discarded by the occurrence analyser.
820 mkDictFunId :: Name -- Name to use for the dict fun;
826 -- Implements the DFun Superclass Invariant (see TcInstDcls)
828 mkDictFunId dfun_name tvs theta clas tys
829 = mkExportedLocalVar (DFunId n_silent is_nt)
834 is_nt = isNewTyCon (classTyCon clas)
835 (n_silent, dfun_ty) = mkDictFunTy tvs theta clas tys
837 mkDictFunTy :: [TyVar] -> ThetaType -> Class -> [Type] -> (Int, Type)
838 mkDictFunTy tvs theta clas tys
839 = (length silent_theta, dfun_ty)
841 dfun_ty = mkSigmaTy tvs (silent_theta ++ theta) (mkDictTy clas tys)
842 silent_theta = filterOut discard $
843 substTheta (zipTopTvSubst (classTyVars clas) tys)
845 -- See Note [Silent Superclass Arguments]
846 discard pred = isEmptyVarSet (tyVarsOfPred pred)
847 || any (`eqPred` pred) theta
848 -- See the DFun Superclass Invariant in TcInstDcls
852 %************************************************************************
854 \subsection{Un-definable}
856 %************************************************************************
858 These Ids can't be defined in Haskell. They could be defined in
859 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
860 ensure that they were definitely, definitely inlined, because there is
861 no curried identifier for them. That's what mkCompulsoryUnfolding
862 does. If we had a way to get a compulsory unfolding from an interface
863 file, we could do that, but we don't right now.
865 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
866 just gets expanded into a type coercion wherever it occurs. Hence we
867 add it as a built-in Id with an unfolding here.
869 The type variables we use here are "open" type variables: this means
870 they can unify with both unlifted and lifted types. Hence we provide
871 another gun with which to shoot yourself in the foot.
874 lazyIdName, unsafeCoerceName, nullAddrName, seqName, realWorldName, coercionTokenName :: Name
875 unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
876 nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId
877 seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId
878 realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId
879 lazyIdName = mkWiredInIdName gHC_BASE (fsLit "lazy") lazyIdKey lazyId
880 coercionTokenName = mkWiredInIdName gHC_PRIM (fsLit "coercionToken#") coercionTokenIdKey coercionTokenId
884 ------------------------------------------------
885 -- unsafeCoerce# :: forall a b. a -> b
888 = pcMiscPrelId unsafeCoerceName ty info
890 info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma
891 `setUnfoldingInfo` mkCompulsoryUnfolding rhs
894 ty = mkForAllTys [argAlphaTyVar,openBetaTyVar]
895 (mkFunTy argAlphaTy openBetaTy)
896 [x] = mkTemplateLocals [argAlphaTy]
897 rhs = mkLams [argAlphaTyVar,openBetaTyVar,x] $
898 Cast (Var x) (mkUnsafeCo argAlphaTy openBetaTy)
900 ------------------------------------------------
902 -- nullAddr# :: Addr#
903 -- The reason is is here is because we don't provide
904 -- a way to write this literal in Haskell.
905 nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info
907 info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma
908 `setUnfoldingInfo` mkCompulsoryUnfolding (Lit nullAddrLit)
910 ------------------------------------------------
911 seqId :: Id -- See Note [seqId magic]
912 seqId = pcMiscPrelId seqName ty info
914 info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma
915 `setUnfoldingInfo` mkCompulsoryUnfolding rhs
916 `setSpecInfo` mkSpecInfo [seq_cast_rule]
919 ty = mkForAllTys [alphaTyVar,argBetaTyVar]
920 (mkFunTy alphaTy (mkFunTy argBetaTy argBetaTy))
921 [x,y] = mkTemplateLocals [alphaTy, argBetaTy]
922 rhs = mkLams [alphaTyVar,argBetaTyVar,x,y] (Case (Var x) x argBetaTy [(DEFAULT, [], Var y)])
924 -- See Note [Built-in RULES for seq]
925 seq_cast_rule = BuiltinRule { ru_name = fsLit "seq of cast"
928 , ru_try = match_seq_of_cast
931 match_seq_of_cast :: IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
932 -- See Note [Built-in RULES for seq]
933 match_seq_of_cast _ [Type _, Type res_ty, Cast scrut co, expr]
934 = Just (Var seqId `mkApps` [Type (pFst (coercionKind co)), Type res_ty,
936 match_seq_of_cast _ _ = Nothing
938 ------------------------------------------------
939 lazyId :: Id -- See Note [lazyId magic]
940 lazyId = pcMiscPrelId lazyIdName ty info
943 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
948 'GHC.Prim.seq' is special in several ways.
950 a) Its second arg can have an unboxed type
953 b) Its fixity is set in LoadIface.ghcPrimIface
955 c) It has quite a bit of desugaring magic.
956 See DsUtils.lhs Note [Desugaring seq (1)] and (2) and (3)
958 d) There is some special rule handing: Note [User-defined RULES for seq]
960 e) See Note [Typing rule for seq] in TcExpr.
962 Note [User-defined RULES for seq]
963 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
964 Roman found situations where he had
966 where he knew that f (which was strict in n) would terminate if n did.
967 Notice that the result of (f n) is discarded. So it makes sense to
971 Rather than attempt some general analysis to support this, I've added
972 enough support that you can do this using a rewrite rule:
974 RULE "f/seq" forall n. seq (f n) e = seq n e
976 You write that rule. When GHC sees a case expression that discards
977 its result, it mentally transforms it to a call to 'seq' and looks for
978 a RULE. (This is done in Simplify.rebuildCase.) As usual, the
979 correctness of the rule is up to you.
981 To make this work, we need to be careful that the magical desugaring
982 done in Note [seqId magic] item (c) is *not* done on the LHS of a rule.
983 Or rather, we arrange to un-do it, in DsBinds.decomposeRuleLhs.
985 Note [Built-in RULES for seq]
986 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
987 We also have the following built-in rule for seq
989 seq (x `cast` co) y = seq x y
991 This eliminates unnecessary casts and also allows other seq rules to
992 match more often. Notably,
994 seq (f x `cast` co) y --> seq (f x) y
996 and now a user-defined rule for seq (see Note [User-defined RULES for seq])
1002 lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
1004 Used to lazify pseq: pseq a b = a `seq` lazy b
1006 Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1007 not from GHC.Base.hi. This is important, because the strictness
1008 analyser will spot it as strict!
1010 Also no unfolding in lazyId: it gets "inlined" by a HACK in CorePrep.
1011 It's very important to do this inlining *after* unfoldings are exposed
1012 in the interface file. Otherwise, the unfolding for (say) pseq in the
1013 interface file will not mention 'lazy', so if we inline 'pseq' we'll totally
1014 miss the very thing that 'lazy' was there for in the first place.
1015 See Trac #3259 for a real world example.
1017 lazyId is defined in GHC.Base, so we don't *have* to inline it. If it
1018 appears un-applied, we'll end up just calling it.
1020 -------------------------------------------------------------
1021 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1022 nasty as-is, change it back to a literal (@Literal@).
1024 voidArgId is a Local Id used simply as an argument in functions
1025 where we just want an arg to avoid having a thunk of unlifted type.
1027 x = \ void :: State# RealWorld -> (# p, q #)
1029 This comes up in strictness analysis
1032 realWorldPrimId :: Id
1033 realWorldPrimId -- :: State# RealWorld
1034 = pcMiscPrelId realWorldName realWorldStatePrimTy
1035 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1036 -- The evaldUnfolding makes it look that realWorld# is evaluated
1037 -- which in turn makes Simplify.interestingArg return True,
1038 -- which in turn makes INLINE things applied to realWorld# likely
1042 voidArgId -- :: State# RealWorld
1043 = mkSysLocal (fsLit "void") voidArgIdKey realWorldStatePrimTy
1045 coercionTokenId :: Id -- :: () ~ ()
1046 coercionTokenId -- Used to replace Coercion terms when we go to STG
1047 = pcMiscPrelId coercionTokenName
1048 (mkTyConApp eqPredPrimTyCon [unitTy, unitTy])
1054 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1055 pcMiscPrelId name ty info
1056 = mkVanillaGlobalWithInfo name ty info
1057 -- We lie and say the thing is imported; otherwise, we get into
1058 -- a mess with dependency analysis; e.g., core2stg may heave in
1059 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1060 -- being compiled, then it's just a matter of luck if the definition
1061 -- will be in "the right place" to be in scope.