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
15 {-# OPTIONS -fno-warn-missing-signatures #-}
16 -- The above warning supression flag is a temporary kludge.
17 -- While working on this module you are encouraged to remove it and fix
18 -- any warnings in the module. See
19 -- <http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings>
23 mkDictFunId, mkDefaultMethodId,
27 mkPrimOpId, mkFCallId, mkTickBoxOpId, mkBreakPointOpId,
29 mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
30 wrapFamInstBody, unwrapFamInstScrut,
31 mkUnpackCase, mkProductBox,
33 -- And some particular Ids; see below for why they are wired in
34 wiredInIds, ghcPrimIds,
35 unsafeCoerceId, realWorldPrimId, voidArgId, nullAddrId, seqId,
38 mkRuntimeErrorApp, mkImpossibleExpr,
39 rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
40 nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
41 pAT_ERROR_ID, eRROR_ID, rEC_SEL_ERROR_ID,
46 #include "HsVersions.h"
55 import CoreUtils ( exprType, mkCoerce )
66 import Var ( Var, TyVar, mkCoVar, mkExportedLocalVar )
72 import BasicTypes hiding ( SuccessFlag(..) )
80 %************************************************************************
82 \subsection{Wired in Ids}
84 %************************************************************************
88 There are several reasons why an Id might appear in the wiredInIds:
90 (1) The ghcPrimIds are wired in because they can't be defined in
91 Haskell at all, although the can be defined in Core. They have
92 compulsory unfoldings, so they are always inlined and they have
93 no definition site. Their home module is GHC.Prim, so they
94 also have a description in primops.txt.pp, where they are called
97 (2) The 'error' function, eRROR_ID, is wired in because we don't yet have
98 a way to express in an interface file that the result type variable
99 is 'open'; that is can be unified with an unboxed type
101 [The interface file format now carry such information, but there's
102 no way yet of expressing at the definition site for these
103 error-reporting functions that they have an 'open'
104 result type. -- sof 1/99]
106 (3) Other error functions (rUNTIME_ERROR_ID) are wired in (a) because
107 the desugarer generates code that mentiones them directly, and
108 (b) for the same reason as eRROR_ID
110 (4) lazyId is wired in because the wired-in version overrides the
111 strictness of the version defined in GHC.Base
113 In cases (2-4), the function has a definition in a library module, and
114 can be called; but the wired-in version means that the details are
115 never read from that module's interface file; instead, the full definition
123 eRROR_ID, -- This one isn't used anywhere else in the compiler
124 -- But we still need it in wiredInIds so that when GHC
125 -- compiles a program that mentions 'error' we don't
126 -- import its type from the interface file; we just get
127 -- the Id defined here. Which has an 'open-tyvar' type.
130 iRREFUT_PAT_ERROR_ID,
131 nON_EXHAUSTIVE_GUARDS_ERROR_ID,
132 nO_METHOD_BINDING_ERROR_ID,
140 -- These Ids are exported from GHC.Prim
143 = [ -- These can't be defined in Haskell, but they have
144 -- perfectly reasonable unfoldings in Core
152 %************************************************************************
154 \subsection{Data constructors}
156 %************************************************************************
158 The wrapper for a constructor is an ordinary top-level binding that evaluates
159 any strict args, unboxes any args that are going to be flattened, and calls
162 We're going to build a constructor that looks like:
164 data (Data a, C b) => T a b = T1 !a !Int b
167 \d1::Data a, d2::C b ->
168 \p q r -> case p of { p ->
170 Con T1 [a,b] [p,q,r]}}
174 * d2 is thrown away --- a context in a data decl is used to make sure
175 one *could* construct dictionaries at the site the constructor
176 is used, but the dictionary isn't actually used.
178 * We have to check that we can construct Data dictionaries for
179 the types a and Int. Once we've done that we can throw d1 away too.
181 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
182 all that matters is that the arguments are evaluated. "seq" is
183 very careful to preserve evaluation order, which we don't need
186 You might think that we could simply give constructors some strictness
187 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
188 But we don't do that because in the case of primops and functions strictness
189 is a *property* not a *requirement*. In the case of constructors we need to
190 do something active to evaluate the argument.
192 Making an explicit case expression allows the simplifier to eliminate
193 it in the (common) case where the constructor arg is already evaluated.
195 Note [Wrappers for data instance tycons]
196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
197 In the case of data instances, the wrapper also applies the coercion turning
198 the representation type into the family instance type to cast the result of
199 the wrapper. For example, consider the declarations
201 data family Map k :: * -> *
202 data instance Map (a, b) v = MapPair (Map a (Pair b v))
204 The tycon to which the datacon MapPair belongs gets a unique internal
205 name of the form :R123Map, and we call it the representation tycon.
206 In contrast, Map is the family tycon (accessible via
207 tyConFamInst_maybe). A coercion allows you to move between
208 representation and family type. It is accessible from :R123Map via
209 tyConFamilyCoercion_maybe and has kind
211 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
213 The wrapper and worker of MapPair get the types
216 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
217 $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v)
220 MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
222 This coercion is conditionally applied by wrapFamInstBody.
224 It's a bit more complicated if the data instance is a GADT as well!
226 data instance T [a] where
227 T1 :: forall b. b -> T [Maybe b]
229 Co7T a :: T [a] ~ :R7T a
234 $WT1 :: forall b. b -> T [Maybe b]
235 $WT1 b v = T1 (Maybe b) b (Maybe b) v
236 `cast` sym (Co7T (Maybe b))
239 T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
242 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
243 mkDataConIds wrap_name wkr_name data_con
244 | isNewTyCon tycon -- Newtype, only has a worker
245 = DCIds Nothing nt_work_id
247 | any isMarkedStrict all_strict_marks -- Algebraic, needs wrapper
248 || not (null eq_spec) -- NB: LoadIface.ifaceDeclSubBndrs
249 || isFamInstTyCon tycon -- depends on this test
250 = DCIds (Just alg_wrap_id) wrk_id
252 | otherwise -- Algebraic, no wrapper
253 = DCIds Nothing wrk_id
255 (univ_tvs, ex_tvs, eq_spec,
256 eq_theta, dict_theta, orig_arg_tys, res_ty) = dataConFullSig data_con
257 tycon = dataConTyCon data_con -- The representation TyCon (not family)
259 ----------- Worker (algebraic data types only) --------------
260 -- The *worker* for the data constructor is the function that
261 -- takes the representation arguments and builds the constructor.
262 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
263 (dataConRepType data_con) wkr_info
265 wkr_arity = dataConRepArity data_con
266 wkr_info = noCafIdInfo
267 `setArityInfo` wkr_arity
268 `setStrictnessInfo` Just wkr_sig
269 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
272 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
273 -- Note [Data-con worker strictness]
274 -- Notice that we do *not* say the worker is strict
275 -- even if the data constructor is declared strict
276 -- e.g. data T = MkT !(Int,Int)
277 -- Why? Because the *wrapper* is strict (and its unfolding has case
278 -- expresssions that do the evals) but the *worker* itself is not.
279 -- If we pretend it is strict then when we see
280 -- case x of y -> $wMkT y
281 -- the simplifier thinks that y is "sure to be evaluated" (because
282 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
284 -- When the simplifer sees a pattern
285 -- case e of MkT x -> ...
286 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
287 -- but that's fine... dataConRepStrictness comes from the data con
288 -- not from the worker Id.
290 cpr_info | isProductTyCon tycon &&
293 wkr_arity <= mAX_CPR_SIZE = retCPR
295 -- RetCPR is only true for products that are real data types;
296 -- that is, not unboxed tuples or [non-recursive] newtypes
298 ----------- Workers for newtypes --------------
299 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
300 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
301 `setArityInfo` 1 -- Arity 1
302 `setUnfoldingInfo` newtype_unf
303 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
304 newtype_unf = ASSERT2( isVanillaDataCon data_con &&
305 isSingleton orig_arg_tys, ppr data_con )
306 -- Note [Newtype datacons]
307 mkCompulsoryUnfolding $
308 mkLams wrap_tvs $ Lam id_arg1 $
309 wrapNewTypeBody tycon res_ty_args (Var id_arg1)
312 ----------- Wrapper --------------
313 -- We used to include the stupid theta in the wrapper's args
314 -- but now we don't. Instead the type checker just injects these
315 -- extra constraints where necessary.
316 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
317 res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
318 eq_tys = mkPredTys eq_theta
319 dict_tys = mkPredTys dict_theta
320 wrap_ty = mkForAllTys wrap_tvs $ mkFunTys eq_tys $ mkFunTys dict_tys $
321 mkFunTys orig_arg_tys $ res_ty
322 -- NB: watch out here if you allow user-written equality
323 -- constraints in data constructor signatures
325 ----------- Wrappers for algebraic data types --------------
326 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
327 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
328 `setArityInfo` wrap_arity
329 -- It's important to specify the arity, so that partial
330 -- applications are treated as values
331 `setUnfoldingInfo` wrap_unf
332 `setStrictnessInfo` Just wrap_sig
334 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
335 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
336 arg_dmds = map mk_dmd all_strict_marks
337 mk_dmd str | isMarkedStrict str = evalDmd
338 | otherwise = lazyDmd
339 -- The Cpr info can be important inside INLINE rhss, where the
340 -- wrapper constructor isn't inlined.
341 -- And the argument strictness can be important too; we
342 -- may not inline a contructor when it is partially applied.
344 -- data W = C !Int !Int !Int
345 -- ...(let w = C x in ...(w p q)...)...
346 -- we want to see that w is strict in its two arguments
348 wrap_unf = mkInlineRule needSaturated wrap_rhs (length dict_args + length id_args)
349 wrap_rhs = mkLams wrap_tvs $
351 mkLams dict_args $ mkLams id_args $
352 foldr mk_case con_app
353 (zip (dict_args ++ id_args) all_strict_marks)
356 con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
357 Var wrk_id `mkTyApps` res_ty_args
359 -- Equality evidence:
360 `mkTyApps` map snd eq_spec
362 `mkVarApps` reverse rep_ids
364 (dict_args,i2) = mkLocals 1 dict_tys
365 (id_args,i3) = mkLocals i2 orig_arg_tys
367 (eq_args,_) = mkCoVarLocals i3 eq_tys
369 mkCoVarLocals i [] = ([],i)
370 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
371 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
375 :: (Id, StrictnessMark) -- Arg, strictness
376 -> (Int -> [Id] -> CoreExpr) -- Body
377 -> Int -- Next rep arg id
378 -> [Id] -- Rep args so far, reversed
380 mk_case (arg,strict) body i rep_args
382 NotMarkedStrict -> body i (arg:rep_args)
384 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
386 Case (Var arg) arg res_ty [(DEFAULT,[], body i (arg:rep_args))]
389 -> unboxProduct i (Var arg) (idType arg) the_body
391 the_body i con_args = body i (reverse con_args ++ rep_args)
393 mAX_CPR_SIZE :: Arity
395 -- We do not treat very big tuples as CPR-ish:
396 -- a) for a start we get into trouble because there aren't
397 -- "enough" unboxed tuple types (a tiresome restriction,
399 -- b) more importantly, big unboxed tuples get returned mainly
400 -- on the stack, and are often then allocated in the heap
401 -- by the caller. So doing CPR for them may in fact make
404 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
409 Note [Newtype datacons]
410 ~~~~~~~~~~~~~~~~~~~~~~~
411 The "data constructor" for a newtype should always be vanilla. At one
412 point this wasn't true, because the newtype arising from
415 newtype T:D a = D:D (C a)
416 so the data constructor for T:C had a single argument, namely the
417 predicate (C a). But now we treat that as an ordinary argument, not
418 part of the theta-type, so all is well.
421 %************************************************************************
423 \subsection{Dictionary selectors}
425 %************************************************************************
427 Selecting a field for a dictionary. If there is just one field, then
428 there's nothing to do.
430 Dictionary selectors may get nested forall-types. Thus:
433 op :: forall b. Ord b => a -> b -> b
435 Then the top-level type for op is
437 op :: forall a. Foo a =>
441 This is unlike ordinary record selectors, which have all the for-alls
442 at the outside. When dealing with classes it's very convenient to
443 recover the original type signature from the class op selector.
446 mkDictSelId :: Bool -- True <=> don't include the unfolding
447 -- Little point on imports without -O, because the
448 -- dictionary itself won't be visible
449 -> Name -> Class -> Id
450 mkDictSelId no_unf name clas
451 = mkGlobalId (ClassOpId clas) name sel_ty info
453 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
454 -- We can't just say (exprType rhs), because that would give a type
456 -- for a single-op class (after all, the selector is the identity)
457 -- But it's type must expose the representation of the dictionary
458 -- to get (say) C a -> (a -> a)
460 base_info = noCafIdInfo
462 `setStrictnessInfo` Just strict_sig
463 `setUnfoldingInfo` (if no_unf then noUnfolding
464 else mkImplicitUnfolding rhs)
465 -- In module where class op is defined, we must add
466 -- the unfolding, even though it'll never be inlined
467 -- becuase we use that to generate a top-level binding
470 info | new_tycon = base_info
471 -- For newtype dictionaries, just inline the class op
472 -- See Note [Single-method classes] in TcInstDcls
473 | otherwise = base_info
474 `setSpecInfo` mkSpecInfo [rule]
475 `setInlinePragInfo` neverInlinePragma
476 -- Otherwise add a magic BuiltinRule, and never inline it
477 -- so that the rule is always available to fire.
478 -- See Note [ClassOp/DFun selection] in TcInstDcls
480 n_ty_args = length tyvars
482 -- This is the built-in rule that goes
483 -- op (dfT d1 d2) ---> opT d1 d2
484 rule = BuiltinRule { ru_name = fsLit "Class op " `appendFS`
485 occNameFS (getOccName name)
487 , ru_nargs = n_ty_args + 1
488 , ru_try = dictSelRule index n_ty_args }
490 -- The strictness signature is of the form U(AAAVAAAA) -> T
491 -- where the V depends on which item we are selecting
492 -- It's worth giving one, so that absence info etc is generated
493 -- even if the selector isn't inlined
494 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
495 arg_dmd | new_tycon = evalDmd
496 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
499 tycon = classTyCon clas
500 new_tycon = isNewTyCon tycon
501 [data_con] = tyConDataCons tycon
502 tyvars = dataConUnivTyVars data_con
503 arg_tys = {- ASSERT( isVanillaDataCon data_con ) -} dataConRepArgTys data_con
504 eq_theta = dataConEqTheta data_con
505 index = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` [0..]) name
506 the_arg_id = arg_ids !! index
508 pred = mkClassPred clas (mkTyVarTys tyvars)
509 dict_id = mkTemplateLocal 1 $ mkPredTy pred
510 (eq_ids,n) = mkCoVarLocals 2 $ mkPredTys eq_theta
511 arg_ids = mkTemplateLocalsNum n arg_tys
513 mkCoVarLocals i [] = ([],i)
514 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
515 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
518 rhs = mkLams tyvars (Lam dict_id rhs_body)
519 rhs_body | new_tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
520 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
521 [(DataAlt data_con, eq_ids ++ arg_ids, Var the_arg_id)]
523 dictSelRule :: Int -> Arity -> IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
525 -- op_i t1..tk (df s1..sn d1..dm) = op_i_helper s1..sn d1..dm
526 -- op_i t1..tk (D t1..tk op1 ... opm) = opi
528 -- NB: the data constructor has the same number of type args as the class op
530 dictSelRule index n_ty_args id_unf args
531 | (dict_arg : _) <- drop n_ty_args args
532 , Just (_, _, val_args) <- exprIsConApp_maybe id_unf dict_arg
533 = Just (val_args !! index)
539 %************************************************************************
543 %************************************************************************
546 -- unbox a product type...
547 -- we will recurse into newtypes, casting along the way, and unbox at the
548 -- first product data constructor we find. e.g.
550 -- data PairInt = PairInt Int Int
551 -- newtype S = MkS PairInt
554 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
555 -- ids, we get (modulo int passing)
557 -- case (e `cast` CoT) `cast` CoS of
558 -- PairInt a b -> body [a,b]
560 -- The Ints passed around are just for creating fresh locals
561 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
562 unboxProduct i arg arg_ty body
565 result = mkUnpackCase the_id arg con_args boxing_con rhs
566 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
567 ([the_id], i') = mkLocals i [arg_ty]
568 (con_args, i'') = mkLocals i' tys
569 rhs = body i'' con_args
571 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
572 -- (mkUnpackCase x e args Con body)
574 -- case (e `cast` ...) of bndr { Con args -> body }
576 -- the type of the bndr passed in is irrelevent
577 mkUnpackCase bndr arg unpk_args boxing_con body
578 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
580 (cast_arg, bndr_ty) = go (idType bndr) arg
582 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
583 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
584 = go (newTyConInstRhs tycon tycon_args)
585 (unwrapNewTypeBody tycon tycon_args arg)
586 | otherwise = (arg, ty)
589 reboxProduct :: [Unique] -- uniques to create new local binders
590 -> Type -- type of product to box
591 -> ([Unique], -- remaining uniques
592 CoreExpr, -- boxed product
593 [Id]) -- Ids being boxed into product
596 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
598 us' = dropList con_arg_tys us
600 arg_ids = zipWith (mkSysLocal (fsLit "rb")) us con_arg_tys
602 bind_rhs = mkProductBox arg_ids ty
605 (us', bind_rhs, arg_ids)
607 mkProductBox :: [Id] -> Type -> CoreExpr
608 mkProductBox arg_ids ty
611 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
614 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
615 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
616 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
618 wrap expr = wrapNewTypeBody tycon tycon_args expr
621 -- (mkReboxingAlt us con xs rhs) basically constructs the case
622 -- alternative (con, xs, rhs)
623 -- but it does the reboxing necessary to construct the *source*
624 -- arguments, xs, from the representation arguments ys.
626 -- data T = MkT !(Int,Int) Bool
628 -- mkReboxingAlt MkT [x,b] r
629 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
631 -- mkDataAlt should really be in DataCon, but it can't because
632 -- it manipulates CoreSyn.
635 :: [Unique] -- Uniques for the new Ids
637 -> [Var] -- Source-level args, including existential dicts
641 mkReboxingAlt us con args rhs
642 | not (any isMarkedUnboxed stricts)
643 = (DataAlt con, args, rhs)
647 (binds, args') = go args stricts us
649 (DataAlt con, args', mkLets binds rhs)
652 stricts = dataConExStricts con ++ dataConStrictMarks con
654 go [] _stricts _us = ([], [])
656 -- Type variable case
657 go (arg:args) stricts us
659 = let (binds, args') = go args stricts us
660 in (binds, arg:args')
662 -- Term variable case
663 go (arg:args) (str:stricts) us
664 | isMarkedUnboxed str
666 let (binds, unpacked_args') = go args stricts us'
667 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
669 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
671 = let (binds, args') = go args stricts us
672 in (binds, arg:args')
673 go (_ : _) [] _ = panic "mkReboxingAlt"
677 %************************************************************************
679 Wrapping and unwrapping newtypes and type families
681 %************************************************************************
684 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
685 -- The wrapper for the data constructor for a newtype looks like this:
686 -- newtype T a = MkT (a,Int)
687 -- MkT :: forall a. (a,Int) -> T a
688 -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
689 -- where CoT is the coercion TyCon assoicated with the newtype
691 -- The call (wrapNewTypeBody T [a] e) returns the
692 -- body of the wrapper, namely
693 -- e `cast` (CoT [a])
695 -- If a coercion constructor is provided in the newtype, then we use
696 -- it, otherwise the wrap/unwrap are both no-ops
698 -- If the we are dealing with a newtype *instance*, we have a second coercion
699 -- identifying the family instance with the constructor of the newtype
700 -- instance. This coercion is applied in any case (ie, composed with the
701 -- coercion constructor of the newtype or applied by itself).
703 wrapNewTypeBody tycon args result_expr
704 = wrapFamInstBody tycon args inner
707 | Just co_con <- newTyConCo_maybe tycon
708 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
712 -- When unwrapping, we do *not* apply any family coercion, because this will
713 -- be done via a CoPat by the type checker. We have to do it this way as
714 -- computing the right type arguments for the coercion requires more than just
715 -- a spliting operation (cf, TcPat.tcConPat).
717 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
718 unwrapNewTypeBody tycon args result_expr
719 | Just co_con <- newTyConCo_maybe tycon
720 = mkCoerce (mkTyConApp co_con args) result_expr
724 -- If the type constructor is a representation type of a data instance, wrap
725 -- the expression into a cast adjusting the expression type, which is an
726 -- instance of the representation type, to the corresponding instance of the
727 -- family instance type.
728 -- See Note [Wrappers for data instance tycons]
729 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
730 wrapFamInstBody tycon args body
731 | Just co_con <- tyConFamilyCoercion_maybe tycon
732 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
736 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
737 unwrapFamInstScrut tycon args scrut
738 | Just co_con <- tyConFamilyCoercion_maybe tycon
739 = mkCoerce (mkTyConApp co_con args) scrut
745 %************************************************************************
747 \subsection{Primitive operations}
749 %************************************************************************
752 mkPrimOpId :: PrimOp -> Id
756 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
757 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
758 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
759 (mkPrimOpIdUnique (primOpTag prim_op))
761 id = mkGlobalId (PrimOpId prim_op) name ty info
764 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
766 `setStrictnessInfo` Just strict_sig
768 -- For each ccall we manufacture a separate CCallOpId, giving it
769 -- a fresh unique, a type that is correct for this particular ccall,
770 -- and a CCall structure that gives the correct details about calling
773 -- The *name* of this Id is a local name whose OccName gives the full
774 -- details of the ccall, type and all. This means that the interface
775 -- file reader can reconstruct a suitable Id
777 mkFCallId :: Unique -> ForeignCall -> Type -> Id
778 mkFCallId uniq fcall ty
779 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
780 -- A CCallOpId should have no free type variables;
781 -- when doing substitutions won't substitute over it
782 mkGlobalId (FCallId fcall) name ty info
784 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
785 -- The "occurrence name" of a ccall is the full info about the
786 -- ccall; it is encoded, but may have embedded spaces etc!
788 name = mkFCallName uniq occ_str
792 `setStrictnessInfo` Just strict_sig
794 (_, tau) = tcSplitForAllTys ty
795 (arg_tys, _) = tcSplitFunTys tau
796 arity = length arg_tys
797 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
799 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
800 -- except for the type:
802 -- a plain HPC tick box has type (State# RealWorld)
803 -- a breakpoint Id has type forall a.a
805 -- The breakpoint Id will be applied to a list of arbitrary free variables,
806 -- which is why it needs a polymorphic type.
808 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
809 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
811 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
812 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
813 where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
815 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info
817 tickbox = TickBox mod ix
818 occ_str = showSDoc (braces (ppr tickbox))
819 name = mkTickBoxOpName uniq occ_str
824 %************************************************************************
826 \subsection{DictFuns and default methods}
828 %************************************************************************
830 Important notes about dict funs and default methods
831 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
832 Dict funs and default methods are *not* ImplicitIds. Their definition
833 involves user-written code, so we can't figure out their strictness etc
834 based on fixed info, as we can for constructors and record selectors (say).
836 We build them as LocalIds, but with External Names. This ensures that
837 they are taken to account by free-variable finding and dependency
838 analysis (e.g. CoreFVs.exprFreeVars).
840 Why shouldn't they be bound as GlobalIds? Because, in particular, if
841 they are globals, the specialiser floats dict uses above their defns,
842 which prevents good simplifications happening. Also the strictness
843 analyser treats a occurrence of a GlobalId as imported and assumes it
844 contains strictness in its IdInfo, which isn't true if the thing is
845 bound in the same module as the occurrence.
847 It's OK for dfuns to be LocalIds, because we form the instance-env to
848 pass on to the next module (md_insts) in CoreTidy, afer tidying
849 and globalising the top-level Ids.
851 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
852 that they aren't discarded by the occurrence analyser.
855 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
857 mkDictFunId :: Name -- Name to use for the dict fun;
864 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
865 = mkExportedLocalVar (DFunId is_nt) dfun_name dfun_ty vanillaIdInfo
867 is_nt = isNewTyCon (classTyCon clas)
868 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
872 %************************************************************************
874 \subsection{Un-definable}
876 %************************************************************************
878 These Ids can't be defined in Haskell. They could be defined in
879 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
880 ensure that they were definitely, definitely inlined, because there is
881 no curried identifier for them. That's what mkCompulsoryUnfolding
882 does. If we had a way to get a compulsory unfolding from an interface
883 file, we could do that, but we don't right now.
885 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
886 just gets expanded into a type coercion wherever it occurs. Hence we
887 add it as a built-in Id with an unfolding here.
889 The type variables we use here are "open" type variables: this means
890 they can unify with both unlifted and lifted types. Hence we provide
891 another gun with which to shoot yourself in the foot.
894 mkWiredInIdName mod fs uniq id
895 = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
897 unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
898 nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId
899 seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId
900 realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId
901 lazyIdName = mkWiredInIdName gHC_BASE (fsLit "lazy") lazyIdKey lazyId
903 errorName = mkWiredInIdName gHC_ERR (fsLit "error") errorIdKey eRROR_ID
904 recSelErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
905 runtimeErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
906 irrefutPatErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
907 recConErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recConError") recConErrorIdKey rEC_CON_ERROR_ID
908 patErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "patError") patErrorIdKey pAT_ERROR_ID
909 noMethodBindingErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "noMethodBindingError")
910 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
911 nonExhaustiveGuardsErrorName
912 = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "nonExhaustiveGuardsError")
913 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
917 ------------------------------------------------
918 -- unsafeCoerce# :: forall a b. a -> b
920 = pcMiscPrelId unsafeCoerceName ty info
922 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
925 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
926 (mkFunTy openAlphaTy openBetaTy)
927 [x] = mkTemplateLocals [openAlphaTy]
928 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
929 Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
931 ------------------------------------------------
933 -- nullAddr# :: Addr#
934 -- The reason is is here is because we don't provide
935 -- a way to write this literal in Haskell.
936 nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info
938 info = noCafIdInfo `setUnfoldingInfo`
939 mkCompulsoryUnfolding (Lit nullAddrLit)
941 ------------------------------------------------
942 seqId :: Id -- See Note [seqId magic]
943 seqId = pcMiscPrelId seqName ty info
945 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
946 `setSpecInfo` mkSpecInfo [seq_cast_rule]
949 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
950 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
951 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
952 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
954 -- See Note [Built-in RULES for seq]
955 seq_cast_rule = BuiltinRule { ru_name = fsLit "seq of cast"
958 , ru_try = match_seq_of_cast
961 match_seq_of_cast :: IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
962 -- See Note [Built-in RULES for seq]
963 match_seq_of_cast _ [Type _, Type res_ty, Cast scrut co, expr]
964 = Just (Var seqId `mkApps` [Type (fst (coercionKind co)), Type res_ty,
966 match_seq_of_cast _ _ = Nothing
968 ------------------------------------------------
969 lazyId :: Id -- See Note [lazyId magic]
970 lazyId = pcMiscPrelId lazyIdName ty info
973 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
978 'GHC.Prim.seq' is special in several ways.
980 a) Its second arg can have an unboxed type
983 b) Its fixity is set in LoadIface.ghcPrimIface
985 c) It has quite a bit of desugaring magic.
986 See DsUtils.lhs Note [Desugaring seq (1)] and (2) and (3)
988 d) There is some special rule handing: Note [User-defined RULES for seq]
990 Note [User-defined RULES for seq]
991 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
992 Roman found situations where he had
994 where he knew that f (which was strict in n) would terminate if n did.
995 Notice that the result of (f n) is discarded. So it makes sense to
999 Rather than attempt some general analysis to support this, I've added
1000 enough support that you can do this using a rewrite rule:
1002 RULE "f/seq" forall n. seq (f n) e = seq n e
1004 You write that rule. When GHC sees a case expression that discards
1005 its result, it mentally transforms it to a call to 'seq' and looks for
1006 a RULE. (This is done in Simplify.rebuildCase.) As usual, the
1007 correctness of the rule is up to you.
1009 To make this work, we need to be careful that the magical desugaring
1010 done in Note [seqId magic] item (c) is *not* done on the LHS of a rule.
1011 Or rather, we arrange to un-do it, in DsBinds.decomposeRuleLhs.
1013 Note [Built-in RULES for seq]
1014 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1015 We also have the following built-in rule for seq
1017 seq (x `cast` co) y = seq x y
1019 This eliminates unnecessary casts and also allows other seq rules to
1020 match more often. Notably,
1022 seq (f x `cast` co) y --> seq (f x) y
1024 and now a user-defined rule for seq (see Note [User-defined RULES for seq])
1030 lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
1032 Used to lazify pseq: pseq a b = a `seq` lazy b
1034 Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1035 not from GHC.Base.hi. This is important, because the strictness
1036 analyser will spot it as strict!
1038 Also no unfolding in lazyId: it gets "inlined" by a HACK in CorePrep.
1039 It's very important to do this inlining *after* unfoldings are exposed
1040 in the interface file. Otherwise, the unfolding for (say) pseq in the
1041 interface file will not mention 'lazy', so if we inline 'pseq' we'll totally
1042 miss the very thing that 'lazy' was there for in the first place.
1043 See Trac #3259 for a real world example.
1045 lazyId is defined in GHC.Base, so we don't *have* to inline it. If it
1046 appears un-applied, we'll end up just calling it.
1048 -------------------------------------------------------------
1049 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1050 nasty as-is, change it back to a literal (@Literal@).
1052 voidArgId is a Local Id used simply as an argument in functions
1053 where we just want an arg to avoid having a thunk of unlifted type.
1055 x = \ void :: State# RealWorld -> (# p, q #)
1057 This comes up in strictness analysis
1060 realWorldPrimId -- :: State# RealWorld
1061 = pcMiscPrelId realWorldName realWorldStatePrimTy
1062 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1063 -- The evaldUnfolding makes it look that realWorld# is evaluated
1064 -- which in turn makes Simplify.interestingArg return True,
1065 -- which in turn makes INLINE things applied to realWorld# likely
1069 voidArgId -- :: State# RealWorld
1070 = mkSysLocal (fsLit "void") voidArgIdKey realWorldStatePrimTy
1074 %************************************************************************
1076 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1078 %************************************************************************
1080 GHC randomly injects these into the code.
1082 @patError@ is just a version of @error@ for pattern-matching
1083 failures. It knows various ``codes'' which expand to longer
1084 strings---this saves space!
1086 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
1087 well shouldn't be yanked on, but if one is, then you will get a
1088 friendly message from @absentErr@ (rather than a totally random
1091 @parError@ is a special version of @error@ which the compiler does
1092 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
1093 templates, but we don't ever expect to generate code for it.
1097 :: Id -- Should be of type (forall a. Addr# -> a)
1098 -- where Addr# points to a UTF8 encoded string
1099 -> Type -- The type to instantiate 'a'
1100 -> String -- The string to print
1103 mkRuntimeErrorApp err_id res_ty err_msg
1104 = mkApps (Var err_id) [Type res_ty, err_string]
1106 err_string = Lit (mkMachString err_msg)
1108 mkImpossibleExpr :: Type -> CoreExpr
1109 mkImpossibleExpr res_ty
1110 = mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty "Impossible case alternative"
1112 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
1113 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
1114 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
1115 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
1116 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
1117 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
1118 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1120 -- The runtime error Ids take a UTF8-encoded string as argument
1122 mkRuntimeErrorId :: Name -> Id
1123 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1125 runtimeErrorTy :: Type
1126 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1130 eRROR_ID = pc_bottoming_Id errorName errorTy
1133 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1134 -- Notice the openAlphaTyVar. It says that "error" can be applied
1135 -- to unboxed as well as boxed types. This is OK because it never
1136 -- returns, so the return type is irrelevant.
1140 %************************************************************************
1142 \subsection{Utilities}
1144 %************************************************************************
1147 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1148 pcMiscPrelId name ty info
1149 = mkVanillaGlobalWithInfo name ty info
1150 -- We lie and say the thing is imported; otherwise, we get into
1151 -- a mess with dependency analysis; e.g., core2stg may heave in
1152 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1153 -- being compiled, then it's just a matter of luck if the definition
1154 -- will be in "the right place" to be in scope.
1156 pc_bottoming_Id :: Name -> Type -> Id
1157 -- Function of arity 1, which diverges after being given one argument
1158 pc_bottoming_Id name ty
1159 = pcMiscPrelId name ty bottoming_info
1161 bottoming_info = vanillaIdInfo `setStrictnessInfo` Just strict_sig
1163 -- Make arity and strictness agree
1165 -- Do *not* mark them as NoCafRefs, because they can indeed have
1166 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1167 -- which has some CAFs
1168 -- In due course we may arrange that these error-y things are
1169 -- regarded by the GC as permanently live, in which case we
1170 -- can give them NoCaf info. As it is, any function that calls
1171 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1174 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1175 -- These "bottom" out, no matter what their arguments