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"
56 import CoreUtils ( exprType, mkCoerce )
68 import Var ( Var, TyVar, mkCoVar, mkExportedLocalVar )
75 import BasicTypes hiding ( SuccessFlag(..) )
83 %************************************************************************
85 \subsection{Wired in Ids}
87 %************************************************************************
91 There are several reasons why an Id might appear in the wiredInIds:
93 (1) The ghcPrimIds are wired in because they can't be defined in
94 Haskell at all, although the can be defined in Core. They have
95 compulsory unfoldings, so they are always inlined and they have
96 no definition site. Their home module is GHC.Prim, so they
97 also have a description in primops.txt.pp, where they are called
100 (2) The 'error' function, eRROR_ID, is wired in because we don't yet have
101 a way to express in an interface file that the result type variable
102 is 'open'; that is can be unified with an unboxed type
104 [The interface file format now carry such information, but there's
105 no way yet of expressing at the definition site for these
106 error-reporting functions that they have an 'open'
107 result type. -- sof 1/99]
109 (3) Other error functions (rUNTIME_ERROR_ID) are wired in (a) because
110 the desugarer generates code that mentiones them directly, and
111 (b) for the same reason as eRROR_ID
113 (4) lazyId is wired in because the wired-in version overrides the
114 strictness of the version defined in GHC.Base
116 In cases (2-4), the function has a definition in a library module, and
117 can be called; but the wired-in version means that the details are
118 never read from that module's interface file; instead, the full definition
126 eRROR_ID, -- This one isn't used anywhere else in the compiler
127 -- But we still need it in wiredInIds so that when GHC
128 -- compiles a program that mentions 'error' we don't
129 -- import its type from the interface file; we just get
130 -- the Id defined here. Which has an 'open-tyvar' type.
133 iRREFUT_PAT_ERROR_ID,
134 nON_EXHAUSTIVE_GUARDS_ERROR_ID,
135 nO_METHOD_BINDING_ERROR_ID,
143 -- These Ids are exported from GHC.Prim
146 = [ -- These can't be defined in Haskell, but they have
147 -- perfectly reasonable unfoldings in Core
155 %************************************************************************
157 \subsection{Data constructors}
159 %************************************************************************
161 The wrapper for a constructor is an ordinary top-level binding that evaluates
162 any strict args, unboxes any args that are going to be flattened, and calls
165 We're going to build a constructor that looks like:
167 data (Data a, C b) => T a b = T1 !a !Int b
170 \d1::Data a, d2::C b ->
171 \p q r -> case p of { p ->
173 Con T1 [a,b] [p,q,r]}}
177 * d2 is thrown away --- a context in a data decl is used to make sure
178 one *could* construct dictionaries at the site the constructor
179 is used, but the dictionary isn't actually used.
181 * We have to check that we can construct Data dictionaries for
182 the types a and Int. Once we've done that we can throw d1 away too.
184 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
185 all that matters is that the arguments are evaluated. "seq" is
186 very careful to preserve evaluation order, which we don't need
189 You might think that we could simply give constructors some strictness
190 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
191 But we don't do that because in the case of primops and functions strictness
192 is a *property* not a *requirement*. In the case of constructors we need to
193 do something active to evaluate the argument.
195 Making an explicit case expression allows the simplifier to eliminate
196 it in the (common) case where the constructor arg is already evaluated.
198 Note [Wrappers for data instance tycons]
199 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
200 In the case of data instances, the wrapper also applies the coercion turning
201 the representation type into the family instance type to cast the result of
202 the wrapper. For example, consider the declarations
204 data family Map k :: * -> *
205 data instance Map (a, b) v = MapPair (Map a (Pair b v))
207 The tycon to which the datacon MapPair belongs gets a unique internal
208 name of the form :R123Map, and we call it the representation tycon.
209 In contrast, Map is the family tycon (accessible via
210 tyConFamInst_maybe). A coercion allows you to move between
211 representation and family type. It is accessible from :R123Map via
212 tyConFamilyCoercion_maybe and has kind
214 Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
216 The wrapper and worker of MapPair get the types
219 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
220 $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v)
223 MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
225 This coercion is conditionally applied by wrapFamInstBody.
227 It's a bit more complicated if the data instance is a GADT as well!
229 data instance T [a] where
230 T1 :: forall b. b -> T [Maybe b]
232 Co7T a :: T [a] ~ :R7T a
237 $WT1 :: forall b. b -> T [Maybe b]
238 $WT1 b v = T1 (Maybe b) b (Maybe b) v
239 `cast` sym (Co7T (Maybe b))
242 T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
245 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
246 mkDataConIds wrap_name wkr_name data_con
247 | isNewTyCon tycon -- Newtype, only has a worker
248 = DCIds Nothing nt_work_id
250 | any isMarkedStrict all_strict_marks -- Algebraic, needs wrapper
251 || not (null eq_spec) -- NB: LoadIface.ifaceDeclSubBndrs
252 || isFamInstTyCon tycon -- depends on this test
253 = DCIds (Just alg_wrap_id) wrk_id
255 | otherwise -- Algebraic, no wrapper
256 = DCIds Nothing wrk_id
258 (univ_tvs, ex_tvs, eq_spec,
259 eq_theta, dict_theta, orig_arg_tys, res_ty) = dataConFullSig data_con
260 tycon = dataConTyCon data_con -- The representation TyCon (not family)
262 ----------- Worker (algebraic data types only) --------------
263 -- The *worker* for the data constructor is the function that
264 -- takes the representation arguments and builds the constructor.
265 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
266 (dataConRepType data_con) wkr_info
268 wkr_arity = dataConRepArity data_con
269 wkr_info = noCafIdInfo
270 `setArityInfo` wkr_arity
271 `setAllStrictnessInfo` Just wkr_sig
272 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
275 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
276 -- Note [Data-con worker strictness]
277 -- Notice that we do *not* say the worker is strict
278 -- even if the data constructor is declared strict
279 -- e.g. data T = MkT !(Int,Int)
280 -- Why? Because the *wrapper* is strict (and its unfolding has case
281 -- expresssions that do the evals) but the *worker* itself is not.
282 -- If we pretend it is strict then when we see
283 -- case x of y -> $wMkT y
284 -- the simplifier thinks that y is "sure to be evaluated" (because
285 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
287 -- When the simplifer sees a pattern
288 -- case e of MkT x -> ...
289 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
290 -- but that's fine... dataConRepStrictness comes from the data con
291 -- not from the worker Id.
293 cpr_info | isProductTyCon tycon &&
296 wkr_arity <= mAX_CPR_SIZE = retCPR
298 -- RetCPR is only true for products that are real data types;
299 -- that is, not unboxed tuples or [non-recursive] newtypes
301 ----------- Workers for newtypes --------------
302 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
303 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
304 `setArityInfo` 1 -- Arity 1
305 `setUnfoldingInfo` newtype_unf
306 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
307 newtype_unf = ASSERT2( isVanillaDataCon data_con &&
308 isSingleton orig_arg_tys, ppr data_con )
309 -- Note [Newtype datacons]
310 mkCompulsoryUnfolding $
311 mkLams wrap_tvs $ Lam id_arg1 $
312 wrapNewTypeBody tycon res_ty_args (Var id_arg1)
315 ----------- Wrapper --------------
316 -- We used to include the stupid theta in the wrapper's args
317 -- but now we don't. Instead the type checker just injects these
318 -- extra constraints where necessary.
319 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
320 res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
321 eq_tys = mkPredTys eq_theta
322 dict_tys = mkPredTys dict_theta
323 wrap_ty = mkForAllTys wrap_tvs $ mkFunTys eq_tys $ mkFunTys dict_tys $
324 mkFunTys orig_arg_tys $ res_ty
325 -- NB: watch out here if you allow user-written equality
326 -- constraints in data constructor signatures
328 ----------- Wrappers for algebraic data types --------------
329 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
330 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
331 `setArityInfo` wrap_arity
332 -- It's important to specify the arity, so that partial
333 -- applications are treated as values
334 `setUnfoldingInfo` wrap_unf
335 `setAllStrictnessInfo` Just wrap_sig
337 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
338 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
339 arg_dmds = map mk_dmd all_strict_marks
340 mk_dmd str | isMarkedStrict str = evalDmd
341 | otherwise = lazyDmd
342 -- The Cpr info can be important inside INLINE rhss, where the
343 -- wrapper constructor isn't inlined.
344 -- And the argument strictness can be important too; we
345 -- may not inline a contructor when it is partially applied.
347 -- data W = C !Int !Int !Int
348 -- ...(let w = C x in ...(w p q)...)...
349 -- we want to see that w is strict in its two arguments
351 wrap_unf = mkImplicitUnfolding $ Note InlineMe $
354 mkLams dict_args $ mkLams id_args $
355 foldr mk_case con_app
356 (zip (dict_args ++ id_args) all_strict_marks)
359 con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
360 Var wrk_id `mkTyApps` res_ty_args
362 -- Equality evidence:
363 `mkTyApps` map snd eq_spec
365 `mkVarApps` reverse rep_ids
367 (dict_args,i2) = mkLocals 1 dict_tys
368 (id_args,i3) = mkLocals i2 orig_arg_tys
370 (eq_args,_) = mkCoVarLocals i3 eq_tys
372 mkCoVarLocals i [] = ([],i)
373 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
374 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
378 :: (Id, StrictnessMark) -- Arg, strictness
379 -> (Int -> [Id] -> CoreExpr) -- Body
380 -> Int -- Next rep arg id
381 -> [Id] -- Rep args so far, reversed
383 mk_case (arg,strict) body i rep_args
385 NotMarkedStrict -> body i (arg:rep_args)
387 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
389 Case (Var arg) arg res_ty [(DEFAULT,[], body i (arg:rep_args))]
392 -> unboxProduct i (Var arg) (idType arg) the_body
394 the_body i con_args = body i (reverse con_args ++ rep_args)
396 mAX_CPR_SIZE :: Arity
398 -- We do not treat very big tuples as CPR-ish:
399 -- a) for a start we get into trouble because there aren't
400 -- "enough" unboxed tuple types (a tiresome restriction,
402 -- b) more importantly, big unboxed tuples get returned mainly
403 -- on the stack, and are often then allocated in the heap
404 -- by the caller. So doing CPR for them may in fact make
407 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
412 Note [Newtype datacons]
413 ~~~~~~~~~~~~~~~~~~~~~~~
414 The "data constructor" for a newtype should always be vanilla. At one
415 point this wasn't true, because the newtype arising from
418 newtype T:D a = D:D (C a)
419 so the data constructor for T:C had a single argument, namely the
420 predicate (C a). But now we treat that as an ordinary argument, not
421 part of the theta-type, so all is well.
424 %************************************************************************
426 \subsection{Dictionary selectors}
428 %************************************************************************
430 Selecting a field for a dictionary. If there is just one field, then
431 there's nothing to do.
433 Dictionary selectors may get nested forall-types. Thus:
436 op :: forall b. Ord b => a -> b -> b
438 Then the top-level type for op is
440 op :: forall a. Foo a =>
444 This is unlike ordinary record selectors, which have all the for-alls
445 at the outside. When dealing with classes it's very convenient to
446 recover the original type signature from the class op selector.
449 mkDictSelId :: Bool -- True <=> don't include the unfolding
450 -- Little point on imports without -O, because the
451 -- dictionary itself won't be visible
452 -> Name -> Class -> Id
453 mkDictSelId no_unf name clas
454 = mkGlobalId (ClassOpId clas) name sel_ty info
456 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
457 -- We can't just say (exprType rhs), because that would give a type
459 -- for a single-op class (after all, the selector is the identity)
460 -- But it's type must expose the representation of the dictionary
461 -- to get (say) C a -> (a -> a)
465 `setAllStrictnessInfo` Just strict_sig
466 `setUnfoldingInfo` (if no_unf then noUnfolding
467 else mkImplicitUnfolding rhs)
469 -- We no longer use 'must-inline' on record selectors. They'll
470 -- inline like crazy if they scrutinise a constructor
472 -- The strictness signature is of the form U(AAAVAAAA) -> T
473 -- where the V depends on which item we are selecting
474 -- It's worth giving one, so that absence info etc is generated
475 -- even if the selector isn't inlined
476 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
477 arg_dmd | isNewTyCon tycon = evalDmd
478 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
481 tycon = classTyCon clas
482 [data_con] = tyConDataCons tycon
483 tyvars = dataConUnivTyVars data_con
484 arg_tys = {- ASSERT( isVanillaDataCon data_con ) -} dataConRepArgTys data_con
485 eq_theta = dataConEqTheta data_con
486 the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
488 pred = mkClassPred clas (mkTyVarTys tyvars)
489 dict_id = mkTemplateLocal 1 $ mkPredTy pred
490 (eq_ids,n) = mkCoVarLocals 2 $ mkPredTys eq_theta
491 arg_ids = mkTemplateLocalsNum n arg_tys
493 mkCoVarLocals i [] = ([],i)
494 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
495 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
498 rhs = mkLams tyvars (Lam dict_id rhs_body)
499 rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
500 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
501 [(DataAlt data_con, eq_ids ++ arg_ids, Var the_arg_id)]
505 %************************************************************************
509 %************************************************************************
512 -- unbox a product type...
513 -- we will recurse into newtypes, casting along the way, and unbox at the
514 -- first product data constructor we find. e.g.
516 -- data PairInt = PairInt Int Int
517 -- newtype S = MkS PairInt
520 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
521 -- ids, we get (modulo int passing)
523 -- case (e `cast` CoT) `cast` CoS of
524 -- PairInt a b -> body [a,b]
526 -- The Ints passed around are just for creating fresh locals
527 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
528 unboxProduct i arg arg_ty body
531 result = mkUnpackCase the_id arg con_args boxing_con rhs
532 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
533 ([the_id], i') = mkLocals i [arg_ty]
534 (con_args, i'') = mkLocals i' tys
535 rhs = body i'' con_args
537 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
538 -- (mkUnpackCase x e args Con body)
540 -- case (e `cast` ...) of bndr { Con args -> body }
542 -- the type of the bndr passed in is irrelevent
543 mkUnpackCase bndr arg unpk_args boxing_con body
544 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
546 (cast_arg, bndr_ty) = go (idType bndr) arg
548 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
549 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
550 = go (newTyConInstRhs tycon tycon_args)
551 (unwrapNewTypeBody tycon tycon_args arg)
552 | otherwise = (arg, ty)
555 reboxProduct :: [Unique] -- uniques to create new local binders
556 -> Type -- type of product to box
557 -> ([Unique], -- remaining uniques
558 CoreExpr, -- boxed product
559 [Id]) -- Ids being boxed into product
562 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
564 us' = dropList con_arg_tys us
566 arg_ids = zipWith (mkSysLocal (fsLit "rb")) us con_arg_tys
568 bind_rhs = mkProductBox arg_ids ty
571 (us', bind_rhs, arg_ids)
573 mkProductBox :: [Id] -> Type -> CoreExpr
574 mkProductBox arg_ids ty
577 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
580 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
581 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
582 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
584 wrap expr = wrapNewTypeBody tycon tycon_args expr
587 -- (mkReboxingAlt us con xs rhs) basically constructs the case
588 -- alternative (con, xs, rhs)
589 -- but it does the reboxing necessary to construct the *source*
590 -- arguments, xs, from the representation arguments ys.
592 -- data T = MkT !(Int,Int) Bool
594 -- mkReboxingAlt MkT [x,b] r
595 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
597 -- mkDataAlt should really be in DataCon, but it can't because
598 -- it manipulates CoreSyn.
601 :: [Unique] -- Uniques for the new Ids
603 -> [Var] -- Source-level args, including existential dicts
607 mkReboxingAlt us con args rhs
608 | not (any isMarkedUnboxed stricts)
609 = (DataAlt con, args, rhs)
613 (binds, args') = go args stricts us
615 (DataAlt con, args', mkLets binds rhs)
618 stricts = dataConExStricts con ++ dataConStrictMarks con
620 go [] _stricts _us = ([], [])
622 -- Type variable case
623 go (arg:args) stricts us
625 = let (binds, args') = go args stricts us
626 in (binds, arg:args')
628 -- Term variable case
629 go (arg:args) (str:stricts) us
630 | isMarkedUnboxed str
632 let (binds, unpacked_args') = go args stricts us'
633 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
635 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
637 = let (binds, args') = go args stricts us
638 in (binds, arg:args')
639 go (_ : _) [] _ = panic "mkReboxingAlt"
643 %************************************************************************
645 Wrapping and unwrapping newtypes and type families
647 %************************************************************************
650 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
651 -- The wrapper for the data constructor for a newtype looks like this:
652 -- newtype T a = MkT (a,Int)
653 -- MkT :: forall a. (a,Int) -> T a
654 -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
655 -- where CoT is the coercion TyCon assoicated with the newtype
657 -- The call (wrapNewTypeBody T [a] e) returns the
658 -- body of the wrapper, namely
659 -- e `cast` (CoT [a])
661 -- If a coercion constructor is provided in the newtype, then we use
662 -- it, otherwise the wrap/unwrap are both no-ops
664 -- If the we are dealing with a newtype *instance*, we have a second coercion
665 -- identifying the family instance with the constructor of the newtype
666 -- instance. This coercion is applied in any case (ie, composed with the
667 -- coercion constructor of the newtype or applied by itself).
669 wrapNewTypeBody tycon args result_expr
670 = wrapFamInstBody tycon args inner
673 | Just co_con <- newTyConCo_maybe tycon
674 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
678 -- When unwrapping, we do *not* apply any family coercion, because this will
679 -- be done via a CoPat by the type checker. We have to do it this way as
680 -- computing the right type arguments for the coercion requires more than just
681 -- a spliting operation (cf, TcPat.tcConPat).
683 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
684 unwrapNewTypeBody tycon args result_expr
685 | Just co_con <- newTyConCo_maybe tycon
686 = mkCoerce (mkTyConApp co_con args) result_expr
690 -- If the type constructor is a representation type of a data instance, wrap
691 -- the expression into a cast adjusting the expression type, which is an
692 -- instance of the representation type, to the corresponding instance of the
693 -- family instance type.
694 -- See Note [Wrappers for data instance tycons]
695 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
696 wrapFamInstBody tycon args body
697 | Just co_con <- tyConFamilyCoercion_maybe tycon
698 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
702 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
703 unwrapFamInstScrut tycon args scrut
704 | Just co_con <- tyConFamilyCoercion_maybe tycon
705 = mkCoerce (mkTyConApp co_con args) scrut
711 %************************************************************************
713 \subsection{Primitive operations}
715 %************************************************************************
718 mkPrimOpId :: PrimOp -> Id
722 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
723 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
724 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
725 (mkPrimOpIdUnique (primOpTag prim_op))
727 id = mkGlobalId (PrimOpId prim_op) name ty info
730 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
732 `setAllStrictnessInfo` Just strict_sig
734 -- For each ccall we manufacture a separate CCallOpId, giving it
735 -- a fresh unique, a type that is correct for this particular ccall,
736 -- and a CCall structure that gives the correct details about calling
739 -- The *name* of this Id is a local name whose OccName gives the full
740 -- details of the ccall, type and all. This means that the interface
741 -- file reader can reconstruct a suitable Id
743 mkFCallId :: Unique -> ForeignCall -> Type -> Id
744 mkFCallId uniq fcall ty
745 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
746 -- A CCallOpId should have no free type variables;
747 -- when doing substitutions won't substitute over it
748 mkGlobalId (FCallId fcall) name ty info
750 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
751 -- The "occurrence name" of a ccall is the full info about the
752 -- ccall; it is encoded, but may have embedded spaces etc!
754 name = mkFCallName uniq occ_str
758 `setAllStrictnessInfo` Just strict_sig
760 (_, tau) = tcSplitForAllTys ty
761 (arg_tys, _) = tcSplitFunTys tau
762 arity = length arg_tys
763 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
765 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
766 -- except for the type:
768 -- a plain HPC tick box has type (State# RealWorld)
769 -- a breakpoint Id has type forall a.a
771 -- The breakpoint Id will be applied to a list of arbitrary free variables,
772 -- which is why it needs a polymorphic type.
774 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
775 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
777 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
778 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
779 where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
781 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info
783 tickbox = TickBox mod ix
784 occ_str = showSDoc (braces (ppr tickbox))
785 name = mkTickBoxOpName uniq occ_str
790 %************************************************************************
792 \subsection{DictFuns and default methods}
794 %************************************************************************
796 Important notes about dict funs and default methods
797 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
798 Dict funs and default methods are *not* ImplicitIds. Their definition
799 involves user-written code, so we can't figure out their strictness etc
800 based on fixed info, as we can for constructors and record selectors (say).
802 We build them as LocalIds, but with External Names. This ensures that
803 they are taken to account by free-variable finding and dependency
804 analysis (e.g. CoreFVs.exprFreeVars).
806 Why shouldn't they be bound as GlobalIds? Because, in particular, if
807 they are globals, the specialiser floats dict uses above their defns,
808 which prevents good simplifications happening. Also the strictness
809 analyser treats a occurrence of a GlobalId as imported and assumes it
810 contains strictness in its IdInfo, which isn't true if the thing is
811 bound in the same module as the occurrence.
813 It's OK for dfuns to be LocalIds, because we form the instance-env to
814 pass on to the next module (md_insts) in CoreTidy, afer tidying
815 and globalising the top-level Ids.
817 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
818 that they aren't discarded by the occurrence analyser.
821 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
823 mkDictFunId :: Name -- Name to use for the dict fun;
830 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
831 = mkExportedLocalVar DFunId dfun_name dfun_ty vanillaIdInfo
833 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
837 %************************************************************************
839 \subsection{Un-definable}
841 %************************************************************************
843 These Ids can't be defined in Haskell. They could be defined in
844 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
845 ensure that they were definitely, definitely inlined, because there is
846 no curried identifier for them. That's what mkCompulsoryUnfolding
847 does. If we had a way to get a compulsory unfolding from an interface
848 file, we could do that, but we don't right now.
850 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
851 just gets expanded into a type coercion wherever it occurs. Hence we
852 add it as a built-in Id with an unfolding here.
854 The type variables we use here are "open" type variables: this means
855 they can unify with both unlifted and lifted types. Hence we provide
856 another gun with which to shoot yourself in the foot.
859 mkWiredInIdName mod fs uniq id
860 = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
862 unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
863 nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId
864 seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId
865 realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId
866 lazyIdName = mkWiredInIdName gHC_BASE (fsLit "lazy") lazyIdKey lazyId
868 errorName = mkWiredInIdName gHC_ERR (fsLit "error") errorIdKey eRROR_ID
869 recSelErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
870 runtimeErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
871 irrefutPatErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
872 recConErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recConError") recConErrorIdKey rEC_CON_ERROR_ID
873 patErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "patError") patErrorIdKey pAT_ERROR_ID
874 noMethodBindingErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "noMethodBindingError")
875 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
876 nonExhaustiveGuardsErrorName
877 = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "nonExhaustiveGuardsError")
878 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
882 ------------------------------------------------
883 -- unsafeCoerce# :: forall a b. a -> b
885 = pcMiscPrelId unsafeCoerceName ty info
887 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
890 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
891 (mkFunTy openAlphaTy openBetaTy)
892 [x] = mkTemplateLocals [openAlphaTy]
893 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
894 Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
896 ------------------------------------------------
898 -- nullAddr# :: Addr#
899 -- The reason is is here is because we don't provide
900 -- a way to write this literal in Haskell.
901 nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info
903 info = noCafIdInfo `setUnfoldingInfo`
904 mkCompulsoryUnfolding (Lit nullAddrLit)
906 ------------------------------------------------
907 seqId :: Id -- See Note [seqId magic]
908 seqId = pcMiscPrelId seqName ty info
910 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
913 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
914 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
915 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
916 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
918 ------------------------------------------------
919 lazyId :: Id -- See Note [lazyId magic]
920 lazyId = pcMiscPrelId lazyIdName ty info
923 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
928 'seq' is special in several ways.
930 a) Its second arg can have an unboxed type
933 b) Its fixity is set in LoadIface.ghcPrimIface
935 c) It has quite a bit of desugaring magic.
936 See DsUtils.lhs Note [Desugaring seq (1)] and (2) and (3)
938 d) There is some special rule handing: Note [RULES for seq]
942 Roman found situations where he had
944 where he knew that f (which was strict in n) would terminate if n did.
945 Notice that the result of (f n) is discarded. So it makes sense to
949 Rather than attempt some general analysis to support this, I've added
950 enough support that you can do this using a rewrite rule:
952 RULE "f/seq" forall n. seq (f n) e = seq n e
954 You write that rule. When GHC sees a case expression that discards
955 its result, it mentally transforms it to a call to 'seq' and looks for
956 a RULE. (This is done in Simplify.rebuildCase.) As usual, the
957 correctness of the rule is up to you.
959 To make this work, we need to be careful that the magical desugaring
960 done in Note [seqId magic] item (c) is *not* done on the LHS of a rule.
961 Or rather, we arrange to un-do it, in DsBinds.decomposeRuleLhs.
966 lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
968 Used to lazify pseq: pseq a b = a `seq` lazy b
970 Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
971 not from GHC.Base.hi. This is important, because the strictness
972 analyser will spot it as strict!
974 Also no unfolding in lazyId: it gets "inlined" by a HACK in CorePrep.
975 It's very important to do this inlining *after* unfoldings are exposed
976 in the interface file. Otherwise, the unfolding for (say) pseq in the
977 interface file will not mention 'lazy', so if we inline 'pseq' we'll totally
978 miss the very thing that 'lazy' was there for in the first place.
979 See Trac #3259 for a real world example.
981 lazyId is defined in GHC.Base, so we don't *have* to inline it. If it
982 appears un-applied, we'll end up just calling it.
984 -------------------------------------------------------------
985 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
986 nasty as-is, change it back to a literal (@Literal@).
988 voidArgId is a Local Id used simply as an argument in functions
989 where we just want an arg to avoid having a thunk of unlifted type.
991 x = \ void :: State# RealWorld -> (# p, q #)
993 This comes up in strictness analysis
996 realWorldPrimId -- :: State# RealWorld
997 = pcMiscPrelId realWorldName realWorldStatePrimTy
998 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
999 -- The evaldUnfolding makes it look that realWorld# is evaluated
1000 -- which in turn makes Simplify.interestingArg return True,
1001 -- which in turn makes INLINE things applied to realWorld# likely
1005 voidArgId -- :: State# RealWorld
1006 = mkSysLocal (fsLit "void") voidArgIdKey realWorldStatePrimTy
1010 %************************************************************************
1012 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1014 %************************************************************************
1016 GHC randomly injects these into the code.
1018 @patError@ is just a version of @error@ for pattern-matching
1019 failures. It knows various ``codes'' which expand to longer
1020 strings---this saves space!
1022 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
1023 well shouldn't be yanked on, but if one is, then you will get a
1024 friendly message from @absentErr@ (rather than a totally random
1027 @parError@ is a special version of @error@ which the compiler does
1028 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
1029 templates, but we don't ever expect to generate code for it.
1033 :: Id -- Should be of type (forall a. Addr# -> a)
1034 -- where Addr# points to a UTF8 encoded string
1035 -> Type -- The type to instantiate 'a'
1036 -> String -- The string to print
1039 mkRuntimeErrorApp err_id res_ty err_msg
1040 = mkApps (Var err_id) [Type res_ty, err_string]
1042 err_string = Lit (mkMachString err_msg)
1044 mkImpossibleExpr :: Type -> CoreExpr
1045 mkImpossibleExpr res_ty
1046 = mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty "Impossible case alternative"
1048 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
1049 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
1050 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
1051 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
1052 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
1053 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
1054 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1056 -- The runtime error Ids take a UTF8-encoded string as argument
1058 mkRuntimeErrorId :: Name -> Id
1059 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1061 runtimeErrorTy :: Type
1062 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1066 eRROR_ID = pc_bottoming_Id errorName errorTy
1069 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1070 -- Notice the openAlphaTyVar. It says that "error" can be applied
1071 -- to unboxed as well as boxed types. This is OK because it never
1072 -- returns, so the return type is irrelevant.
1076 %************************************************************************
1078 \subsection{Utilities}
1080 %************************************************************************
1083 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1084 pcMiscPrelId name ty info
1085 = mkVanillaGlobalWithInfo name ty info
1086 -- We lie and say the thing is imported; otherwise, we get into
1087 -- a mess with dependency analysis; e.g., core2stg may heave in
1088 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1089 -- being compiled, then it's just a matter of luck if the definition
1090 -- will be in "the right place" to be in scope.
1092 pc_bottoming_Id :: Name -> Type -> Id
1093 -- Function of arity 1, which diverges after being given one argument
1094 pc_bottoming_Id name ty
1095 = pcMiscPrelId name ty bottoming_info
1097 bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1099 -- Make arity and strictness agree
1101 -- Do *not* mark them as NoCafRefs, because they can indeed have
1102 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1103 -- which has some CAFs
1104 -- In due course we may arrange that these error-y things are
1105 -- regarded by the GC as permanently live, in which case we
1106 -- can give them NoCaf info. As it is, any function that calls
1107 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1110 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1111 -- These "bottom" out, no matter what their arguments