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 Co7T a :: T [a] ~ :R7T a
227 $WT1 :: forall b. b -> T [Maybe b]
228 $WT1 b v = T1 (Maybe b) b (Maybe b) v
229 `cast` sym (Co7T (Maybe b))
232 T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
235 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
236 mkDataConIds wrap_name wkr_name data_con
237 | isNewTyCon tycon -- Newtype, only has a worker
238 = DCIds Nothing nt_work_id
240 | any isBanged all_strict_marks -- Algebraic, needs wrapper
241 || not (null eq_spec) -- NB: LoadIface.ifaceDeclSubBndrs
242 || isFamInstTyCon tycon -- depends on this test
243 = DCIds (Just alg_wrap_id) wrk_id
245 | otherwise -- Algebraic, no wrapper
246 = DCIds Nothing wrk_id
248 (univ_tvs, ex_tvs, eq_spec,
249 eq_theta, dict_theta, orig_arg_tys, res_ty) = dataConFullSig data_con
250 tycon = dataConTyCon data_con -- The representation TyCon (not family)
252 ----------- Worker (algebraic data types only) --------------
253 -- The *worker* for the data constructor is the function that
254 -- takes the representation arguments and builds the constructor.
255 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
256 (dataConRepType data_con) wkr_info
258 wkr_arity = dataConRepArity data_con
259 wkr_info = noCafIdInfo
260 `setArityInfo` wkr_arity
261 `setStrictnessInfo` Just wkr_sig
262 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
265 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
266 -- Note [Data-con worker strictness]
267 -- Notice that we do *not* say the worker is strict
268 -- even if the data constructor is declared strict
269 -- e.g. data T = MkT !(Int,Int)
270 -- Why? Because the *wrapper* is strict (and its unfolding has case
271 -- expresssions that do the evals) but the *worker* itself is not.
272 -- If we pretend it is strict then when we see
273 -- case x of y -> $wMkT y
274 -- the simplifier thinks that y is "sure to be evaluated" (because
275 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
277 -- When the simplifer sees a pattern
278 -- case e of MkT x -> ...
279 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
280 -- but that's fine... dataConRepStrictness comes from the data con
281 -- not from the worker Id.
283 cpr_info | isProductTyCon tycon &&
286 wkr_arity <= mAX_CPR_SIZE = retCPR
288 -- RetCPR is only true for products that are real data types;
289 -- that is, not unboxed tuples or [non-recursive] newtypes
291 ----------- Workers for newtypes --------------
292 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
293 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
294 `setArityInfo` 1 -- Arity 1
295 `setUnfoldingInfo` newtype_unf
296 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
297 newtype_unf = ASSERT2( isVanillaDataCon data_con &&
298 isSingleton orig_arg_tys, ppr data_con )
299 -- Note [Newtype datacons]
300 mkCompulsoryUnfolding $
301 mkLams wrap_tvs $ Lam id_arg1 $
302 wrapNewTypeBody tycon res_ty_args (Var id_arg1)
305 ----------- Wrapper --------------
306 -- We used to include the stupid theta in the wrapper's args
307 -- but now we don't. Instead the type checker just injects these
308 -- extra constraints where necessary.
309 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
310 res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
311 eq_tys = mkPredTys eq_theta
312 dict_tys = mkPredTys dict_theta
313 wrap_ty = mkForAllTys wrap_tvs $ mkFunTys eq_tys $ mkFunTys dict_tys $
314 mkFunTys orig_arg_tys $ res_ty
315 -- NB: watch out here if you allow user-written equality
316 -- constraints in data constructor signatures
318 ----------- Wrappers for algebraic data types --------------
319 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
320 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
321 `setArityInfo` wrap_arity
322 -- It's important to specify the arity, so that partial
323 -- applications are treated as values
324 `setUnfoldingInfo` wrap_unf
325 `setStrictnessInfo` Just wrap_sig
327 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
328 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
329 arg_dmds = map mk_dmd all_strict_marks
330 mk_dmd str | isBanged str = evalDmd
331 | otherwise = lazyDmd
332 -- The Cpr info can be important inside INLINE rhss, where the
333 -- wrapper constructor isn't inlined.
334 -- And the argument strictness can be important too; we
335 -- may not inline a contructor when it is partially applied.
337 -- data W = C !Int !Int !Int
338 -- ...(let w = C x in ...(w p q)...)...
339 -- we want to see that w is strict in its two arguments
341 wrap_unf = mkInlineRule wrap_rhs (Just (length dict_args + length id_args))
342 wrap_rhs = mkLams wrap_tvs $
344 mkLams dict_args $ mkLams id_args $
345 foldr mk_case con_app
346 (zip (dict_args ++ id_args) all_strict_marks)
349 con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
350 Var wrk_id `mkTyApps` res_ty_args
352 -- Equality evidence:
353 `mkTyApps` map snd eq_spec
355 `mkVarApps` reverse rep_ids
357 (dict_args,i2) = mkLocals 1 dict_tys
358 (id_args,i3) = mkLocals i2 orig_arg_tys
360 (eq_args,_) = mkCoVarLocals i3 eq_tys
362 mkCoVarLocals i [] = ([],i)
363 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
364 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
368 :: (Id, HsBang) -- Arg, strictness
369 -> (Int -> [Id] -> CoreExpr) -- Body
370 -> Int -- Next rep arg id
371 -> [Id] -- Rep args so far, reversed
373 mk_case (arg,strict) body i rep_args
375 HsNoBang -> body i (arg:rep_args)
376 HsUnpack -> unboxProduct i (Var arg) (idType arg) the_body
378 the_body i con_args = body i (reverse con_args ++ rep_args)
379 _other -- HsUnpackFailed and HsStrict
380 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
381 | otherwise -> Case (Var arg) arg res_ty
382 [(DEFAULT,[], body i (arg:rep_args))]
384 mAX_CPR_SIZE :: Arity
386 -- We do not treat very big tuples as CPR-ish:
387 -- a) for a start we get into trouble because there aren't
388 -- "enough" unboxed tuple types (a tiresome restriction,
390 -- b) more importantly, big unboxed tuples get returned mainly
391 -- on the stack, and are often then allocated in the heap
392 -- by the caller. So doing CPR for them may in fact make
395 mkLocals :: Int -> [Type] -> ([Id], Int)
396 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
401 Note [Newtype datacons]
402 ~~~~~~~~~~~~~~~~~~~~~~~
403 The "data constructor" for a newtype should always be vanilla. At one
404 point this wasn't true, because the newtype arising from
407 newtype T:D a = D:D (C a)
408 so the data constructor for T:C had a single argument, namely the
409 predicate (C a). But now we treat that as an ordinary argument, not
410 part of the theta-type, so all is well.
413 %************************************************************************
415 \subsection{Dictionary selectors}
417 %************************************************************************
419 Selecting a field for a dictionary. If there is just one field, then
420 there's nothing to do.
422 Dictionary selectors may get nested forall-types. Thus:
425 op :: forall b. Ord b => a -> b -> b
427 Then the top-level type for op is
429 op :: forall a. Foo a =>
433 This is unlike ordinary record selectors, which have all the for-alls
434 at the outside. When dealing with classes it's very convenient to
435 recover the original type signature from the class op selector.
438 mkDictSelId :: Bool -- True <=> don't include the unfolding
439 -- Little point on imports without -O, because the
440 -- dictionary itself won't be visible
441 -> Name -> Class -> Id
442 mkDictSelId no_unf name clas
443 = mkGlobalId (ClassOpId clas) name sel_ty info
445 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
446 -- We can't just say (exprType rhs), because that would give a type
448 -- for a single-op class (after all, the selector is the identity)
449 -- But it's type must expose the representation of the dictionary
450 -- to get (say) C a -> (a -> a)
452 base_info = noCafIdInfo
454 `setStrictnessInfo` Just strict_sig
455 `setUnfoldingInfo` (if no_unf then noUnfolding
456 else mkImplicitUnfolding rhs)
457 -- In module where class op is defined, we must add
458 -- the unfolding, even though it'll never be inlined
459 -- becuase we use that to generate a top-level binding
462 info = base_info `setSpecInfo` mkSpecInfo [rule]
463 `setInlinePragInfo` neverInlinePragma
464 -- Add a magic BuiltinRule, and never inline it
465 -- so that the rule is always available to fire.
466 -- See Note [ClassOp/DFun selection] in TcInstDcls
468 n_ty_args = length tyvars
470 -- This is the built-in rule that goes
471 -- op (dfT d1 d2) ---> opT d1 d2
472 rule = BuiltinRule { ru_name = fsLit "Class op " `appendFS`
473 occNameFS (getOccName name)
475 , ru_nargs = n_ty_args + 1
476 , ru_try = dictSelRule index n_ty_args }
478 -- The strictness signature is of the form U(AAAVAAAA) -> T
479 -- where the V depends on which item we are selecting
480 -- It's worth giving one, so that absence info etc is generated
481 -- even if the selector isn't inlined
482 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
483 arg_dmd | new_tycon = evalDmd
484 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
487 tycon = classTyCon clas
488 new_tycon = isNewTyCon tycon
489 [data_con] = tyConDataCons tycon
490 tyvars = dataConUnivTyVars data_con
491 arg_tys = {- ASSERT( isVanillaDataCon data_con ) -} dataConRepArgTys data_con
492 eq_theta = dataConEqTheta data_con
493 index = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` [0..]) name
494 the_arg_id = arg_ids !! index
496 pred = mkClassPred clas (mkTyVarTys tyvars)
497 dict_id = mkTemplateLocal 1 $ mkPredTy pred
498 (eq_ids,n) = mkCoVarLocals 2 $ mkPredTys eq_theta
499 arg_ids = mkTemplateLocalsNum n arg_tys
501 mkCoVarLocals i [] = ([],i)
502 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
503 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
506 rhs = mkLams tyvars (Lam dict_id rhs_body)
507 rhs_body | new_tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
508 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
509 [(DataAlt data_con, eq_ids ++ arg_ids, Var the_arg_id)]
511 dictSelRule :: Int -> Arity -> IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
513 -- op_i t1..tk (df s1..sn d1..dm) = op_i_helper s1..sn d1..dm
514 -- op_i t1..tk (D t1..tk op1 ... opm) = opi
516 -- NB: the data constructor has the same number of type args as the class op
518 dictSelRule index n_ty_args id_unf args
519 | (dict_arg : _) <- drop n_ty_args args
520 , Just (_, _, val_args) <- exprIsConApp_maybe id_unf dict_arg
521 = Just (val_args !! index)
527 %************************************************************************
531 %************************************************************************
534 -- unbox a product type...
535 -- we will recurse into newtypes, casting along the way, and unbox at the
536 -- first product data constructor we find. e.g.
538 -- data PairInt = PairInt Int Int
539 -- newtype S = MkS PairInt
542 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
543 -- ids, we get (modulo int passing)
545 -- case (e `cast` CoT) `cast` CoS of
546 -- PairInt a b -> body [a,b]
548 -- The Ints passed around are just for creating fresh locals
549 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
550 unboxProduct i arg arg_ty body
553 result = mkUnpackCase the_id arg con_args boxing_con rhs
554 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
555 ([the_id], i') = mkLocals i [arg_ty]
556 (con_args, i'') = mkLocals i' tys
557 rhs = body i'' con_args
559 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
560 -- (mkUnpackCase x e args Con body)
562 -- case (e `cast` ...) of bndr { Con args -> body }
564 -- the type of the bndr passed in is irrelevent
565 mkUnpackCase bndr arg unpk_args boxing_con body
566 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
568 (cast_arg, bndr_ty) = go (idType bndr) arg
570 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
571 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
572 = go (newTyConInstRhs tycon tycon_args)
573 (unwrapNewTypeBody tycon tycon_args arg)
574 | otherwise = (arg, ty)
577 reboxProduct :: [Unique] -- uniques to create new local binders
578 -> Type -- type of product to box
579 -> ([Unique], -- remaining uniques
580 CoreExpr, -- boxed product
581 [Id]) -- Ids being boxed into product
584 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
586 us' = dropList con_arg_tys us
588 arg_ids = zipWith (mkSysLocal (fsLit "rb")) us con_arg_tys
590 bind_rhs = mkProductBox arg_ids ty
593 (us', bind_rhs, arg_ids)
595 mkProductBox :: [Id] -> Type -> CoreExpr
596 mkProductBox arg_ids ty
599 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
602 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
603 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
604 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
606 wrap expr = wrapNewTypeBody tycon tycon_args expr
609 -- (mkReboxingAlt us con xs rhs) basically constructs the case
610 -- alternative (con, xs, rhs)
611 -- but it does the reboxing necessary to construct the *source*
612 -- arguments, xs, from the representation arguments ys.
614 -- data T = MkT !(Int,Int) Bool
616 -- mkReboxingAlt MkT [x,b] r
617 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
619 -- mkDataAlt should really be in DataCon, but it can't because
620 -- it manipulates CoreSyn.
623 :: [Unique] -- Uniques for the new Ids
625 -> [Var] -- Source-level args, including existential dicts
629 mkReboxingAlt us con args rhs
630 | not (any isMarkedUnboxed stricts)
631 = (DataAlt con, args, rhs)
635 (binds, args') = go args stricts us
637 (DataAlt con, args', mkLets binds rhs)
640 stricts = dataConExStricts con ++ dataConStrictMarks con
642 go [] _stricts _us = ([], [])
644 -- Type variable case
645 go (arg:args) stricts us
647 = let (binds, args') = go args stricts us
648 in (binds, arg:args')
650 -- Term variable case
651 go (arg:args) (str:stricts) us
652 | isMarkedUnboxed str
654 let (binds, unpacked_args') = go args stricts us'
655 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
657 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
659 = let (binds, args') = go args stricts us
660 in (binds, arg:args')
661 go (_ : _) [] _ = panic "mkReboxingAlt"
665 %************************************************************************
667 Wrapping and unwrapping newtypes and type families
669 %************************************************************************
672 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
673 -- The wrapper for the data constructor for a newtype looks like this:
674 -- newtype T a = MkT (a,Int)
675 -- MkT :: forall a. (a,Int) -> T a
676 -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
677 -- where CoT is the coercion TyCon assoicated with the newtype
679 -- The call (wrapNewTypeBody T [a] e) returns the
680 -- body of the wrapper, namely
681 -- e `cast` (CoT [a])
683 -- If a coercion constructor is provided in the newtype, then we use
684 -- it, otherwise the wrap/unwrap are both no-ops
686 -- If the we are dealing with a newtype *instance*, we have a second coercion
687 -- identifying the family instance with the constructor of the newtype
688 -- instance. This coercion is applied in any case (ie, composed with the
689 -- coercion constructor of the newtype or applied by itself).
691 wrapNewTypeBody tycon args result_expr
692 = wrapFamInstBody tycon args inner
695 | Just co_con <- newTyConCo_maybe tycon
696 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
700 -- When unwrapping, we do *not* apply any family coercion, because this will
701 -- be done via a CoPat by the type checker. We have to do it this way as
702 -- computing the right type arguments for the coercion requires more than just
703 -- a spliting operation (cf, TcPat.tcConPat).
705 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
706 unwrapNewTypeBody tycon args result_expr
707 | Just co_con <- newTyConCo_maybe tycon
708 = mkCoerce (mkTyConApp co_con args) result_expr
712 -- If the type constructor is a representation type of a data instance, wrap
713 -- the expression into a cast adjusting the expression type, which is an
714 -- instance of the representation type, to the corresponding instance of the
715 -- family instance type.
716 -- See Note [Wrappers for data instance tycons]
717 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
718 wrapFamInstBody tycon args body
719 | Just co_con <- tyConFamilyCoercion_maybe tycon
720 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
724 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
725 unwrapFamInstScrut tycon args scrut
726 | Just co_con <- tyConFamilyCoercion_maybe tycon
727 = mkCoerce (mkTyConApp co_con args) scrut
733 %************************************************************************
735 \subsection{Primitive operations}
737 %************************************************************************
740 mkPrimOpId :: PrimOp -> Id
744 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
745 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
746 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
747 (mkPrimOpIdUnique (primOpTag prim_op))
749 id = mkGlobalId (PrimOpId prim_op) name ty info
752 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
754 `setStrictnessInfo` Just strict_sig
756 -- For each ccall we manufacture a separate CCallOpId, giving it
757 -- a fresh unique, a type that is correct for this particular ccall,
758 -- and a CCall structure that gives the correct details about calling
761 -- The *name* of this Id is a local name whose OccName gives the full
762 -- details of the ccall, type and all. This means that the interface
763 -- file reader can reconstruct a suitable Id
765 mkFCallId :: Unique -> ForeignCall -> Type -> Id
766 mkFCallId uniq fcall ty
767 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
768 -- A CCallOpId should have no free type variables;
769 -- when doing substitutions won't substitute over it
770 mkGlobalId (FCallId fcall) name ty info
772 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
773 -- The "occurrence name" of a ccall is the full info about the
774 -- ccall; it is encoded, but may have embedded spaces etc!
776 name = mkFCallName uniq occ_str
780 `setStrictnessInfo` Just strict_sig
782 (_, tau) = tcSplitForAllTys ty
783 (arg_tys, _) = tcSplitFunTys tau
784 arity = length arg_tys
785 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
787 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
788 -- except for the type:
790 -- a plain HPC tick box has type (State# RealWorld)
791 -- a breakpoint Id has type forall a.a
793 -- The breakpoint Id will be applied to a list of arbitrary free variables,
794 -- which is why it needs a polymorphic type.
796 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
797 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
799 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
800 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
801 where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
803 mkTickBox' :: Unique -> Module -> TickBoxId -> Type -> Id
804 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info
806 tickbox = TickBox mod ix
807 occ_str = showSDoc (braces (ppr tickbox))
808 name = mkTickBoxOpName uniq occ_str
813 %************************************************************************
815 \subsection{DictFuns and default methods}
817 %************************************************************************
819 Important notes about dict funs and default methods
820 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
821 Dict funs and default methods are *not* ImplicitIds. Their definition
822 involves user-written code, so we can't figure out their strictness etc
823 based on fixed info, as we can for constructors and record selectors (say).
825 We build them as LocalIds, but with External Names. This ensures that
826 they are taken to account by free-variable finding and dependency
827 analysis (e.g. CoreFVs.exprFreeVars).
829 Why shouldn't they be bound as GlobalIds? Because, in particular, if
830 they are globals, the specialiser floats dict uses above their defns,
831 which prevents good simplifications happening. Also the strictness
832 analyser treats a occurrence of a GlobalId as imported and assumes it
833 contains strictness in its IdInfo, which isn't true if the thing is
834 bound in the same module as the occurrence.
836 It's OK for dfuns to be LocalIds, because we form the instance-env to
837 pass on to the next module (md_insts) in CoreTidy, afer tidying
838 and globalising the top-level Ids.
840 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
841 that they aren't discarded by the occurrence analyser.
844 mkDefaultMethodId :: Id -- Selector Id
845 -> Name -- Default method name
846 -> Id -- Default method Id
847 mkDefaultMethodId sel_id dm_name = mkExportedLocalId dm_name (idType sel_id)
849 mkDictFunId :: Name -- Name to use for the dict fun;
856 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
857 = mkExportedLocalVar (DFunId is_nt) dfun_name dfun_ty vanillaIdInfo
859 is_nt = isNewTyCon (classTyCon clas)
860 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
864 %************************************************************************
866 \subsection{Un-definable}
868 %************************************************************************
870 These Ids can't be defined in Haskell. They could be defined in
871 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
872 ensure that they were definitely, definitely inlined, because there is
873 no curried identifier for them. That's what mkCompulsoryUnfolding
874 does. If we had a way to get a compulsory unfolding from an interface
875 file, we could do that, but we don't right now.
877 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
878 just gets expanded into a type coercion wherever it occurs. Hence we
879 add it as a built-in Id with an unfolding here.
881 The type variables we use here are "open" type variables: this means
882 they can unify with both unlifted and lifted types. Hence we provide
883 another gun with which to shoot yourself in the foot.
886 mkWiredInIdName :: Module -> FastString -> Unique -> Id -> Name
887 mkWiredInIdName mod fs uniq id
888 = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
890 unsafeCoerceName, nullAddrName, seqName, realWorldName :: Name
891 lazyIdName, errorName, recSelErrorName, runtimeErrorName :: Name
892 irrefutPatErrorName, recConErrorName, patErrorName :: Name
893 nonExhaustiveGuardsErrorName, noMethodBindingErrorName :: Name
894 unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
895 nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId
896 seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId
897 realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId
898 lazyIdName = mkWiredInIdName gHC_BASE (fsLit "lazy") lazyIdKey lazyId
900 errorName = mkWiredInIdName gHC_ERR (fsLit "error") errorIdKey eRROR_ID
901 recSelErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
902 runtimeErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
903 irrefutPatErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
904 recConErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recConError") recConErrorIdKey rEC_CON_ERROR_ID
905 patErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "patError") patErrorIdKey pAT_ERROR_ID
906 noMethodBindingErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "noMethodBindingError")
907 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
908 nonExhaustiveGuardsErrorName
909 = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "nonExhaustiveGuardsError")
910 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
914 ------------------------------------------------
915 -- unsafeCoerce# :: forall a b. a -> b
918 = pcMiscPrelId unsafeCoerceName ty info
920 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
923 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
924 (mkFunTy openAlphaTy openBetaTy)
925 [x] = mkTemplateLocals [openAlphaTy]
926 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
927 Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
929 ------------------------------------------------
931 -- nullAddr# :: Addr#
932 -- The reason is is here is because we don't provide
933 -- a way to write this literal in Haskell.
934 nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info
936 info = noCafIdInfo `setUnfoldingInfo`
937 mkCompulsoryUnfolding (Lit nullAddrLit)
939 ------------------------------------------------
940 seqId :: Id -- See Note [seqId magic]
941 seqId = pcMiscPrelId seqName ty info
943 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
944 `setSpecInfo` mkSpecInfo [seq_cast_rule]
947 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
948 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
949 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
950 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
952 -- See Note [Built-in RULES for seq]
953 seq_cast_rule = BuiltinRule { ru_name = fsLit "seq of cast"
956 , ru_try = match_seq_of_cast
959 match_seq_of_cast :: IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
960 -- See Note [Built-in RULES for seq]
961 match_seq_of_cast _ [Type _, Type res_ty, Cast scrut co, expr]
962 = Just (Var seqId `mkApps` [Type (fst (coercionKind co)), Type res_ty,
964 match_seq_of_cast _ _ = Nothing
966 ------------------------------------------------
967 lazyId :: Id -- See Note [lazyId magic]
968 lazyId = pcMiscPrelId lazyIdName ty info
971 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
976 'GHC.Prim.seq' is special in several ways.
978 a) Its second arg can have an unboxed type
981 b) Its fixity is set in LoadIface.ghcPrimIface
983 c) It has quite a bit of desugaring magic.
984 See DsUtils.lhs Note [Desugaring seq (1)] and (2) and (3)
986 d) There is some special rule handing: Note [User-defined RULES for seq]
988 Note [User-defined RULES for seq]
989 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
990 Roman found situations where he had
992 where he knew that f (which was strict in n) would terminate if n did.
993 Notice that the result of (f n) is discarded. So it makes sense to
997 Rather than attempt some general analysis to support this, I've added
998 enough support that you can do this using a rewrite rule:
1000 RULE "f/seq" forall n. seq (f n) e = seq n e
1002 You write that rule. When GHC sees a case expression that discards
1003 its result, it mentally transforms it to a call to 'seq' and looks for
1004 a RULE. (This is done in Simplify.rebuildCase.) As usual, the
1005 correctness of the rule is up to you.
1007 To make this work, we need to be careful that the magical desugaring
1008 done in Note [seqId magic] item (c) is *not* done on the LHS of a rule.
1009 Or rather, we arrange to un-do it, in DsBinds.decomposeRuleLhs.
1011 Note [Built-in RULES for seq]
1012 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1013 We also have the following built-in rule for seq
1015 seq (x `cast` co) y = seq x y
1017 This eliminates unnecessary casts and also allows other seq rules to
1018 match more often. Notably,
1020 seq (f x `cast` co) y --> seq (f x) y
1022 and now a user-defined rule for seq (see Note [User-defined RULES for seq])
1028 lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
1030 Used to lazify pseq: pseq a b = a `seq` lazy b
1032 Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1033 not from GHC.Base.hi. This is important, because the strictness
1034 analyser will spot it as strict!
1036 Also no unfolding in lazyId: it gets "inlined" by a HACK in CorePrep.
1037 It's very important to do this inlining *after* unfoldings are exposed
1038 in the interface file. Otherwise, the unfolding for (say) pseq in the
1039 interface file will not mention 'lazy', so if we inline 'pseq' we'll totally
1040 miss the very thing that 'lazy' was there for in the first place.
1041 See Trac #3259 for a real world example.
1043 lazyId is defined in GHC.Base, so we don't *have* to inline it. If it
1044 appears un-applied, we'll end up just calling it.
1046 -------------------------------------------------------------
1047 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1048 nasty as-is, change it back to a literal (@Literal@).
1050 voidArgId is a Local Id used simply as an argument in functions
1051 where we just want an arg to avoid having a thunk of unlifted type.
1053 x = \ void :: State# RealWorld -> (# p, q #)
1055 This comes up in strictness analysis
1058 realWorldPrimId :: Id
1059 realWorldPrimId -- :: State# RealWorld
1060 = pcMiscPrelId realWorldName realWorldStatePrimTy
1061 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1062 -- The evaldUnfolding makes it look that realWorld# is evaluated
1063 -- which in turn makes Simplify.interestingArg return True,
1064 -- which in turn makes INLINE things applied to realWorld# likely
1068 voidArgId -- :: State# RealWorld
1069 = mkSysLocal (fsLit "void") voidArgIdKey realWorldStatePrimTy
1073 %************************************************************************
1075 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1077 %************************************************************************
1079 GHC randomly injects these into the code.
1081 @patError@ is just a version of @error@ for pattern-matching
1082 failures. It knows various ``codes'' which expand to longer
1083 strings---this saves space!
1085 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
1086 well shouldn't be yanked on, but if one is, then you will get a
1087 friendly message from @absentErr@ (rather than a totally random
1090 @parError@ is a special version of @error@ which the compiler does
1091 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
1092 templates, but we don't ever expect to generate code for it.
1096 :: Id -- Should be of type (forall a. Addr# -> a)
1097 -- where Addr# points to a UTF8 encoded string
1098 -> Type -- The type to instantiate 'a'
1099 -> String -- The string to print
1102 mkRuntimeErrorApp err_id res_ty err_msg
1103 = mkApps (Var err_id) [Type res_ty, err_string]
1105 err_string = Lit (mkMachString err_msg)
1107 mkImpossibleExpr :: Type -> CoreExpr
1108 mkImpossibleExpr res_ty
1109 = mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty "Impossible case alternative"
1111 rEC_SEL_ERROR_ID, rUNTIME_ERROR_ID, iRREFUT_PAT_ERROR_ID, rEC_CON_ERROR_ID :: Id
1112 pAT_ERROR_ID, nO_METHOD_BINDING_ERROR_ID, nON_EXHAUSTIVE_GUARDS_ERROR_ID :: Id
1113 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
1114 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
1115 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
1116 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
1117 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
1118 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
1119 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1121 -- The runtime error Ids take a UTF8-encoded string as argument
1123 mkRuntimeErrorId :: Name -> Id
1124 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1126 runtimeErrorTy :: Type
1127 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1132 eRROR_ID = pc_bottoming_Id errorName errorTy
1135 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1136 -- Notice the openAlphaTyVar. It says that "error" can be applied
1137 -- to unboxed as well as boxed types. This is OK because it never
1138 -- returns, so the return type is irrelevant.
1142 %************************************************************************
1144 \subsection{Utilities}
1146 %************************************************************************
1149 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1150 pcMiscPrelId name ty info
1151 = mkVanillaGlobalWithInfo name ty info
1152 -- We lie and say the thing is imported; otherwise, we get into
1153 -- a mess with dependency analysis; e.g., core2stg may heave in
1154 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1155 -- being compiled, then it's just a matter of luck if the definition
1156 -- will be in "the right place" to be in scope.
1158 pc_bottoming_Id :: Name -> Type -> Id
1159 -- Function of arity 1, which diverges after being given one argument
1160 pc_bottoming_Id name ty
1161 = pcMiscPrelId name ty bottoming_info
1163 bottoming_info = vanillaIdInfo `setStrictnessInfo` Just strict_sig
1165 -- Make arity and strictness agree
1167 -- Do *not* mark them as NoCafRefs, because they can indeed have
1168 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1169 -- which has some CAFs
1170 -- In due course we may arrange that these error-y things are
1171 -- regarded by the GC as permanently live, in which case we
1172 -- can give them NoCaf info. As it is, any function that calls
1173 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1176 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1177 -- These "bottom" out, no matter what their arguments