2 % (c) The AQUA Project, Glasgow University, 1998
4 \section[StdIdInfo]{Standard unfoldings}
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,
21 mkPrimOpId, mkFCallId,
23 mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
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,
29 lazyId, lazyIdUnfolding, lazyIdKey,
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,
39 #include "HsVersions.h"
42 import BasicTypes ( Arity, StrictnessMark(..), isMarkedUnboxed, isMarkedStrict )
43 import Rules ( mkSpecInfo )
44 import TysPrim ( openAlphaTyVars, alphaTyVar, alphaTy,
45 realWorldStatePrimTy, addrPrimTy
47 import TysWiredIn ( charTy, mkListTy )
48 import PrelRules ( primOpRules )
49 import Type ( TyThing(..), mkForAllTy, tyVarsOfTypes,
50 newTyConInstRhs, mkTopTvSubst, substTyVar )
51 import TcGadt ( gadtRefine, refineType, emptyRefinement )
52 import HsBinds ( ExprCoFn(..), isIdCoercion )
53 import Coercion ( mkSymCoercion, mkUnsafeCoercion, isEqPred )
54 import TcType ( Type, ThetaType, mkDictTy, mkPredTys, mkPredTy,
55 mkTyConApp, mkTyVarTys, mkClassPred, isPredTy,
56 mkFunTys, mkFunTy, mkSigmaTy, tcSplitSigmaTy, tcEqType,
57 isUnLiftedType, mkForAllTys, mkTyVarTy, tyVarsOfType,
58 tcSplitFunTys, tcSplitForAllTys, dataConsStupidTheta
60 import CoreUtils ( exprType, dataConOrigInstPat )
61 import CoreUnfold ( mkTopUnfolding, mkCompulsoryUnfolding )
62 import Literal ( nullAddrLit, mkStringLit )
63 import TyCon ( TyCon, isNewTyCon, tyConDataCons, FieldLabel,
64 tyConStupidTheta, isProductTyCon, isDataTyCon, isRecursiveTyCon,
66 import Class ( Class, classTyCon, classSelIds )
67 import Var ( Id, TyVar, Var, setIdType )
68 import VarSet ( isEmptyVarSet, subVarSet, varSetElems )
69 import Name ( mkFCallName, mkWiredInName, Name, BuiltInSyntax(..))
70 import OccName ( mkOccNameFS, varName )
71 import PrimOp ( PrimOp, primOpSig, primOpOcc, primOpTag )
72 import ForeignCall ( ForeignCall )
73 import DataCon ( DataCon, DataConIds(..), dataConTyCon, dataConUnivTyVars,
74 dataConFieldLabels, dataConRepArity, dataConResTys,
75 dataConRepArgTys, dataConRepType, dataConFullSig,
76 dataConStrictMarks, dataConExStricts,
77 splitProductType, isVanillaDataCon, dataConFieldType,
80 import Id ( idType, mkGlobalId, mkVanillaGlobal, mkSysLocal,
81 mkTemplateLocals, mkTemplateLocalsNum, mkExportedLocalId,
82 mkTemplateLocal, idName
84 import IdInfo ( IdInfo, noCafIdInfo, setUnfoldingInfo,
85 setArityInfo, setSpecInfo, setCafInfo,
86 setAllStrictnessInfo, vanillaIdInfo,
87 GlobalIdDetails(..), CafInfo(..)
89 import NewDemand ( mkStrictSig, DmdResult(..),
90 mkTopDmdType, topDmd, evalDmd, lazyDmd, retCPR,
91 Demand(..), Demands(..) )
92 import DmdAnal ( dmdAnalTopRhs )
94 import Unique ( mkBuiltinUnique, mkPrimOpIdUnique )
97 import Util ( dropList, isSingleton )
100 import ListSetOps ( assoc, minusList )
103 %************************************************************************
105 \subsection{Wired in Ids}
107 %************************************************************************
111 = [ -- These error-y things are wired in because we don't yet have
112 -- a way to express in an interface file that the result type variable
113 -- is 'open'; that is can be unified with an unboxed type
115 -- [The interface file format now carry such information, but there's
116 -- no way yet of expressing at the definition site for these
117 -- error-reporting functions that they have an 'open'
118 -- result type. -- sof 1/99]
120 eRROR_ID, -- This one isn't used anywhere else in the compiler
121 -- But we still need it in wiredInIds so that when GHC
122 -- compiles a program that mentions 'error' we don't
123 -- import its type from the interface file; we just get
124 -- the Id defined here. Which has an 'open-tyvar' type.
127 iRREFUT_PAT_ERROR_ID,
128 nON_EXHAUSTIVE_GUARDS_ERROR_ID,
129 nO_METHOD_BINDING_ERROR_ID,
136 -- These Ids are exported from GHC.Prim
138 = [ -- These can't be defined in Haskell, but they have
139 -- perfectly reasonable unfoldings in Core
147 %************************************************************************
149 \subsection{Data constructors}
151 %************************************************************************
153 The wrapper for a constructor is an ordinary top-level binding that evaluates
154 any strict args, unboxes any args that are going to be flattened, and calls
157 We're going to build a constructor that looks like:
159 data (Data a, C b) => T a b = T1 !a !Int b
162 \d1::Data a, d2::C b ->
163 \p q r -> case p of { p ->
165 Con T1 [a,b] [p,q,r]}}
169 * d2 is thrown away --- a context in a data decl is used to make sure
170 one *could* construct dictionaries at the site the constructor
171 is used, but the dictionary isn't actually used.
173 * We have to check that we can construct Data dictionaries for
174 the types a and Int. Once we've done that we can throw d1 away too.
176 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
177 all that matters is that the arguments are evaluated. "seq" is
178 very careful to preserve evaluation order, which we don't need
181 You might think that we could simply give constructors some strictness
182 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
183 But we don't do that because in the case of primops and functions strictness
184 is a *property* not a *requirement*. In the case of constructors we need to
185 do something active to evaluate the argument.
187 Making an explicit case expression allows the simplifier to eliminate
188 it in the (common) case where the constructor arg is already evaluated.
192 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
193 mkDataConIds wrap_name wkr_name data_con
195 = DCIds Nothing nt_work_id -- Newtype, only has a worker
197 | any isMarkedStrict all_strict_marks -- Algebraic, needs wrapper
198 || not (null eq_spec)
199 = DCIds (Just alg_wrap_id) wrk_id
201 | otherwise -- Algebraic, no wrapper
202 = DCIds Nothing wrk_id
204 (univ_tvs, ex_tvs, eq_spec, theta, orig_arg_tys) = dataConFullSig data_con
205 tycon = dataConTyCon data_con
207 ----------- Wrapper --------------
208 -- We used to include the stupid theta in the wrapper's args
209 -- but now we don't. Instead the type checker just injects these
210 -- extra constraints where necessary.
211 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
212 subst = mkTopTvSubst eq_spec
213 dict_tys = mkPredTys theta
214 result_ty_args = map (substTyVar subst) univ_tvs
215 result_ty = mkTyConApp tycon result_ty_args
216 wrap_ty = mkForAllTys wrap_tvs $ mkFunTys dict_tys $
217 mkFunTys orig_arg_tys $ result_ty
218 -- NB: watch out here if you allow user-written equality
219 -- constraints in data constructor signatures
221 ----------- Worker (algebraic data types only) --------------
222 -- The *worker* for the data constructor is the function that
223 -- takes the representation arguments and builds the constructor.
224 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
225 (dataConRepType data_con) wkr_info
227 wkr_arity = dataConRepArity data_con
228 wkr_info = noCafIdInfo
229 `setArityInfo` wkr_arity
230 `setAllStrictnessInfo` Just wkr_sig
231 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
234 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
235 -- Notice that we do *not* say the worker is strict
236 -- even if the data constructor is declared strict
237 -- e.g. data T = MkT !(Int,Int)
238 -- Why? Because the *wrapper* is strict (and its unfolding has case
239 -- expresssions that do the evals) but the *worker* itself is not.
240 -- If we pretend it is strict then when we see
241 -- case x of y -> $wMkT y
242 -- the simplifier thinks that y is "sure to be evaluated" (because
243 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
245 -- When the simplifer sees a pattern
246 -- case e of MkT x -> ...
247 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
248 -- but that's fine... dataConRepStrictness comes from the data con
249 -- not from the worker Id.
251 cpr_info | isProductTyCon tycon &&
254 wkr_arity <= mAX_CPR_SIZE = retCPR
256 -- RetCPR is only true for products that are real data types;
257 -- that is, not unboxed tuples or [non-recursive] newtypes
259 ----------- Wrappers for newtypes --------------
260 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
261 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
262 `setArityInfo` 1 -- Arity 1
263 `setUnfoldingInfo` newtype_unf
264 newtype_unf = ASSERT( isVanillaDataCon data_con &&
265 isSingleton orig_arg_tys )
266 -- No existentials on a newtype, but it can have a context
267 -- e.g. newtype Eq a => T a = MkT (...)
268 mkCompulsoryUnfolding $
269 mkLams wrap_tvs $ Lam id_arg1 $
270 wrapNewTypeBody tycon result_ty_args
273 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
275 ----------- Wrappers for algebraic data types --------------
276 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
277 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
278 `setArityInfo` alg_arity
279 -- It's important to specify the arity, so that partial
280 -- applications are treated as values
281 `setUnfoldingInfo` alg_unf
282 `setAllStrictnessInfo` Just wrap_sig
284 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
285 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
286 arg_dmds = map mk_dmd all_strict_marks
287 mk_dmd str | isMarkedStrict str = evalDmd
288 | otherwise = lazyDmd
289 -- The Cpr info can be important inside INLINE rhss, where the
290 -- wrapper constructor isn't inlined.
291 -- And the argument strictness can be important too; we
292 -- may not inline a contructor when it is partially applied.
294 -- data W = C !Int !Int !Int
295 -- ...(let w = C x in ...(w p q)...)...
296 -- we want to see that w is strict in its two arguments
298 alg_unf = mkTopUnfolding $ Note InlineMe $
300 mkLams dict_args $ mkLams id_args $
301 foldr mk_case con_app
302 (zip (dict_args ++ id_args) all_strict_marks)
305 con_app _ rep_ids = Var wrk_id `mkTyApps` result_ty_args
307 `mkTyApps` map snd eq_spec
308 `mkVarApps` reverse rep_ids
310 (dict_args,i2) = mkLocals 1 dict_tys
311 (id_args,i3) = mkLocals i2 orig_arg_tys
315 :: (Id, StrictnessMark) -- Arg, strictness
316 -> (Int -> [Id] -> CoreExpr) -- Body
317 -> Int -- Next rep arg id
318 -> [Id] -- Rep args so far, reversed
320 mk_case (arg,strict) body i rep_args
322 NotMarkedStrict -> body i (arg:rep_args)
324 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
326 Case (Var arg) arg result_ty [(DEFAULT,[], body i (arg:rep_args))]
329 -> unboxProduct i (Var arg) (idType arg) the_body
331 the_body i con_args = body i (reverse con_args ++ rep_args)
333 mAX_CPR_SIZE :: Arity
335 -- We do not treat very big tuples as CPR-ish:
336 -- a) for a start we get into trouble because there aren't
337 -- "enough" unboxed tuple types (a tiresome restriction,
339 -- b) more importantly, big unboxed tuples get returned mainly
340 -- on the stack, and are often then allocated in the heap
341 -- by the caller. So doing CPR for them may in fact make
344 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
350 %************************************************************************
352 \subsection{Record selectors}
354 %************************************************************************
356 We're going to build a record selector unfolding that looks like this:
358 data T a b c = T1 { ..., op :: a, ...}
359 | T2 { ..., op :: a, ...}
362 sel = /\ a b c -> \ d -> case d of
367 Similarly for newtypes
369 newtype N a = MkN { unN :: a->a }
372 unN n = coerce (a->a) n
374 We need to take a little care if the field has a polymorphic type:
376 data R = R { f :: forall a. a->a }
380 f :: forall a. R -> a -> a
381 f = /\ a \ r = case r of
384 (not f :: R -> forall a. a->a, which gives the type inference mechanism
385 problems at call sites)
387 Similarly for (recursive) newtypes
389 newtype N = MkN { unN :: forall a. a->a }
391 unN :: forall b. N -> b -> b
392 unN = /\b -> \n:N -> (coerce (forall a. a->a) n)
395 Note [Naughty record selectors]
396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
397 A "naughty" field is one for which we can't define a record
398 selector, because an existential type variable would escape. For example:
399 data T = forall a. MkT { x,y::a }
400 We obviously can't define
402 Nevertheless we *do* put a RecordSelId into the type environment
403 so that if the user tries to use 'x' as a selector we can bleat
404 helpfully, rather than saying unhelpfully that 'x' is not in scope.
405 Hence the sel_naughty flag, to identify record selectors that don't really exist.
407 In general, a field is naughty if its type mentions a type variable that
408 isn't in the result type of the constructor.
410 Note [GADT record selectors]
411 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
412 For GADTs, we require that all constructors with a common field 'f' have the same
413 result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
416 T1 { f :: a } :: T [a]
417 T2 { f :: a, y :: b } :: T [a]
418 and now the selector takes that type as its argument:
419 f :: forall a. T [a] -> a
423 Note the forall'd tyvars of the selector are just the free tyvars
424 of the result type; there may be other tyvars in the constructor's
425 type (e.g. 'b' in T2).
429 -- Steps for handling "naughty" vs "non-naughty" selectors:
430 -- 1. Determine naughtiness by comparing field type vs result type
431 -- 2. Install naughty ones with selector_ty of type _|_ and fill in mzero for info
432 -- 3. If it's not naughty, do the normal plan.
434 mkRecordSelId :: TyCon -> FieldLabel -> Id
435 mkRecordSelId tycon field_label
436 -- Assumes that all fields with the same field label have the same type
437 | is_naughty = naughty_id
440 is_naughty = not (tyVarsOfType field_ty `subVarSet` res_tv_set)
441 sel_id_details = RecordSelId tycon field_label is_naughty
443 -- Escapist case here for naughty construcotrs
444 -- We give it no IdInfo, and a type of forall a.a (never looked at)
445 naughty_id = mkGlobalId sel_id_details field_label forall_a_a noCafIdInfo
446 forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
448 -- Normal case starts here
449 sel_id = mkGlobalId sel_id_details field_label selector_ty info
450 data_cons = tyConDataCons tycon
451 data_cons_w_field = filter has_field data_cons -- Can't be empty!
452 has_field con = field_label `elem` dataConFieldLabels con
454 con1 = head data_cons_w_field
455 res_tys = dataConResTys con1
456 res_tv_set = tyVarsOfTypes res_tys
457 res_tvs = varSetElems res_tv_set
458 data_ty = mkTyConApp tycon res_tys
459 field_ty = dataConFieldType con1 field_label
461 -- *Very* tiresomely, the selectors are (unnecessarily!) overloaded over
462 -- just the dictionaries in the types of the constructors that contain
463 -- the relevant field. [The Report says that pattern matching on a
464 -- constructor gives the same constraints as applying it.] Urgh.
466 -- However, not all data cons have all constraints (because of
467 -- BuildTyCl.mkDataConStupidTheta). So we need to find all the data cons
468 -- involved in the pattern match and take the union of their constraints.
469 stupid_dict_tys = mkPredTys (dataConsStupidTheta data_cons_w_field)
470 n_stupid_dicts = length stupid_dict_tys
472 (field_tyvars,pre_field_theta,field_tau) = tcSplitSigmaTy field_ty
474 field_theta = filter (not . isEqPred) pre_field_theta
475 field_dict_tys = mkPredTys field_theta
476 n_field_dict_tys = length field_dict_tys
477 -- If the field has a universally quantified type we have to
478 -- be a bit careful. Suppose we have
479 -- data R = R { op :: forall a. Foo a => a -> a }
480 -- Then we can't give op the type
481 -- op :: R -> forall a. Foo a => a -> a
482 -- because the typechecker doesn't understand foralls to the
483 -- right of an arrow. The "right" type to give it is
484 -- op :: forall a. Foo a => R -> a -> a
485 -- But then we must generate the right unfolding too:
486 -- op = /\a -> \dfoo -> \ r ->
489 -- Note that this is exactly the type we'd infer from a user defn
493 selector_ty = mkForAllTys res_tvs $ mkForAllTys field_tyvars $
494 mkFunTys stupid_dict_tys $ mkFunTys field_dict_tys $
495 mkFunTy data_ty field_tau
497 arity = 1 + n_stupid_dicts + n_field_dict_tys
499 (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
500 -- Use the demand analyser to work out strictness.
501 -- With all this unpackery it's not easy!
504 `setCafInfo` caf_info
506 `setUnfoldingInfo` mkTopUnfolding rhs_w_str
507 `setAllStrictnessInfo` Just strict_sig
509 -- Allocate Ids. We do it a funny way round because field_dict_tys is
510 -- almost always empty. Also note that we use max_dict_tys
511 -- rather than n_dict_tys, because the latter gives an infinite loop:
512 -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
513 -- on arity, which depends on n_dict tys. Sigh! Mega sigh!
514 stupid_dict_ids = mkTemplateLocalsNum 1 stupid_dict_tys
515 max_stupid_dicts = length (tyConStupidTheta tycon)
516 field_dict_base = max_stupid_dicts + 1
517 field_dict_ids = mkTemplateLocalsNum field_dict_base field_dict_tys
518 dict_id_base = field_dict_base + n_field_dict_tys
519 data_id = mkTemplateLocal dict_id_base data_ty
520 arg_base = dict_id_base + 1
522 the_alts :: [CoreAlt]
523 the_alts = map mk_alt data_cons_w_field -- Already sorted by data-con
524 no_default = length data_cons == length data_cons_w_field -- No default needed
526 default_alt | no_default = []
527 | otherwise = [(DEFAULT, [], error_expr)]
529 -- The default branch may have CAF refs, because it calls recSelError etc.
530 caf_info | no_default = NoCafRefs
531 | otherwise = MayHaveCafRefs
533 sel_rhs = mkLams res_tvs $ mkLams field_tyvars $
534 mkLams stupid_dict_ids $ mkLams field_dict_ids $
535 Lam data_id $ mk_result sel_body
537 -- NB: A newtype always has a vanilla DataCon; no existentials etc
538 -- res_tys will simply be the dataConUnivTyVars
539 sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon res_tys (Var data_id)
540 | otherwise = Case (Var data_id) data_id field_ty (default_alt ++ the_alts)
542 mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
543 -- We pull the field lambdas to the top, so we need to
544 -- apply them in the body. For example:
545 -- data T = MkT { foo :: forall a. a->a }
547 -- foo :: forall a. T -> a -> a
548 -- foo = /\a. \t:T. case t of { MkT f -> f a }
551 = ASSERT2( res_ty `tcEqType` field_ty, ppr data_con $$ ppr res_ty $$ ppr field_ty )
552 mkReboxingAlt rebox_uniqs data_con (ex_tvs ++ co_tvs ++ arg_vs) rhs
554 -- get pattern binders with types appropriately instantiated
555 arg_uniqs = map mkBuiltinUnique [arg_base..]
556 (ex_tvs, co_tvs, arg_vs) = dataConOrigInstPat arg_uniqs data_con res_tys
558 rebox_base = arg_base + length ex_tvs + length co_tvs + length arg_vs
559 rebox_uniqs = map mkBuiltinUnique [rebox_base..]
561 -- data T :: *->* where T1 { fld :: Maybe b } -> T [b]
562 -- Hence T1 :: forall a b. (a=[b]) => b -> T a
563 -- fld :: forall b. T [b] -> Maybe b
564 -- fld = /\b.\(t:T[b]). case t of
565 -- T1 b' (c : [b]=[b']) (x:Maybe b')
566 -- -> x `cast` Maybe (sym (right c))
568 Succeeded refinement = gadtRefine emptyRefinement ex_tvs co_tvs
569 (co_fn, res_ty) = refineType refinement (idType the_arg_id)
570 -- Generate the refinement for b'=b,
571 -- and apply to (Maybe b'), to get (Maybe b)
574 ExprCoFn co -> Cast (Var the_arg_id) co
575 id_co -> ASSERT(isIdCoercion id_co) Var the_arg_id
577 field_vs = filter (not . isPredTy . idType) arg_vs
578 the_arg_id = assoc "mkRecordSelId:mk_alt" (field_lbls `zip` field_vs) field_label
579 field_lbls = dataConFieldLabels data_con
581 error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_ty full_msg
582 full_msg = showSDoc (sep [text "No match in record selector", ppr sel_id])
584 -- unbox a product type...
585 -- we will recurse into newtypes, casting along the way, and unbox at the
586 -- first product data constructor we find. e.g.
588 -- data PairInt = PairInt Int Int
589 -- newtype S = MkS PairInt
592 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
593 -- ids, we get (modulo int passing)
595 -- case (e `cast` (sym CoT)) `cast` (sym CoS) of
596 -- PairInt a b -> body [a,b]
598 -- The Ints passed around are just for creating fresh locals
599 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
600 unboxProduct i arg arg_ty body
603 result = mkUnpackCase the_id arg con_args boxing_con rhs
604 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
605 ([the_id], i') = mkLocals i [arg_ty]
606 (con_args, i'') = mkLocals i' tys
607 rhs = body i'' con_args
609 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
610 -- (mkUnpackCase x e args Con body)
612 -- case (e `cast` ...) of bndr { Con args -> body }
614 -- the type of the bndr passed in is irrelevent
615 mkUnpackCase bndr arg unpk_args boxing_con body
616 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
618 (cast_arg, bndr_ty) = go (idType bndr) arg
620 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
621 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
622 = go (newTyConInstRhs tycon tycon_args)
623 (unwrapNewTypeBody tycon tycon_args arg)
624 | otherwise = (arg, ty)
627 reboxProduct :: [Unique] -- uniques to create new local binders
628 -> Type -- type of product to box
629 -> ([Unique], -- remaining uniques
630 CoreExpr, -- boxed product
631 [Id]) -- Ids being boxed into product
634 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
636 us' = dropList con_arg_tys us
638 arg_ids = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
640 bind_rhs = mkProductBox arg_ids ty
643 (us', bind_rhs, arg_ids)
645 mkProductBox :: [Id] -> Type -> CoreExpr
646 mkProductBox arg_ids ty
649 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
652 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
653 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
654 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
656 wrap expr = wrapNewTypeBody tycon tycon_args expr
659 -- (mkReboxingAlt us con xs rhs) basically constructs the case
660 -- alternative (con, xs, rhs)
661 -- but it does the reboxing necessary to construct the *source*
662 -- arguments, xs, from the representation arguments ys.
664 -- data T = MkT !(Int,Int) Bool
666 -- mkReboxingAlt MkT [x,b] r
667 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
669 -- mkDataAlt should really be in DataCon, but it can't because
670 -- it manipulates CoreSyn.
673 :: [Unique] -- Uniques for the new Ids
675 -> [Var] -- Source-level args, including existential dicts
679 mkReboxingAlt us con args rhs
680 | not (any isMarkedUnboxed stricts)
681 = (DataAlt con, args, rhs)
685 (binds, args') = go args stricts us
687 (DataAlt con, args', mkLets binds rhs)
690 stricts = dataConExStricts con ++ dataConStrictMarks con
692 go [] _stricts _us = ([], [])
694 -- Type variable case
695 go (arg:args) stricts us
697 = let (binds, args') = go args stricts us
698 in (binds, arg:args')
700 -- Term variable case
701 go (arg:args) (str:stricts) us
702 | isMarkedUnboxed str
704 let (binds, unpacked_args') = go args stricts us'
705 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
707 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
709 = let (binds, args') = go args stricts us
710 in (binds, arg:args')
714 %************************************************************************
716 \subsection{Dictionary selectors}
718 %************************************************************************
720 Selecting a field for a dictionary. If there is just one field, then
721 there's nothing to do.
723 Dictionary selectors may get nested forall-types. Thus:
726 op :: forall b. Ord b => a -> b -> b
728 Then the top-level type for op is
730 op :: forall a. Foo a =>
734 This is unlike ordinary record selectors, which have all the for-alls
735 at the outside. When dealing with classes it's very convenient to
736 recover the original type signature from the class op selector.
739 mkDictSelId :: Name -> Class -> Id
740 mkDictSelId name clas
741 = mkGlobalId (ClassOpId clas) name sel_ty info
743 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
744 -- We can't just say (exprType rhs), because that would give a type
746 -- for a single-op class (after all, the selector is the identity)
747 -- But it's type must expose the representation of the dictionary
748 -- to gat (say) C a -> (a -> a)
752 `setUnfoldingInfo` mkTopUnfolding rhs
753 `setAllStrictnessInfo` Just strict_sig
755 -- We no longer use 'must-inline' on record selectors. They'll
756 -- inline like crazy if they scrutinise a constructor
758 -- The strictness signature is of the form U(AAAVAAAA) -> T
759 -- where the V depends on which item we are selecting
760 -- It's worth giving one, so that absence info etc is generated
761 -- even if the selector isn't inlined
762 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
763 arg_dmd | isNewTyCon tycon = evalDmd
764 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
767 tycon = classTyCon clas
768 [data_con] = tyConDataCons tycon
769 tyvars = dataConUnivTyVars data_con
770 arg_tys = ASSERT( isVanillaDataCon data_con ) dataConRepArgTys data_con
771 the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
773 pred = mkClassPred clas (mkTyVarTys tyvars)
774 (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
776 rhs = mkLams tyvars (Lam dict_id rhs_body)
777 rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
778 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
779 [(DataAlt data_con, arg_ids, Var the_arg_id)]
781 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
782 -- The wrapper for the data constructor for a newtype looks like this:
783 -- newtype T a = MkT (a,Int)
784 -- MkT :: forall a. (a,Int) -> T a
785 -- MkT = /\a. \(x:(a,Int)). x `cast` CoT a
786 -- where CoT is the coercion TyCon assoicated with the newtype
788 -- The call (wrapNewTypeBody T [a] e) returns the
789 -- body of the wrapper, namely
792 -- If a coercion constructor is prodivided in the newtype, then we use
793 -- it, otherwise the wrap/unwrap are both no-ops
795 wrapNewTypeBody tycon args result_expr
796 | Just co_con <- newTyConCo tycon
797 = Cast result_expr (mkTyConApp co_con args)
801 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
802 unwrapNewTypeBody tycon args result_expr
803 | Just co_con <- newTyConCo tycon
804 = Cast result_expr (mkSymCoercion (mkTyConApp co_con args))
812 %************************************************************************
814 \subsection{Primitive operations
816 %************************************************************************
819 mkPrimOpId :: PrimOp -> Id
823 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
824 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
825 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
826 (mkPrimOpIdUnique (primOpTag prim_op))
827 Nothing (AnId id) UserSyntax
828 id = mkGlobalId (PrimOpId prim_op) name ty info
831 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
833 `setAllStrictnessInfo` Just strict_sig
835 -- For each ccall we manufacture a separate CCallOpId, giving it
836 -- a fresh unique, a type that is correct for this particular ccall,
837 -- and a CCall structure that gives the correct details about calling
840 -- The *name* of this Id is a local name whose OccName gives the full
841 -- details of the ccall, type and all. This means that the interface
842 -- file reader can reconstruct a suitable Id
844 mkFCallId :: Unique -> ForeignCall -> Type -> Id
845 mkFCallId uniq fcall ty
846 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
847 -- A CCallOpId should have no free type variables;
848 -- when doing substitutions won't substitute over it
849 mkGlobalId (FCallId fcall) name ty info
851 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
852 -- The "occurrence name" of a ccall is the full info about the
853 -- ccall; it is encoded, but may have embedded spaces etc!
855 name = mkFCallName uniq occ_str
859 `setAllStrictnessInfo` Just strict_sig
861 (_, tau) = tcSplitForAllTys ty
862 (arg_tys, _) = tcSplitFunTys tau
863 arity = length arg_tys
864 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
868 %************************************************************************
870 \subsection{DictFuns and default methods}
872 %************************************************************************
874 Important notes about dict funs and default methods
875 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
876 Dict funs and default methods are *not* ImplicitIds. Their definition
877 involves user-written code, so we can't figure out their strictness etc
878 based on fixed info, as we can for constructors and record selectors (say).
880 We build them as LocalIds, but with External Names. This ensures that
881 they are taken to account by free-variable finding and dependency
882 analysis (e.g. CoreFVs.exprFreeVars).
884 Why shouldn't they be bound as GlobalIds? Because, in particular, if
885 they are globals, the specialiser floats dict uses above their defns,
886 which prevents good simplifications happening. Also the strictness
887 analyser treats a occurrence of a GlobalId as imported and assumes it
888 contains strictness in its IdInfo, which isn't true if the thing is
889 bound in the same module as the occurrence.
891 It's OK for dfuns to be LocalIds, because we form the instance-env to
892 pass on to the next module (md_insts) in CoreTidy, afer tidying
893 and globalising the top-level Ids.
895 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
896 that they aren't discarded by the occurrence analyser.
899 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
901 mkDictFunId :: Name -- Name to use for the dict fun;
908 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
909 = mkExportedLocalId dfun_name dfun_ty
911 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
913 {- 1 dec 99: disable the Mark Jones optimisation for the sake
914 of compatibility with Hugs.
915 See `types/InstEnv' for a discussion related to this.
917 (class_tyvars, sc_theta, _, _) = classBigSig clas
918 not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
919 sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
920 dfun_theta = case inst_decl_theta of
921 [] -> [] -- If inst_decl_theta is empty, then we don't
922 -- want to have any dict arguments, so that we can
923 -- expose the constant methods.
925 other -> nub (inst_decl_theta ++ filter not_const sc_theta')
926 -- Otherwise we pass the superclass dictionaries to
927 -- the dictionary function; the Mark Jones optimisation.
929 -- NOTE the "nub". I got caught by this one:
930 -- class Monad m => MonadT t m where ...
931 -- instance Monad m => MonadT (EnvT env) m where ...
932 -- Here, the inst_decl_theta has (Monad m); but so
933 -- does the sc_theta'!
935 -- NOTE the "not_const". I got caught by this one too:
936 -- class Foo a => Baz a b where ...
937 -- instance Wob b => Baz T b where..
938 -- Now sc_theta' has Foo T
943 %************************************************************************
945 \subsection{Un-definable}
947 %************************************************************************
949 These Ids can't be defined in Haskell. They could be defined in
950 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
951 ensure that they were definitely, definitely inlined, because there is
952 no curried identifier for them. That's what mkCompulsoryUnfolding
953 does. If we had a way to get a compulsory unfolding from an interface
954 file, we could do that, but we don't right now.
956 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
957 just gets expanded into a type coercion wherever it occurs. Hence we
958 add it as a built-in Id with an unfolding here.
960 The type variables we use here are "open" type variables: this means
961 they can unify with both unlifted and lifted types. Hence we provide
962 another gun with which to shoot yourself in the foot.
965 mkWiredInIdName mod fs uniq id
966 = mkWiredInName mod (mkOccNameFS varName fs) uniq Nothing (AnId id) UserSyntax
968 unsafeCoerceName = mkWiredInIdName gHC_PRIM FSLIT("unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
969 nullAddrName = mkWiredInIdName gHC_PRIM FSLIT("nullAddr#") nullAddrIdKey nullAddrId
970 seqName = mkWiredInIdName gHC_PRIM FSLIT("seq") seqIdKey seqId
971 realWorldName = mkWiredInIdName gHC_PRIM FSLIT("realWorld#") realWorldPrimIdKey realWorldPrimId
972 lazyIdName = mkWiredInIdName gHC_BASE FSLIT("lazy") lazyIdKey lazyId
974 errorName = mkWiredInIdName gHC_ERR FSLIT("error") errorIdKey eRROR_ID
975 recSelErrorName = mkWiredInIdName gHC_ERR FSLIT("recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
976 runtimeErrorName = mkWiredInIdName gHC_ERR FSLIT("runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
977 irrefutPatErrorName = mkWiredInIdName gHC_ERR FSLIT("irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
978 recConErrorName = mkWiredInIdName gHC_ERR FSLIT("recConError") recConErrorIdKey rEC_CON_ERROR_ID
979 patErrorName = mkWiredInIdName gHC_ERR FSLIT("patError") patErrorIdKey pAT_ERROR_ID
980 noMethodBindingErrorName = mkWiredInIdName gHC_ERR FSLIT("noMethodBindingError")
981 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
982 nonExhaustiveGuardsErrorName
983 = mkWiredInIdName gHC_ERR FSLIT("nonExhaustiveGuardsError")
984 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
988 -- unsafeCoerce# :: forall a b. a -> b
990 = pcMiscPrelId unsafeCoerceName ty info
992 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
995 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
996 (mkFunTy openAlphaTy openBetaTy)
997 [x] = mkTemplateLocals [openAlphaTy]
998 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
999 -- Note (Coerce openBetaTy openAlphaTy) (Var x)
1000 Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
1002 -- nullAddr# :: Addr#
1003 -- The reason is is here is because we don't provide
1004 -- a way to write this literal in Haskell.
1006 = pcMiscPrelId nullAddrName addrPrimTy info
1008 info = noCafIdInfo `setUnfoldingInfo`
1009 mkCompulsoryUnfolding (Lit nullAddrLit)
1012 = pcMiscPrelId seqName ty info
1014 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1017 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
1018 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
1019 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
1020 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
1022 -- lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
1023 -- Used to lazify pseq: pseq a b = a `seq` lazy b
1025 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1026 -- not from GHC.Base.hi. This is important, because the strictness
1027 -- analyser will spot it as strict!
1029 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapper pass
1030 -- (see WorkWrap.wwExpr)
1031 -- We could use inline phases to do this, but that would be vulnerable to changes in
1032 -- phase numbering....we must inline precisely after strictness analysis.
1034 = pcMiscPrelId lazyIdName ty info
1037 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1039 lazyIdUnfolding :: CoreExpr -- Used to expand 'lazyId' after strictness anal
1040 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1042 [x] = mkTemplateLocals [openAlphaTy]
1045 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1046 nasty as-is, change it back to a literal (@Literal@).
1048 voidArgId is a Local Id used simply as an argument in functions
1049 where we just want an arg to avoid having a thunk of unlifted type.
1051 x = \ void :: State# RealWorld -> (# p, q #)
1053 This comes up in strictness analysis
1056 realWorldPrimId -- :: State# RealWorld
1057 = pcMiscPrelId realWorldName realWorldStatePrimTy
1058 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1059 -- The evaldUnfolding makes it look that realWorld# is evaluated
1060 -- which in turn makes Simplify.interestingArg return True,
1061 -- which in turn makes INLINE things applied to realWorld# likely
1064 voidArgId -- :: State# RealWorld
1065 = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
1069 %************************************************************************
1071 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1073 %************************************************************************
1075 GHC randomly injects these into the code.
1077 @patError@ is just a version of @error@ for pattern-matching
1078 failures. It knows various ``codes'' which expand to longer
1079 strings---this saves space!
1081 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
1082 well shouldn't be yanked on, but if one is, then you will get a
1083 friendly message from @absentErr@ (rather than a totally random
1086 @parError@ is a special version of @error@ which the compiler does
1087 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
1088 templates, but we don't ever expect to generate code for it.
1092 :: Id -- Should be of type (forall a. Addr# -> a)
1093 -- where Addr# points to a UTF8 encoded string
1094 -> Type -- The type to instantiate 'a'
1095 -> String -- The string to print
1098 mkRuntimeErrorApp err_id res_ty err_msg
1099 = mkApps (Var err_id) [Type res_ty, err_string]
1101 err_string = Lit (mkStringLit err_msg)
1103 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
1104 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
1105 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
1106 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
1107 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
1108 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
1109 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1111 -- The runtime error Ids take a UTF8-encoded string as argument
1112 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1113 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1117 eRROR_ID = pc_bottoming_Id errorName errorTy
1120 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1121 -- Notice the openAlphaTyVar. It says that "error" can be applied
1122 -- to unboxed as well as boxed types. This is OK because it never
1123 -- returns, so the return type is irrelevant.
1127 %************************************************************************
1129 \subsection{Utilities}
1131 %************************************************************************
1134 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1135 pcMiscPrelId name ty info
1136 = mkVanillaGlobal name ty info
1137 -- We lie and say the thing is imported; otherwise, we get into
1138 -- a mess with dependency analysis; e.g., core2stg may heave in
1139 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1140 -- being compiled, then it's just a matter of luck if the definition
1141 -- will be in "the right place" to be in scope.
1143 pc_bottoming_Id name ty
1144 = pcMiscPrelId name ty bottoming_info
1146 bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1147 -- Do *not* mark them as NoCafRefs, because they can indeed have
1148 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1149 -- which has some CAFs
1150 -- In due course we may arrange that these error-y things are
1151 -- regarded by the GC as permanently live, in which case we
1152 -- can give them NoCaf info. As it is, any function that calls
1153 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1156 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1157 -- These "bottom" out, no matter what their arguments
1159 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
1160 openAlphaTy = mkTyVarTy openAlphaTyVar
1161 openBetaTy = mkTyVarTy openBetaTyVar