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 unsafeCoerceId, realWorldPrimId, voidArgId, nullAddrId, seqId,
31 mkRuntimeErrorApp, mkImpossibleExpr,
32 rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
33 nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
34 pAT_ERROR_ID, eRROR_ID, rEC_SEL_ERROR_ID,
39 #include "HsVersions.h"
48 import CoreUtils ( exprType, mkCoerce )
59 import Var ( Var, TyVar, mkCoVar, mkExportedLocalVar )
65 import BasicTypes hiding ( SuccessFlag(..) )
73 %************************************************************************
75 \subsection{Wired in Ids}
77 %************************************************************************
81 There are several reasons why an Id might appear in the wiredInIds:
83 (1) The ghcPrimIds are wired in because they can't be defined in
84 Haskell at all, although the can be defined in Core. They have
85 compulsory unfoldings, so they are always inlined and they have
86 no definition site. Their home module is GHC.Prim, so they
87 also have a description in primops.txt.pp, where they are called
90 (2) The 'error' function, eRROR_ID, is wired in because we don't yet have
91 a way to express in an interface file that the result type variable
92 is 'open'; that is can be unified with an unboxed type
94 [The interface file format now carry such information, but there's
95 no way yet of expressing at the definition site for these
96 error-reporting functions that they have an 'open'
97 result type. -- sof 1/99]
99 (3) Other error functions (rUNTIME_ERROR_ID) are wired in (a) because
100 the desugarer generates code that mentiones them directly, and
101 (b) for the same reason as eRROR_ID
103 (4) lazyId is wired in because the wired-in version overrides the
104 strictness of the version defined in GHC.Base
106 In cases (2-4), the function has a definition in a library module, and
107 can be called; but the wired-in version means that the details are
108 never read from that module's interface file; instead, the full definition
116 eRROR_ID, -- This one isn't used anywhere else in the compiler
117 -- But we still need it in wiredInIds so that when GHC
118 -- compiles a program that mentions 'error' we don't
119 -- import its type from the interface file; we just get
120 -- the Id defined here. Which has an 'open-tyvar' type.
123 iRREFUT_PAT_ERROR_ID,
124 nON_EXHAUSTIVE_GUARDS_ERROR_ID,
125 nO_METHOD_BINDING_ERROR_ID,
133 -- These Ids are exported from GHC.Prim
136 = [ -- These can't be defined in Haskell, but they have
137 -- perfectly reasonable unfoldings in Core
145 %************************************************************************
147 \subsection{Data constructors}
149 %************************************************************************
151 The wrapper for a constructor is an ordinary top-level binding that evaluates
152 any strict args, unboxes any args that are going to be flattened, and calls
155 We're going to build a constructor that looks like:
157 data (Data a, C b) => T a b = T1 !a !Int b
160 \d1::Data a, d2::C b ->
161 \p q r -> case p of { p ->
163 Con T1 [a,b] [p,q,r]}}
167 * d2 is thrown away --- a context in a data decl is used to make sure
168 one *could* construct dictionaries at the site the constructor
169 is used, but the dictionary isn't actually used.
171 * We have to check that we can construct Data dictionaries for
172 the types a and Int. Once we've done that we can throw d1 away too.
174 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
175 all that matters is that the arguments are evaluated. "seq" is
176 very careful to preserve evaluation order, which we don't need
179 You might think that we could simply give constructors some strictness
180 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
181 But we don't do that because in the case of primops and functions strictness
182 is a *property* not a *requirement*. In the case of constructors we need to
183 do something active to evaluate the argument.
185 Making an explicit case expression allows the simplifier to eliminate
186 it in the (common) case where the constructor arg is already evaluated.
188 Note [Wrappers for data instance tycons]
189 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
190 In the case of data instances, the wrapper also applies the coercion turning
191 the representation type into the family instance type to cast the result of
192 the wrapper. For example, consider the declarations
194 data family Map k :: * -> *
195 data instance Map (a, b) v = MapPair (Map a (Pair b v))
197 The tycon to which the datacon MapPair belongs gets a unique internal
198 name of the form :R123Map, and we call it the representation tycon.
199 In contrast, Map is the family tycon (accessible via
200 tyConFamInst_maybe). A coercion allows you to move between
201 representation and family type. It is accessible from :R123Map via
202 tyConFamilyCoercion_maybe and has kind
204 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
206 The wrapper and worker of MapPair get the types
209 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
210 $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v)
213 MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
215 This coercion is conditionally applied by wrapFamInstBody.
217 It's a bit more complicated if the data instance is a GADT as well!
219 data instance T [a] where
220 T1 :: forall b. b -> T [Maybe b]
222 Hence we translate to
225 $WT1 :: forall b. b -> T [Maybe b]
226 $WT1 b v = T1 (Maybe b) b (Maybe b) v
227 `cast` sym (Co7T (Maybe b))
230 T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
232 -- Coercion from family type to representation type
233 Co7T a :: T [a] ~ :R7T a
236 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
237 mkDataConIds wrap_name wkr_name data_con
238 | isNewTyCon tycon -- Newtype, only has a worker
239 = DCIds Nothing nt_work_id
241 | any isBanged all_strict_marks -- Algebraic, needs wrapper
242 || not (null eq_spec) -- NB: LoadIface.ifaceDeclSubBndrs
243 || isFamInstTyCon tycon -- depends on this test
244 = DCIds (Just alg_wrap_id) wrk_id
246 | otherwise -- Algebraic, no wrapper
247 = DCIds Nothing wrk_id
249 (univ_tvs, ex_tvs, eq_spec,
250 eq_theta, dict_theta, orig_arg_tys, res_ty) = dataConFullSig data_con
251 tycon = dataConTyCon data_con -- The representation TyCon (not family)
253 ----------- Worker (algebraic data types only) --------------
254 -- The *worker* for the data constructor is the function that
255 -- takes the representation arguments and builds the constructor.
256 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
257 (dataConRepType data_con) wkr_info
259 wkr_arity = dataConRepArity data_con
260 wkr_info = noCafIdInfo
261 `setArityInfo` wkr_arity
262 `setStrictnessInfo` Just wkr_sig
263 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
266 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
267 -- Note [Data-con worker strictness]
268 -- Notice that we do *not* say the worker is strict
269 -- even if the data constructor is declared strict
270 -- e.g. data T = MkT !(Int,Int)
271 -- Why? Because the *wrapper* is strict (and its unfolding has case
272 -- expresssions that do the evals) but the *worker* itself is not.
273 -- If we pretend it is strict then when we see
274 -- case x of y -> $wMkT y
275 -- the simplifier thinks that y is "sure to be evaluated" (because
276 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
278 -- When the simplifer sees a pattern
279 -- case e of MkT x -> ...
280 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
281 -- but that's fine... dataConRepStrictness comes from the data con
282 -- not from the worker Id.
284 cpr_info | isProductTyCon tycon &&
287 wkr_arity <= mAX_CPR_SIZE = retCPR
289 -- RetCPR is only true for products that are real data types;
290 -- that is, not unboxed tuples or [non-recursive] newtypes
292 ----------- Workers for newtypes --------------
293 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
294 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
295 `setArityInfo` 1 -- Arity 1
296 `setUnfoldingInfo` newtype_unf
297 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
298 newtype_unf = ASSERT2( isVanillaDataCon data_con &&
299 isSingleton orig_arg_tys, ppr data_con )
300 -- Note [Newtype datacons]
301 mkCompulsoryUnfolding $
302 mkLams wrap_tvs $ Lam id_arg1 $
303 wrapNewTypeBody tycon res_ty_args (Var id_arg1)
306 ----------- Wrapper --------------
307 -- We used to include the stupid theta in the wrapper's args
308 -- but now we don't. Instead the type checker just injects these
309 -- extra constraints where necessary.
310 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
311 res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
312 eq_tys = mkPredTys eq_theta
313 dict_tys = mkPredTys dict_theta
314 wrap_ty = mkForAllTys wrap_tvs $ mkFunTys eq_tys $ mkFunTys dict_tys $
315 mkFunTys orig_arg_tys $ res_ty
316 -- NB: watch out here if you allow user-written equality
317 -- constraints in data constructor signatures
319 ----------- Wrappers for algebraic data types --------------
320 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
321 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
322 `setArityInfo` wrap_arity
323 -- It's important to specify the arity, so that partial
324 -- applications are treated as values
325 `setUnfoldingInfo` wrap_unf
326 `setStrictnessInfo` Just wrap_sig
328 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
329 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
330 arg_dmds = map mk_dmd all_strict_marks
331 mk_dmd str | isBanged str = evalDmd
332 | otherwise = lazyDmd
333 -- The Cpr info can be important inside INLINE rhss, where the
334 -- wrapper constructor isn't inlined.
335 -- And the argument strictness can be important too; we
336 -- may not inline a contructor when it is partially applied.
338 -- data W = C !Int !Int !Int
339 -- ...(let w = C x in ...(w p q)...)...
340 -- we want to see that w is strict in its two arguments
342 wrap_unf = mkInlineRule wrap_rhs (Just (length dict_args + length id_args))
343 wrap_rhs = mkLams wrap_tvs $
345 mkLams dict_args $ mkLams id_args $
346 foldr mk_case con_app
347 (zip (dict_args ++ id_args) all_strict_marks)
350 con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
351 Var wrk_id `mkTyApps` res_ty_args
353 -- Equality evidence:
354 `mkTyApps` map snd eq_spec
356 `mkVarApps` reverse rep_ids
358 (dict_args,i2) = mkLocals 1 dict_tys
359 (id_args,i3) = mkLocals i2 orig_arg_tys
361 (eq_args,_) = mkCoVarLocals i3 eq_tys
363 mkCoVarLocals i [] = ([],i)
364 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
365 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
369 :: (Id, HsBang) -- Arg, strictness
370 -> (Int -> [Id] -> CoreExpr) -- Body
371 -> Int -- Next rep arg id
372 -> [Id] -- Rep args so far, reversed
374 mk_case (arg,strict) body i rep_args
376 HsNoBang -> body i (arg:rep_args)
377 HsUnpack -> unboxProduct i (Var arg) (idType arg) the_body
379 the_body i con_args = body i (reverse con_args ++ rep_args)
380 _other -- HsUnpackFailed and HsStrict
381 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
382 | otherwise -> Case (Var arg) arg res_ty
383 [(DEFAULT,[], body i (arg:rep_args))]
385 mAX_CPR_SIZE :: Arity
387 -- We do not treat very big tuples as CPR-ish:
388 -- a) for a start we get into trouble because there aren't
389 -- "enough" unboxed tuple types (a tiresome restriction,
391 -- b) more importantly, big unboxed tuples get returned mainly
392 -- on the stack, and are often then allocated in the heap
393 -- by the caller. So doing CPR for them may in fact make
396 mkLocals :: Int -> [Type] -> ([Id], Int)
397 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
402 Note [Newtype datacons]
403 ~~~~~~~~~~~~~~~~~~~~~~~
404 The "data constructor" for a newtype should always be vanilla. At one
405 point this wasn't true, because the newtype arising from
408 newtype T:D a = D:D (C a)
409 so the data constructor for T:C had a single argument, namely the
410 predicate (C a). But now we treat that as an ordinary argument, not
411 part of the theta-type, so all is well.
414 %************************************************************************
416 \subsection{Dictionary selectors}
418 %************************************************************************
420 Selecting a field for a dictionary. If there is just one field, then
421 there's nothing to do.
423 Dictionary selectors may get nested forall-types. Thus:
426 op :: forall b. Ord b => a -> b -> b
428 Then the top-level type for op is
430 op :: forall a. Foo a =>
434 This is unlike ordinary record selectors, which have all the for-alls
435 at the outside. When dealing with classes it's very convenient to
436 recover the original type signature from the class op selector.
439 mkDictSelId :: Bool -- True <=> don't include the unfolding
440 -- Little point on imports without -O, because the
441 -- dictionary itself won't be visible
442 -> Name -> Class -> Id
443 mkDictSelId no_unf name clas
444 = mkGlobalId (ClassOpId clas) name sel_ty info
446 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
447 -- We can't just say (exprType rhs), because that would give a type
449 -- for a single-op class (after all, the selector is the identity)
450 -- But it's type must expose the representation of the dictionary
451 -- to get (say) C a -> (a -> a)
453 base_info = noCafIdInfo
455 `setStrictnessInfo` Just strict_sig
456 `setUnfoldingInfo` (if no_unf then noUnfolding
457 else mkImplicitUnfolding rhs)
458 -- In module where class op is defined, we must add
459 -- the unfolding, even though it'll never be inlined
460 -- becuase we use that to generate a top-level binding
463 info = base_info `setSpecInfo` mkSpecInfo [rule]
464 `setInlinePragInfo` neverInlinePragma
465 -- Add a magic BuiltinRule, and never inline it
466 -- so that the rule is always available to fire.
467 -- See Note [ClassOp/DFun selection] in TcInstDcls
469 n_ty_args = length tyvars
471 -- This is the built-in rule that goes
472 -- op (dfT d1 d2) ---> opT d1 d2
473 rule = BuiltinRule { ru_name = fsLit "Class op " `appendFS`
474 occNameFS (getOccName name)
476 , ru_nargs = n_ty_args + 1
477 , ru_try = dictSelRule index n_ty_args }
479 -- The strictness signature is of the form U(AAAVAAAA) -> T
480 -- where the V depends on which item we are selecting
481 -- It's worth giving one, so that absence info etc is generated
482 -- even if the selector isn't inlined
483 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
484 arg_dmd | new_tycon = evalDmd
485 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
488 tycon = classTyCon clas
489 new_tycon = isNewTyCon tycon
490 [data_con] = tyConDataCons tycon
491 tyvars = dataConUnivTyVars data_con
492 arg_tys = {- ASSERT( isVanillaDataCon data_con ) -} dataConRepArgTys data_con
493 eq_theta = dataConEqTheta data_con
494 index = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` [0..]) name
495 the_arg_id = arg_ids !! index
497 pred = mkClassPred clas (mkTyVarTys tyvars)
498 dict_id = mkTemplateLocal 1 $ mkPredTy pred
499 (eq_ids,n) = mkCoVarLocals 2 $ mkPredTys eq_theta
500 arg_ids = mkTemplateLocalsNum n arg_tys
502 mkCoVarLocals i [] = ([],i)
503 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
504 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
507 rhs = mkLams tyvars (Lam dict_id rhs_body)
508 rhs_body | new_tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
509 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
510 [(DataAlt data_con, eq_ids ++ arg_ids, Var the_arg_id)]
512 dictSelRule :: Int -> Arity -> IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
514 -- op_i t1..tk (df s1..sn d1..dm) = op_i_helper s1..sn d1..dm
515 -- op_i t1..tk (D t1..tk op1 ... opm) = opi
517 -- NB: the data constructor has the same number of type args as the class op
519 dictSelRule index n_ty_args id_unf args
520 | (dict_arg : _) <- drop n_ty_args args
521 , Just (_, _, val_args) <- exprIsConApp_maybe id_unf dict_arg
522 = Just (val_args !! index)
528 %************************************************************************
532 %************************************************************************
535 -- unbox a product type...
536 -- we will recurse into newtypes, casting along the way, and unbox at the
537 -- first product data constructor we find. e.g.
539 -- data PairInt = PairInt Int Int
540 -- newtype S = MkS PairInt
543 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
544 -- ids, we get (modulo int passing)
546 -- case (e `cast` CoT) `cast` CoS of
547 -- PairInt a b -> body [a,b]
549 -- The Ints passed around are just for creating fresh locals
550 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
551 unboxProduct i arg arg_ty body
554 result = mkUnpackCase the_id arg con_args boxing_con rhs
555 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
556 ([the_id], i') = mkLocals i [arg_ty]
557 (con_args, i'') = mkLocals i' tys
558 rhs = body i'' con_args
560 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
561 -- (mkUnpackCase x e args Con body)
563 -- case (e `cast` ...) of bndr { Con args -> body }
565 -- the type of the bndr passed in is irrelevent
566 mkUnpackCase bndr arg unpk_args boxing_con body
567 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
569 (cast_arg, bndr_ty) = go (idType bndr) arg
571 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
572 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
573 = go (newTyConInstRhs tycon tycon_args)
574 (unwrapNewTypeBody tycon tycon_args arg)
575 | otherwise = (arg, ty)
578 reboxProduct :: [Unique] -- uniques to create new local binders
579 -> Type -- type of product to box
580 -> ([Unique], -- remaining uniques
581 CoreExpr, -- boxed product
582 [Id]) -- Ids being boxed into product
585 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
587 us' = dropList con_arg_tys us
589 arg_ids = zipWith (mkSysLocal (fsLit "rb")) us con_arg_tys
591 bind_rhs = mkProductBox arg_ids ty
594 (us', bind_rhs, arg_ids)
596 mkProductBox :: [Id] -> Type -> CoreExpr
597 mkProductBox arg_ids ty
600 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
603 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
604 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
605 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
607 wrap expr = wrapNewTypeBody tycon tycon_args expr
610 -- (mkReboxingAlt us con xs rhs) basically constructs the case
611 -- alternative (con, xs, rhs)
612 -- but it does the reboxing necessary to construct the *source*
613 -- arguments, xs, from the representation arguments ys.
615 -- data T = MkT !(Int,Int) Bool
617 -- mkReboxingAlt MkT [x,b] r
618 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
620 -- mkDataAlt should really be in DataCon, but it can't because
621 -- it manipulates CoreSyn.
624 :: [Unique] -- Uniques for the new Ids
626 -> [Var] -- Source-level args, including existential dicts
630 mkReboxingAlt us con args rhs
631 | not (any isMarkedUnboxed stricts)
632 = (DataAlt con, args, rhs)
636 (binds, args') = go args stricts us
638 (DataAlt con, args', mkLets binds rhs)
641 stricts = dataConExStricts con ++ dataConStrictMarks con
643 go [] _stricts _us = ([], [])
645 -- Type variable case
646 go (arg:args) stricts us
648 = let (binds, args') = go args stricts us
649 in (binds, arg:args')
651 -- Term variable case
652 go (arg:args) (str:stricts) us
653 | isMarkedUnboxed str
655 let (binds, unpacked_args') = go args stricts us'
656 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
658 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
660 = let (binds, args') = go args stricts us
661 in (binds, arg:args')
662 go (_ : _) [] _ = panic "mkReboxingAlt"
666 %************************************************************************
668 Wrapping and unwrapping newtypes and type families
670 %************************************************************************
673 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
674 -- The wrapper for the data constructor for a newtype looks like this:
675 -- newtype T a = MkT (a,Int)
676 -- MkT :: forall a. (a,Int) -> T a
677 -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
678 -- where CoT is the coercion TyCon assoicated with the newtype
680 -- The call (wrapNewTypeBody T [a] e) returns the
681 -- body of the wrapper, namely
682 -- e `cast` (CoT [a])
684 -- If a coercion constructor is provided in the newtype, then we use
685 -- it, otherwise the wrap/unwrap are both no-ops
687 -- If the we are dealing with a newtype *instance*, we have a second coercion
688 -- identifying the family instance with the constructor of the newtype
689 -- instance. This coercion is applied in any case (ie, composed with the
690 -- coercion constructor of the newtype or applied by itself).
692 wrapNewTypeBody tycon args result_expr
693 = wrapFamInstBody tycon args inner
696 | Just co_con <- newTyConCo_maybe tycon
697 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
701 -- When unwrapping, we do *not* apply any family coercion, because this will
702 -- be done via a CoPat by the type checker. We have to do it this way as
703 -- computing the right type arguments for the coercion requires more than just
704 -- a spliting operation (cf, TcPat.tcConPat).
706 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
707 unwrapNewTypeBody tycon args result_expr
708 | Just co_con <- newTyConCo_maybe tycon
709 = mkCoerce (mkTyConApp co_con args) result_expr
713 -- If the type constructor is a representation type of a data instance, wrap
714 -- the expression into a cast adjusting the expression type, which is an
715 -- instance of the representation type, to the corresponding instance of the
716 -- family instance type.
717 -- See Note [Wrappers for data instance tycons]
718 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
719 wrapFamInstBody tycon args body
720 | Just co_con <- tyConFamilyCoercion_maybe tycon
721 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
725 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
726 unwrapFamInstScrut tycon args scrut
727 | Just co_con <- tyConFamilyCoercion_maybe tycon
728 = mkCoerce (mkTyConApp co_con args) scrut
734 %************************************************************************
736 \subsection{Primitive operations}
738 %************************************************************************
741 mkPrimOpId :: PrimOp -> Id
745 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
746 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
747 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
748 (mkPrimOpIdUnique (primOpTag prim_op))
750 id = mkGlobalId (PrimOpId prim_op) name ty info
753 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
755 `setStrictnessInfo` Just strict_sig
757 -- For each ccall we manufacture a separate CCallOpId, giving it
758 -- a fresh unique, a type that is correct for this particular ccall,
759 -- and a CCall structure that gives the correct details about calling
762 -- The *name* of this Id is a local name whose OccName gives the full
763 -- details of the ccall, type and all. This means that the interface
764 -- file reader can reconstruct a suitable Id
766 mkFCallId :: Unique -> ForeignCall -> Type -> Id
767 mkFCallId uniq fcall ty
768 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
769 -- A CCallOpId should have no free type variables;
770 -- when doing substitutions won't substitute over it
771 mkGlobalId (FCallId fcall) name ty info
773 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
774 -- The "occurrence name" of a ccall is the full info about the
775 -- ccall; it is encoded, but may have embedded spaces etc!
777 name = mkFCallName uniq occ_str
781 `setStrictnessInfo` Just strict_sig
783 (_, tau) = tcSplitForAllTys ty
784 (arg_tys, _) = tcSplitFunTys tau
785 arity = length arg_tys
786 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
788 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
789 -- except for the type:
791 -- a plain HPC tick box has type (State# RealWorld)
792 -- a breakpoint Id has type forall a.a
794 -- The breakpoint Id will be applied to a list of arbitrary free variables,
795 -- which is why it needs a polymorphic type.
797 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
798 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
800 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
801 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
802 where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
804 mkTickBox' :: Unique -> Module -> TickBoxId -> Type -> Id
805 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info
807 tickbox = TickBox mod ix
808 occ_str = showSDoc (braces (ppr tickbox))
809 name = mkTickBoxOpName uniq occ_str
814 %************************************************************************
816 \subsection{DictFuns and default methods}
818 %************************************************************************
820 Important notes about dict funs and default methods
821 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
822 Dict funs and default methods are *not* ImplicitIds. Their definition
823 involves user-written code, so we can't figure out their strictness etc
824 based on fixed info, as we can for constructors and record selectors (say).
826 We build them as LocalIds, but with External Names. This ensures that
827 they are taken to account by free-variable finding and dependency
828 analysis (e.g. CoreFVs.exprFreeVars).
830 Why shouldn't they be bound as GlobalIds? Because, in particular, if
831 they are globals, the specialiser floats dict uses above their defns,
832 which prevents good simplifications happening. Also the strictness
833 analyser treats a occurrence of a GlobalId as imported and assumes it
834 contains strictness in its IdInfo, which isn't true if the thing is
835 bound in the same module as the occurrence.
837 It's OK for dfuns to be LocalIds, because we form the instance-env to
838 pass on to the next module (md_insts) in CoreTidy, afer tidying
839 and globalising the top-level Ids.
841 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
842 that they aren't discarded by the occurrence analyser.
845 mkDefaultMethodId :: Id -- Selector Id
846 -> Name -- Default method name
847 -> Id -- Default method Id
848 mkDefaultMethodId sel_id dm_name = mkExportedLocalId dm_name (idType sel_id)
850 mkDictFunId :: Name -- Name to use for the dict fun;
857 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
858 = mkExportedLocalVar (DFunId is_nt) dfun_name dfun_ty vanillaIdInfo
860 is_nt = isNewTyCon (classTyCon clas)
861 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
865 %************************************************************************
867 \subsection{Un-definable}
869 %************************************************************************
871 These Ids can't be defined in Haskell. They could be defined in
872 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
873 ensure that they were definitely, definitely inlined, because there is
874 no curried identifier for them. That's what mkCompulsoryUnfolding
875 does. If we had a way to get a compulsory unfolding from an interface
876 file, we could do that, but we don't right now.
878 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
879 just gets expanded into a type coercion wherever it occurs. Hence we
880 add it as a built-in Id with an unfolding here.
882 The type variables we use here are "open" type variables: this means
883 they can unify with both unlifted and lifted types. Hence we provide
884 another gun with which to shoot yourself in the foot.
887 mkWiredInIdName :: Module -> FastString -> Unique -> Id -> Name
888 mkWiredInIdName mod fs uniq id
889 = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
891 unsafeCoerceName, nullAddrName, seqName, realWorldName :: Name
892 lazyIdName, errorName, recSelErrorName, runtimeErrorName :: Name
893 irrefutPatErrorName, recConErrorName, patErrorName :: Name
894 nonExhaustiveGuardsErrorName, noMethodBindingErrorName :: Name
895 unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
896 nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId
897 seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId
898 realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId
899 lazyIdName = mkWiredInIdName gHC_BASE (fsLit "lazy") lazyIdKey lazyId
901 errorName = mkWiredInIdName gHC_ERR (fsLit "error") errorIdKey eRROR_ID
902 recSelErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
903 runtimeErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
904 irrefutPatErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
905 recConErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recConError") recConErrorIdKey rEC_CON_ERROR_ID
906 patErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "patError") patErrorIdKey pAT_ERROR_ID
907 noMethodBindingErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "noMethodBindingError")
908 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
909 nonExhaustiveGuardsErrorName
910 = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "nonExhaustiveGuardsError")
911 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
915 ------------------------------------------------
916 -- unsafeCoerce# :: forall a b. a -> b
919 = pcMiscPrelId unsafeCoerceName ty info
921 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
924 ty = mkForAllTys [argAlphaTyVar,openBetaTyVar]
925 (mkFunTy argAlphaTy openBetaTy)
926 [x] = mkTemplateLocals [argAlphaTy]
927 rhs = mkLams [argAlphaTyVar,openBetaTyVar,x] $
928 Cast (Var x) (mkUnsafeCoercion argAlphaTy openBetaTy)
930 ------------------------------------------------
932 -- nullAddr# :: Addr#
933 -- The reason is is here is because we don't provide
934 -- a way to write this literal in Haskell.
935 nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info
937 info = noCafIdInfo `setUnfoldingInfo`
938 mkCompulsoryUnfolding (Lit nullAddrLit)
940 ------------------------------------------------
941 seqId :: Id -- See Note [seqId magic]
942 seqId = pcMiscPrelId seqName ty info
944 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
945 `setSpecInfo` mkSpecInfo [seq_cast_rule]
948 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
949 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
950 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
951 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
953 -- See Note [Built-in RULES for seq]
954 seq_cast_rule = BuiltinRule { ru_name = fsLit "seq of cast"
957 , ru_try = match_seq_of_cast
960 match_seq_of_cast :: IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
961 -- See Note [Built-in RULES for seq]
962 match_seq_of_cast _ [Type _, Type res_ty, Cast scrut co, expr]
963 = Just (Var seqId `mkApps` [Type (fst (coercionKind co)), Type res_ty,
965 match_seq_of_cast _ _ = Nothing
967 ------------------------------------------------
968 lazyId :: Id -- See Note [lazyId magic]
969 lazyId = pcMiscPrelId lazyIdName ty info
972 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
977 'GHC.Prim.seq' is special in several ways.
979 a) Its second arg can have an unboxed type
982 b) Its fixity is set in LoadIface.ghcPrimIface
984 c) It has quite a bit of desugaring magic.
985 See DsUtils.lhs Note [Desugaring seq (1)] and (2) and (3)
987 d) There is some special rule handing: Note [User-defined RULES for seq]
989 Note [User-defined RULES for seq]
990 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
991 Roman found situations where he had
993 where he knew that f (which was strict in n) would terminate if n did.
994 Notice that the result of (f n) is discarded. So it makes sense to
998 Rather than attempt some general analysis to support this, I've added
999 enough support that you can do this using a rewrite rule:
1001 RULE "f/seq" forall n. seq (f n) e = seq n e
1003 You write that rule. When GHC sees a case expression that discards
1004 its result, it mentally transforms it to a call to 'seq' and looks for
1005 a RULE. (This is done in Simplify.rebuildCase.) As usual, the
1006 correctness of the rule is up to you.
1008 To make this work, we need to be careful that the magical desugaring
1009 done in Note [seqId magic] item (c) is *not* done on the LHS of a rule.
1010 Or rather, we arrange to un-do it, in DsBinds.decomposeRuleLhs.
1012 Note [Built-in RULES for seq]
1013 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1014 We also have the following built-in rule for seq
1016 seq (x `cast` co) y = seq x y
1018 This eliminates unnecessary casts and also allows other seq rules to
1019 match more often. Notably,
1021 seq (f x `cast` co) y --> seq (f x) y
1023 and now a user-defined rule for seq (see Note [User-defined RULES for seq])
1029 lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
1031 Used to lazify pseq: pseq a b = a `seq` lazy b
1033 Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1034 not from GHC.Base.hi. This is important, because the strictness
1035 analyser will spot it as strict!
1037 Also no unfolding in lazyId: it gets "inlined" by a HACK in CorePrep.
1038 It's very important to do this inlining *after* unfoldings are exposed
1039 in the interface file. Otherwise, the unfolding for (say) pseq in the
1040 interface file will not mention 'lazy', so if we inline 'pseq' we'll totally
1041 miss the very thing that 'lazy' was there for in the first place.
1042 See Trac #3259 for a real world example.
1044 lazyId is defined in GHC.Base, so we don't *have* to inline it. If it
1045 appears un-applied, we'll end up just calling it.
1047 -------------------------------------------------------------
1048 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1049 nasty as-is, change it back to a literal (@Literal@).
1051 voidArgId is a Local Id used simply as an argument in functions
1052 where we just want an arg to avoid having a thunk of unlifted type.
1054 x = \ void :: State# RealWorld -> (# p, q #)
1056 This comes up in strictness analysis
1059 realWorldPrimId :: Id
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, rUNTIME_ERROR_ID, iRREFUT_PAT_ERROR_ID, rEC_CON_ERROR_ID :: Id
1113 pAT_ERROR_ID, nO_METHOD_BINDING_ERROR_ID, nON_EXHAUSTIVE_GUARDS_ERROR_ID :: Id
1114 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
1115 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
1116 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
1117 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
1118 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
1119 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
1120 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1122 -- The runtime error Ids take a UTF8-encoded string as argument
1124 mkRuntimeErrorId :: Name -> Id
1125 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1127 runtimeErrorTy :: Type
1128 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1133 eRROR_ID = pc_bottoming_Id errorName errorTy
1136 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1137 -- Notice the openAlphaTyVar. It says that "error" can be applied
1138 -- to unboxed as well as boxed types. This is OK because it never
1139 -- returns, so the return type is irrelevant.
1143 %************************************************************************
1145 \subsection{Utilities}
1147 %************************************************************************
1150 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1151 pcMiscPrelId name ty info
1152 = mkVanillaGlobalWithInfo name ty info
1153 -- We lie and say the thing is imported; otherwise, we get into
1154 -- a mess with dependency analysis; e.g., core2stg may heave in
1155 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1156 -- being compiled, then it's just a matter of luck if the definition
1157 -- will be in "the right place" to be in scope.
1159 pc_bottoming_Id :: Name -> Type -> Id
1160 -- Function of arity 1, which diverges after being given one argument
1161 pc_bottoming_Id name ty
1162 = pcMiscPrelId name ty bottoming_info
1164 bottoming_info = vanillaIdInfo `setStrictnessInfo` Just strict_sig
1166 -- Make arity and strictness agree
1168 -- Do *not* mark them as NoCafRefs, because they can indeed have
1169 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1170 -- which has some CAFs
1171 -- In due course we may arrange that these error-y things are
1172 -- regarded by the GC as permanently live, in which case we
1173 -- can give them NoCaf info. As it is, any function that calls
1174 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1177 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1178 -- These "bottom" out, no matter what their arguments