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, mkDefaultMethodId,
20 mkPrimOpId, mkFCallId, mkTickBoxOpId, mkBreakPointOpId,
22 mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
23 wrapFamInstBody, unwrapFamInstScrut,
24 mkUnpackCase, mkProductBox,
26 -- And some particular Ids; see below for why they are wired in
27 wiredInIds, ghcPrimIds,
28 unsafeCoerceName, unsafeCoerceId, realWorldPrimId,
29 voidArgId, nullAddrId, seqId, lazyId, lazyIdKey
32 #include "HsVersions.h"
41 import CoreUtils ( exprType, mkCoerce )
52 import Var ( Var, TyVar, mkCoVar, mkExportedLocalVar )
58 import BasicTypes hiding ( SuccessFlag(..) )
66 %************************************************************************
68 \subsection{Wired in Ids}
70 %************************************************************************
74 There are several reasons why an Id might appear in the wiredInIds:
76 (1) The ghcPrimIds are wired in because they can't be defined in
77 Haskell at all, although the can be defined in Core. They have
78 compulsory unfoldings, so they are always inlined and they have
79 no definition site. Their home module is GHC.Prim, so they
80 also have a description in primops.txt.pp, where they are called
83 (2) The 'error' function, eRROR_ID, is wired in because we don't yet have
84 a way to express in an interface file that the result type variable
85 is 'open'; that is can be unified with an unboxed type
87 [The interface file format now carry such information, but there's
88 no way yet of expressing at the definition site for these
89 error-reporting functions that they have an 'open'
90 result type. -- sof 1/99]
92 (3) Other error functions (rUNTIME_ERROR_ID) are wired in (a) because
93 the desugarer generates code that mentiones them directly, and
94 (b) for the same reason as eRROR_ID
96 (4) lazyId is wired in because the wired-in version overrides the
97 strictness of the version defined in GHC.Base
99 In cases (2-4), the function has a definition in a library module, and
100 can be called; but the wired-in version means that the details are
101 never read from that module's interface file; instead, the full definition
108 ++ errorIds -- Defined in MkCore
111 -- These Ids are exported from GHC.Prim
114 = [ -- These can't be defined in Haskell, but they have
115 -- perfectly reasonable unfoldings in Core
123 %************************************************************************
125 \subsection{Data constructors}
127 %************************************************************************
129 The wrapper for a constructor is an ordinary top-level binding that evaluates
130 any strict args, unboxes any args that are going to be flattened, and calls
133 We're going to build a constructor that looks like:
135 data (Data a, C b) => T a b = T1 !a !Int b
138 \d1::Data a, d2::C b ->
139 \p q r -> case p of { p ->
141 Con T1 [a,b] [p,q,r]}}
145 * d2 is thrown away --- a context in a data decl is used to make sure
146 one *could* construct dictionaries at the site the constructor
147 is used, but the dictionary isn't actually used.
149 * We have to check that we can construct Data dictionaries for
150 the types a and Int. Once we've done that we can throw d1 away too.
152 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
153 all that matters is that the arguments are evaluated. "seq" is
154 very careful to preserve evaluation order, which we don't need
157 You might think that we could simply give constructors some strictness
158 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
159 But we don't do that because in the case of primops and functions strictness
160 is a *property* not a *requirement*. In the case of constructors we need to
161 do something active to evaluate the argument.
163 Making an explicit case expression allows the simplifier to eliminate
164 it in the (common) case where the constructor arg is already evaluated.
166 Note [Wrappers for data instance tycons]
167 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
168 In the case of data instances, the wrapper also applies the coercion turning
169 the representation type into the family instance type to cast the result of
170 the wrapper. For example, consider the declarations
172 data family Map k :: * -> *
173 data instance Map (a, b) v = MapPair (Map a (Pair b v))
175 The tycon to which the datacon MapPair belongs gets a unique internal
176 name of the form :R123Map, and we call it the representation tycon.
177 In contrast, Map is the family tycon (accessible via
178 tyConFamInst_maybe). A coercion allows you to move between
179 representation and family type. It is accessible from :R123Map via
180 tyConFamilyCoercion_maybe and has kind
182 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
184 The wrapper and worker of MapPair get the types
187 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
188 $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v)
191 MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
193 This coercion is conditionally applied by wrapFamInstBody.
195 It's a bit more complicated if the data instance is a GADT as well!
197 data instance T [a] where
198 T1 :: forall b. b -> T [Maybe b]
200 Hence we translate to
203 $WT1 :: forall b. b -> T [Maybe b]
204 $WT1 b v = T1 (Maybe b) b (Maybe b) v
205 `cast` sym (Co7T (Maybe b))
208 T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
210 -- Coercion from family type to representation type
211 Co7T a :: T [a] ~ :R7T a
214 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
215 mkDataConIds wrap_name wkr_name data_con
216 | isNewTyCon tycon -- Newtype, only has a worker
217 = DCIds Nothing nt_work_id
219 | any isBanged all_strict_marks -- Algebraic, needs wrapper
220 || not (null eq_spec) -- NB: LoadIface.ifaceDeclSubBndrs
221 || isFamInstTyCon tycon -- depends on this test
222 = DCIds (Just alg_wrap_id) wrk_id
224 | otherwise -- Algebraic, no wrapper
225 = DCIds Nothing wrk_id
227 (univ_tvs, ex_tvs, eq_spec,
228 eq_theta, dict_theta, orig_arg_tys, res_ty) = dataConFullSig data_con
229 tycon = dataConTyCon data_con -- The representation TyCon (not family)
231 ----------- Worker (algebraic data types only) --------------
232 -- The *worker* for the data constructor is the function that
233 -- takes the representation arguments and builds the constructor.
234 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
235 (dataConRepType data_con) wkr_info
237 wkr_arity = dataConRepArity data_con
238 wkr_info = noCafIdInfo
239 `setArityInfo` wkr_arity
240 `setStrictnessInfo` Just wkr_sig
241 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
244 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
245 -- Note [Data-con worker strictness]
246 -- Notice that we do *not* say the worker is strict
247 -- even if the data constructor is declared strict
248 -- e.g. data T = MkT !(Int,Int)
249 -- Why? Because the *wrapper* is strict (and its unfolding has case
250 -- expresssions that do the evals) but the *worker* itself is not.
251 -- If we pretend it is strict then when we see
252 -- case x of y -> $wMkT y
253 -- the simplifier thinks that y is "sure to be evaluated" (because
254 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
256 -- When the simplifer sees a pattern
257 -- case e of MkT x -> ...
258 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
259 -- but that's fine... dataConRepStrictness comes from the data con
260 -- not from the worker Id.
262 cpr_info | isProductTyCon tycon &&
265 wkr_arity <= mAX_CPR_SIZE = retCPR
267 -- RetCPR is only true for products that are real data types;
268 -- that is, not unboxed tuples or [non-recursive] newtypes
270 ----------- Workers for newtypes --------------
271 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
272 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
273 `setArityInfo` 1 -- Arity 1
274 `setUnfoldingInfo` newtype_unf
275 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
276 newtype_unf = ASSERT2( isVanillaDataCon data_con &&
277 isSingleton orig_arg_tys, ppr data_con )
278 -- Note [Newtype datacons]
279 mkCompulsoryUnfolding $
280 mkLams wrap_tvs $ Lam id_arg1 $
281 wrapNewTypeBody tycon res_ty_args (Var id_arg1)
284 ----------- Wrapper --------------
285 -- We used to include the stupid theta in the wrapper's args
286 -- but now we don't. Instead the type checker just injects these
287 -- extra constraints where necessary.
288 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
289 res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
290 eq_tys = mkPredTys eq_theta
291 dict_tys = mkPredTys dict_theta
292 wrap_ty = mkForAllTys wrap_tvs $ mkFunTys eq_tys $ mkFunTys dict_tys $
293 mkFunTys orig_arg_tys $ res_ty
294 -- NB: watch out here if you allow user-written equality
295 -- constraints in data constructor signatures
297 ----------- Wrappers for algebraic data types --------------
298 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
299 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
300 `setArityInfo` wrap_arity
301 -- It's important to specify the arity, so that partial
302 -- applications are treated as values
303 `setUnfoldingInfo` wrap_unf
304 `setStrictnessInfo` Just wrap_sig
306 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
307 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
308 arg_dmds = map mk_dmd all_strict_marks
309 mk_dmd str | isBanged str = evalDmd
310 | otherwise = lazyDmd
311 -- The Cpr info can be important inside INLINE rhss, where the
312 -- wrapper constructor isn't inlined.
313 -- And the argument strictness can be important too; we
314 -- may not inline a contructor when it is partially applied.
316 -- data W = C !Int !Int !Int
317 -- ...(let w = C x in ...(w p q)...)...
318 -- we want to see that w is strict in its two arguments
320 wrap_unf = mkInlineUnfolding (Just (length dict_args + length id_args)) wrap_rhs
321 wrap_rhs = mkLams wrap_tvs $
323 mkLams dict_args $ mkLams id_args $
324 foldr mk_case con_app
325 (zip (dict_args ++ id_args) all_strict_marks)
328 con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
329 Var wrk_id `mkTyApps` res_ty_args
331 -- Equality evidence:
332 `mkTyApps` map snd eq_spec
334 `mkVarApps` reverse rep_ids
336 (dict_args,i2) = mkLocals 1 dict_tys
337 (id_args,i3) = mkLocals i2 orig_arg_tys
339 (eq_args,_) = mkCoVarLocals i3 eq_tys
341 mkCoVarLocals i [] = ([],i)
342 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
343 y = mkCoVar (mkSysTvName (mkBuiltinUnique i)
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 = base_info `setSpecInfo` mkSpecInfo [rule]
445 `setInlinePragInfo` neverInlinePragma
446 -- Add a magic BuiltinRule, and never inline it
447 -- so that the rule is always available to fire.
448 -- See Note [ClassOp/DFun selection] in TcInstDcls
450 n_ty_args = length tyvars
452 -- This is the built-in rule that goes
453 -- op (dfT d1 d2) ---> opT d1 d2
454 rule = BuiltinRule { ru_name = fsLit "Class op " `appendFS`
455 occNameFS (getOccName name)
457 , ru_nargs = n_ty_args + 1
458 , ru_try = dictSelRule val_index n_ty_args n_eq_args }
460 -- The strictness signature is of the form U(AAAVAAAA) -> T
461 -- where the V depends on which item we are selecting
462 -- It's worth giving one, so that absence info etc is generated
463 -- even if the selector isn't inlined
464 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
465 arg_dmd | new_tycon = evalDmd
466 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
469 tycon = classTyCon clas
470 new_tycon = isNewTyCon tycon
471 [data_con] = tyConDataCons tycon
472 tyvars = dataConUnivTyVars data_con
473 arg_tys = dataConRepArgTys data_con -- Includes the dictionary superclasses
474 eq_theta = dataConEqTheta data_con
475 n_eq_args = length eq_theta
477 -- 'index' is a 0-index into the *value* arguments of the dictionary
478 val_index = assoc "MkId.mkDictSelId" sel_index_prs name
479 sel_index_prs = map idName (classAllSelIds clas) `zip` [0..]
481 the_arg_id = arg_ids !! val_index
482 pred = mkClassPred clas (mkTyVarTys tyvars)
483 dict_id = mkTemplateLocal 1 $ mkPredTy pred
484 arg_ids = mkTemplateLocalsNum 2 arg_tys
485 eq_ids = map mkWildEvBinder eq_theta
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, eq_ids ++ arg_ids, Var the_arg_id)]
492 dictSelRule :: Int -> Arity -> Arity
493 -> IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
495 -- sel_i t1..tk (df s1..sn d1..dm) = op_i_helper s1..sn d1..dm
496 -- sel_i t1..tk (D t1..tk op1 ... opm) = opi
498 -- NB: the data constructor has the same number of type and
499 -- coercion args as the selector
501 -- This only works for *value* superclasses
502 -- There are no selector functions for equality superclasses
503 dictSelRule val_index n_ty_args n_eq_args id_unf args
504 | (dict_arg : _) <- drop n_ty_args args
505 , Just (_, _, con_args) <- exprIsConApp_maybe id_unf dict_arg
506 , let val_args = drop n_eq_args con_args
507 = Just (val_args !! val_index)
513 %************************************************************************
517 %************************************************************************
520 -- unbox a product type...
521 -- we will recurse into newtypes, casting along the way, and unbox at the
522 -- first product data constructor we find. e.g.
524 -- data PairInt = PairInt Int Int
525 -- newtype S = MkS PairInt
528 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
529 -- ids, we get (modulo int passing)
531 -- case (e `cast` CoT) `cast` CoS of
532 -- PairInt a b -> body [a,b]
534 -- The Ints passed around are just for creating fresh locals
535 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
536 unboxProduct i arg arg_ty body
539 result = mkUnpackCase the_id arg con_args boxing_con rhs
540 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
541 ([the_id], i') = mkLocals i [arg_ty]
542 (con_args, i'') = mkLocals i' tys
543 rhs = body i'' con_args
545 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
546 -- (mkUnpackCase x e args Con body)
548 -- case (e `cast` ...) of bndr { Con args -> body }
550 -- the type of the bndr passed in is irrelevent
551 mkUnpackCase bndr arg unpk_args boxing_con body
552 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
554 (cast_arg, bndr_ty) = go (idType bndr) arg
556 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
557 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
558 = go (newTyConInstRhs tycon tycon_args)
559 (unwrapNewTypeBody tycon tycon_args arg)
560 | otherwise = (arg, ty)
563 reboxProduct :: [Unique] -- uniques to create new local binders
564 -> Type -- type of product to box
565 -> ([Unique], -- remaining uniques
566 CoreExpr, -- boxed product
567 [Id]) -- Ids being boxed into product
570 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
572 us' = dropList con_arg_tys us
574 arg_ids = zipWith (mkSysLocal (fsLit "rb")) us con_arg_tys
576 bind_rhs = mkProductBox arg_ids ty
579 (us', bind_rhs, arg_ids)
581 mkProductBox :: [Id] -> Type -> CoreExpr
582 mkProductBox arg_ids ty
585 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
588 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
589 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
590 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
592 wrap expr = wrapNewTypeBody tycon tycon_args expr
595 -- (mkReboxingAlt us con xs rhs) basically constructs the case
596 -- alternative (con, xs, rhs)
597 -- but it does the reboxing necessary to construct the *source*
598 -- arguments, xs, from the representation arguments ys.
600 -- data T = MkT !(Int,Int) Bool
602 -- mkReboxingAlt MkT [x,b] r
603 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
605 -- mkDataAlt should really be in DataCon, but it can't because
606 -- it manipulates CoreSyn.
609 :: [Unique] -- Uniques for the new Ids
611 -> [Var] -- Source-level args, including existential dicts
615 mkReboxingAlt us con args rhs
616 | not (any isMarkedUnboxed stricts)
617 = (DataAlt con, args, rhs)
621 (binds, args') = go args stricts us
623 (DataAlt con, args', mkLets binds rhs)
626 stricts = dataConExStricts con ++ dataConStrictMarks con
628 go [] _stricts _us = ([], [])
630 -- Type variable case
631 go (arg:args) stricts us
633 = let (binds, args') = go args stricts us
634 in (binds, arg:args')
636 -- Term variable case
637 go (arg:args) (str:stricts) us
638 | isMarkedUnboxed str
640 let (binds, unpacked_args') = go args stricts us'
641 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
643 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
645 = let (binds, args') = go args stricts us
646 in (binds, arg:args')
647 go (_ : _) [] _ = panic "mkReboxingAlt"
651 %************************************************************************
653 Wrapping and unwrapping newtypes and type families
655 %************************************************************************
658 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
659 -- The wrapper for the data constructor for a newtype looks like this:
660 -- newtype T a = MkT (a,Int)
661 -- MkT :: forall a. (a,Int) -> T a
662 -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
663 -- where CoT is the coercion TyCon assoicated with the newtype
665 -- The call (wrapNewTypeBody T [a] e) returns the
666 -- body of the wrapper, namely
667 -- e `cast` (CoT [a])
669 -- If a coercion constructor is provided in the newtype, then we use
670 -- it, otherwise the wrap/unwrap are both no-ops
672 -- If the we are dealing with a newtype *instance*, we have a second coercion
673 -- identifying the family instance with the constructor of the newtype
674 -- instance. This coercion is applied in any case (ie, composed with the
675 -- coercion constructor of the newtype or applied by itself).
677 wrapNewTypeBody tycon args result_expr
678 = wrapFamInstBody tycon args inner
681 | Just co_con <- newTyConCo_maybe tycon
682 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
686 -- When unwrapping, we do *not* apply any family coercion, because this will
687 -- be done via a CoPat by the type checker. We have to do it this way as
688 -- computing the right type arguments for the coercion requires more than just
689 -- a spliting operation (cf, TcPat.tcConPat).
691 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
692 unwrapNewTypeBody tycon args result_expr
693 | Just co_con <- newTyConCo_maybe tycon
694 = mkCoerce (mkTyConApp co_con args) result_expr
698 -- If the type constructor is a representation type of a data instance, wrap
699 -- the expression into a cast adjusting the expression type, which is an
700 -- instance of the representation type, to the corresponding instance of the
701 -- family instance type.
702 -- See Note [Wrappers for data instance tycons]
703 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
704 wrapFamInstBody tycon args body
705 | Just co_con <- tyConFamilyCoercion_maybe tycon
706 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
710 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
711 unwrapFamInstScrut tycon args scrut
712 | Just co_con <- tyConFamilyCoercion_maybe tycon
713 = mkCoerce (mkTyConApp co_con args) scrut
719 %************************************************************************
721 \subsection{Primitive operations}
723 %************************************************************************
726 mkPrimOpId :: PrimOp -> Id
730 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
731 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
732 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
733 (mkPrimOpIdUnique (primOpTag prim_op))
735 id = mkGlobalId (PrimOpId prim_op) name ty info
738 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
740 `setStrictnessInfo` Just strict_sig
742 -- For each ccall we manufacture a separate CCallOpId, giving it
743 -- a fresh unique, a type that is correct for this particular ccall,
744 -- and a CCall structure that gives the correct details about calling
747 -- The *name* of this Id is a local name whose OccName gives the full
748 -- details of the ccall, type and all. This means that the interface
749 -- file reader can reconstruct a suitable Id
751 mkFCallId :: Unique -> ForeignCall -> Type -> Id
752 mkFCallId uniq fcall ty
753 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
754 -- A CCallOpId should have no free type variables;
755 -- when doing substitutions won't substitute over it
756 mkGlobalId (FCallId fcall) name ty info
758 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
759 -- The "occurrence name" of a ccall is the full info about the
760 -- ccall; it is encoded, but may have embedded spaces etc!
762 name = mkFCallName uniq occ_str
766 `setStrictnessInfo` Just strict_sig
768 (_, tau) = tcSplitForAllTys ty
769 (arg_tys, _) = tcSplitFunTys tau
770 arity = length arg_tys
771 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
773 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
774 -- except for the type:
776 -- a plain HPC tick box has type (State# RealWorld)
777 -- a breakpoint Id has type forall a.a
779 -- The breakpoint Id will be applied to a list of arbitrary free variables,
780 -- which is why it needs a polymorphic type.
782 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
783 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
785 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
786 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
787 where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
789 mkTickBox' :: Unique -> Module -> TickBoxId -> Type -> Id
790 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info
792 tickbox = TickBox mod ix
793 occ_str = showSDoc (braces (ppr tickbox))
794 name = mkTickBoxOpName uniq occ_str
799 %************************************************************************
801 \subsection{DictFuns and default methods}
803 %************************************************************************
805 Important notes about dict funs and default methods
806 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
807 Dict funs and default methods are *not* ImplicitIds. Their definition
808 involves user-written code, so we can't figure out their strictness etc
809 based on fixed info, as we can for constructors and record selectors (say).
811 We build them as LocalIds, but with External Names. This ensures that
812 they are taken to account by free-variable finding and dependency
813 analysis (e.g. CoreFVs.exprFreeVars).
815 Why shouldn't they be bound as GlobalIds? Because, in particular, if
816 they are globals, the specialiser floats dict uses above their defns,
817 which prevents good simplifications happening. Also the strictness
818 analyser treats a occurrence of a GlobalId as imported and assumes it
819 contains strictness in its IdInfo, which isn't true if the thing is
820 bound in the same module as the occurrence.
822 It's OK for dfuns to be LocalIds, because we form the instance-env to
823 pass on to the next module (md_insts) in CoreTidy, afer tidying
824 and globalising the top-level Ids.
826 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
827 that they aren't discarded by the occurrence analyser.
830 mkDefaultMethodId :: Id -- Selector Id
831 -> Name -- Default method name
832 -> Id -- Default method Id
833 mkDefaultMethodId sel_id dm_name = mkExportedLocalId dm_name (idType sel_id)
835 mkDictFunId :: Name -- Name to use for the dict fun;
842 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
843 = mkExportedLocalVar (DFunId is_nt) dfun_name dfun_ty vanillaIdInfo
845 is_nt = isNewTyCon (classTyCon clas)
846 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
850 %************************************************************************
852 \subsection{Un-definable}
854 %************************************************************************
856 These Ids can't be defined in Haskell. They could be defined in
857 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
858 ensure that they were definitely, definitely inlined, because there is
859 no curried identifier for them. That's what mkCompulsoryUnfolding
860 does. If we had a way to get a compulsory unfolding from an interface
861 file, we could do that, but we don't right now.
863 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
864 just gets expanded into a type coercion wherever it occurs. Hence we
865 add it as a built-in Id with an unfolding here.
867 The type variables we use here are "open" type variables: this means
868 they can unify with both unlifted and lifted types. Hence we provide
869 another gun with which to shoot yourself in the foot.
872 lazyIdName, unsafeCoerceName, nullAddrName, seqName, realWorldName :: Name
873 unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
874 nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId
875 seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId
876 realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId
877 lazyIdName = mkWiredInIdName gHC_BASE (fsLit "lazy") lazyIdKey lazyId
881 ------------------------------------------------
882 -- unsafeCoerce# :: forall a b. a -> b
885 = pcMiscPrelId unsafeCoerceName ty info
887 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
890 ty = mkForAllTys [argAlphaTyVar,openBetaTyVar]
891 (mkFunTy argAlphaTy openBetaTy)
892 [x] = mkTemplateLocals [argAlphaTy]
893 rhs = mkLams [argAlphaTyVar,openBetaTyVar,x] $
894 Cast (Var x) (mkUnsafeCoercion argAlphaTy openBetaTy)
896 ------------------------------------------------
898 -- nullAddr# :: Addr#
899 -- The reason is is here is because we don't provide
900 -- a way to write this literal in Haskell.
901 nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info
903 info = noCafIdInfo `setUnfoldingInfo`
904 mkCompulsoryUnfolding (Lit nullAddrLit)
906 ------------------------------------------------
907 seqId :: Id -- See Note [seqId magic]
908 seqId = pcMiscPrelId seqName ty info
910 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
911 `setSpecInfo` mkSpecInfo [seq_cast_rule]
914 ty = mkForAllTys [alphaTyVar,argBetaTyVar]
915 (mkFunTy alphaTy (mkFunTy argBetaTy argBetaTy))
916 [x,y] = mkTemplateLocals [alphaTy, argBetaTy]
917 rhs = mkLams [alphaTyVar,argBetaTyVar,x,y] (Case (Var x) x argBetaTy [(DEFAULT, [], Var y)])
919 -- See Note [Built-in RULES for seq]
920 seq_cast_rule = BuiltinRule { ru_name = fsLit "seq of cast"
923 , ru_try = match_seq_of_cast
926 match_seq_of_cast :: IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
927 -- See Note [Built-in RULES for seq]
928 match_seq_of_cast _ [Type _, Type res_ty, Cast scrut co, expr]
929 = Just (Var seqId `mkApps` [Type (fst (coercionKind co)), Type res_ty,
931 match_seq_of_cast _ _ = Nothing
933 ------------------------------------------------
934 lazyId :: Id -- See Note [lazyId magic]
935 lazyId = pcMiscPrelId lazyIdName ty info
938 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
943 'GHC.Prim.seq' is special in several ways.
945 a) Its second arg can have an unboxed type
948 b) Its fixity is set in LoadIface.ghcPrimIface
950 c) It has quite a bit of desugaring magic.
951 See DsUtils.lhs Note [Desugaring seq (1)] and (2) and (3)
953 d) There is some special rule handing: Note [User-defined RULES for seq]
955 e) See Note [Typing rule for seq] in TcExpr.
957 Note [User-defined RULES for seq]
958 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
959 Roman found situations where he had
961 where he knew that f (which was strict in n) would terminate if n did.
962 Notice that the result of (f n) is discarded. So it makes sense to
966 Rather than attempt some general analysis to support this, I've added
967 enough support that you can do this using a rewrite rule:
969 RULE "f/seq" forall n. seq (f n) e = seq n e
971 You write that rule. When GHC sees a case expression that discards
972 its result, it mentally transforms it to a call to 'seq' and looks for
973 a RULE. (This is done in Simplify.rebuildCase.) As usual, the
974 correctness of the rule is up to you.
976 To make this work, we need to be careful that the magical desugaring
977 done in Note [seqId magic] item (c) is *not* done on the LHS of a rule.
978 Or rather, we arrange to un-do it, in DsBinds.decomposeRuleLhs.
980 Note [Built-in RULES for seq]
981 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
982 We also have the following built-in rule for seq
984 seq (x `cast` co) y = seq x y
986 This eliminates unnecessary casts and also allows other seq rules to
987 match more often. Notably,
989 seq (f x `cast` co) y --> seq (f x) y
991 and now a user-defined rule for seq (see Note [User-defined RULES for seq])
997 lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
999 Used to lazify pseq: pseq a b = a `seq` lazy b
1001 Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1002 not from GHC.Base.hi. This is important, because the strictness
1003 analyser will spot it as strict!
1005 Also no unfolding in lazyId: it gets "inlined" by a HACK in CorePrep.
1006 It's very important to do this inlining *after* unfoldings are exposed
1007 in the interface file. Otherwise, the unfolding for (say) pseq in the
1008 interface file will not mention 'lazy', so if we inline 'pseq' we'll totally
1009 miss the very thing that 'lazy' was there for in the first place.
1010 See Trac #3259 for a real world example.
1012 lazyId is defined in GHC.Base, so we don't *have* to inline it. If it
1013 appears un-applied, we'll end up just calling it.
1015 -------------------------------------------------------------
1016 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1017 nasty as-is, change it back to a literal (@Literal@).
1019 voidArgId is a Local Id used simply as an argument in functions
1020 where we just want an arg to avoid having a thunk of unlifted type.
1022 x = \ void :: State# RealWorld -> (# p, q #)
1024 This comes up in strictness analysis
1027 realWorldPrimId :: Id
1028 realWorldPrimId -- :: State# RealWorld
1029 = pcMiscPrelId realWorldName realWorldStatePrimTy
1030 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1031 -- The evaldUnfolding makes it look that realWorld# is evaluated
1032 -- which in turn makes Simplify.interestingArg return True,
1033 -- which in turn makes INLINE things applied to realWorld# likely
1037 voidArgId -- :: State# RealWorld
1038 = mkSysLocal (fsLit "void") voidArgIdKey realWorldStatePrimTy
1043 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1044 pcMiscPrelId name ty info
1045 = mkVanillaGlobalWithInfo name ty info
1046 -- We lie and say the thing is imported; otherwise, we get into
1047 -- a mess with dependency analysis; e.g., core2stg may heave in
1048 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1049 -- being compiled, then it's just a matter of luck if the definition
1050 -- will be in "the right place" to be in scope.