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, substTy )
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, mkCoerce )
61 import CoreUnfold ( mkTopUnfolding, mkCompulsoryUnfolding )
62 import Literal ( nullAddrLit, mkStringLit )
63 import TyCon ( TyCon, isNewTyCon, tyConDataCons, FieldLabel,
64 tyConStupidTheta, isProductTyCon, isDataTyCon,
65 isRecursiveTyCon, tyConFamily_maybe, newTyConCo )
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,
74 dataConUnivTyVars, dataConInstTys,
75 dataConFieldLabels, dataConRepArity, dataConResTys,
76 dataConRepArgTys, dataConRepType, dataConFullSig,
77 dataConStrictMarks, dataConExStricts,
78 splitProductType, isVanillaDataCon, dataConFieldType,
81 import Id ( idType, mkGlobalId, mkVanillaGlobal, mkSysLocal,
82 mkTemplateLocals, mkTemplateLocalsNum, mkExportedLocalId,
83 mkTemplateLocal, idName
85 import IdInfo ( IdInfo, noCafIdInfo, setUnfoldingInfo,
86 setArityInfo, setSpecInfo, setCafInfo,
87 setAllStrictnessInfo, vanillaIdInfo,
88 GlobalIdDetails(..), CafInfo(..)
90 import NewDemand ( mkStrictSig, DmdResult(..),
91 mkTopDmdType, topDmd, evalDmd, lazyDmd, retCPR,
92 Demand(..), Demands(..) )
93 import DmdAnal ( dmdAnalTopRhs )
95 import Unique ( mkBuiltinUnique, mkPrimOpIdUnique )
96 import Maybe ( fromJust )
99 import Util ( dropList, isSingleton )
102 import ListSetOps ( assoc, minusList )
105 %************************************************************************
107 \subsection{Wired in Ids}
109 %************************************************************************
113 = [ -- These error-y things are wired in because we don't yet have
114 -- a way to express in an interface file that the result type variable
115 -- is 'open'; that is can be unified with an unboxed type
117 -- [The interface file format now carry such information, but there's
118 -- no way yet of expressing at the definition site for these
119 -- error-reporting functions that they have an 'open'
120 -- result type. -- sof 1/99]
122 eRROR_ID, -- This one isn't used anywhere else in the compiler
123 -- But we still need it in wiredInIds so that when GHC
124 -- compiles a program that mentions 'error' we don't
125 -- import its type from the interface file; we just get
126 -- the Id defined here. Which has an 'open-tyvar' type.
129 iRREFUT_PAT_ERROR_ID,
130 nON_EXHAUSTIVE_GUARDS_ERROR_ID,
131 nO_METHOD_BINDING_ERROR_ID,
138 -- These Ids are exported from GHC.Prim
140 = [ -- These can't be defined in Haskell, but they have
141 -- perfectly reasonable unfoldings in Core
149 %************************************************************************
151 \subsection{Data constructors}
153 %************************************************************************
155 The wrapper for a constructor is an ordinary top-level binding that evaluates
156 any strict args, unboxes any args that are going to be flattened, and calls
159 We're going to build a constructor that looks like:
161 data (Data a, C b) => T a b = T1 !a !Int b
164 \d1::Data a, d2::C b ->
165 \p q r -> case p of { p ->
167 Con T1 [a,b] [p,q,r]}}
171 * d2 is thrown away --- a context in a data decl is used to make sure
172 one *could* construct dictionaries at the site the constructor
173 is used, but the dictionary isn't actually used.
175 * We have to check that we can construct Data dictionaries for
176 the types a and Int. Once we've done that we can throw d1 away too.
178 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
179 all that matters is that the arguments are evaluated. "seq" is
180 very careful to preserve evaluation order, which we don't need
183 You might think that we could simply give constructors some strictness
184 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
185 But we don't do that because in the case of primops and functions strictness
186 is a *property* not a *requirement*. In the case of constructors we need to
187 do something active to evaluate the argument.
189 Making an explicit case expression allows the simplifier to eliminate
190 it in the (common) case where the constructor arg is already evaluated.
194 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
195 mkDataConIds wrap_name wkr_name data_con
197 = DCIds Nothing nt_work_id -- Newtype, only has a worker
199 | any isMarkedStrict all_strict_marks -- Algebraic, needs wrapper
200 || not (null eq_spec)
202 = DCIds (Just alg_wrap_id) wrk_id
204 | otherwise -- Algebraic, no wrapper
205 = DCIds Nothing wrk_id
207 (univ_tvs, ex_tvs, eq_spec,
208 theta, orig_arg_tys) = dataConFullSig data_con
209 tycon = dataConTyCon data_con
210 (isInst, instTys, familyTyCon) =
211 case dataConInstTys data_con of
212 Nothing -> (False, [] , familyTyCon)
213 Just instTys -> (True , instTys, familyTyCon)
215 familyTyCon = fromJust $ tyConFamily_maybe tycon
216 -- this is defined whenever `isInst'
218 ----------- Wrapper --------------
219 -- We used to include the stupid theta in the wrapper's args
220 -- but now we don't. Instead the type checker just injects these
221 -- extra constraints where necessary.
222 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
223 subst = mkTopTvSubst eq_spec
224 dict_tys = mkPredTys theta
225 result_ty_args = map (substTyVar subst) univ_tvs
226 familyArgs = map (substTy subst) instTys
227 result_ty = if isInst
228 then mkTyConApp familyTyCon familyArgs -- instance con
229 else mkTyConApp tycon result_ty_args -- ordinary con
230 wrap_ty = mkForAllTys wrap_tvs $ mkFunTys dict_tys $
231 mkFunTys orig_arg_tys $ result_ty
232 -- NB: watch out here if you allow user-written equality
233 -- constraints in data constructor signatures
235 ----------- Worker (algebraic data types only) --------------
236 -- The *worker* for the data constructor is the function that
237 -- takes the representation arguments and builds the constructor.
238 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
239 (dataConRepType data_con) wkr_info
241 wkr_arity = dataConRepArity data_con
242 wkr_info = noCafIdInfo
243 `setArityInfo` wkr_arity
244 `setAllStrictnessInfo` Just wkr_sig
245 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
248 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
249 -- Notice that we do *not* say the worker is strict
250 -- even if the data constructor is declared strict
251 -- e.g. data T = MkT !(Int,Int)
252 -- Why? Because the *wrapper* is strict (and its unfolding has case
253 -- expresssions that do the evals) but the *worker* itself is not.
254 -- If we pretend it is strict then when we see
255 -- case x of y -> $wMkT y
256 -- the simplifier thinks that y is "sure to be evaluated" (because
257 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
259 -- When the simplifer sees a pattern
260 -- case e of MkT x -> ...
261 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
262 -- but that's fine... dataConRepStrictness comes from the data con
263 -- not from the worker Id.
265 cpr_info | isProductTyCon tycon &&
268 wkr_arity <= mAX_CPR_SIZE = retCPR
270 -- RetCPR is only true for products that are real data types;
271 -- that is, not unboxed tuples or [non-recursive] newtypes
273 ----------- Workers for newtypes --------------
274 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
275 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
276 `setArityInfo` 1 -- Arity 1
277 `setUnfoldingInfo` newtype_unf
278 newtype_unf = ASSERT( isVanillaDataCon data_con &&
279 isSingleton orig_arg_tys )
280 -- No existentials on a newtype, but it can have a context
281 -- e.g. newtype Eq a => T a = MkT (...)
282 mkCompulsoryUnfolding $
283 mkLams wrap_tvs $ Lam id_arg1 $
284 wrapNewTypeBody tycon result_ty_args
287 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
289 ----------- Wrappers for algebraic data types --------------
290 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
291 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
292 `setArityInfo` alg_arity
293 -- It's important to specify the arity, so that partial
294 -- applications are treated as values
295 `setUnfoldingInfo` alg_unf
296 `setAllStrictnessInfo` Just wrap_sig
298 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
299 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
300 arg_dmds = map mk_dmd all_strict_marks
301 mk_dmd str | isMarkedStrict str = evalDmd
302 | otherwise = lazyDmd
303 -- The Cpr info can be important inside INLINE rhss, where the
304 -- wrapper constructor isn't inlined.
305 -- And the argument strictness can be important too; we
306 -- may not inline a contructor when it is partially applied.
308 -- data W = C !Int !Int !Int
309 -- ...(let w = C x in ...(w p q)...)...
310 -- we want to see that w is strict in its two arguments
312 alg_unf = mkTopUnfolding $ Note InlineMe $
314 mkLams dict_args $ mkLams id_args $
315 foldr mk_case con_app
316 (zip (dict_args ++ id_args) all_strict_marks)
319 con_app _ rep_ids = Var wrk_id `mkTyApps` result_ty_args
321 `mkTyApps` map snd eq_spec
322 `mkVarApps` reverse rep_ids
324 (dict_args,i2) = mkLocals 1 dict_tys
325 (id_args,i3) = mkLocals i2 orig_arg_tys
329 :: (Id, StrictnessMark) -- Arg, strictness
330 -> (Int -> [Id] -> CoreExpr) -- Body
331 -> Int -- Next rep arg id
332 -> [Id] -- Rep args so far, reversed
334 mk_case (arg,strict) body i rep_args
336 NotMarkedStrict -> body i (arg:rep_args)
338 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
340 Case (Var arg) arg result_ty [(DEFAULT,[], body i (arg:rep_args))]
343 -> unboxProduct i (Var arg) (idType arg) the_body
345 the_body i con_args = body i (reverse con_args ++ rep_args)
347 mAX_CPR_SIZE :: Arity
349 -- We do not treat very big tuples as CPR-ish:
350 -- a) for a start we get into trouble because there aren't
351 -- "enough" unboxed tuple types (a tiresome restriction,
353 -- b) more importantly, big unboxed tuples get returned mainly
354 -- on the stack, and are often then allocated in the heap
355 -- by the caller. So doing CPR for them may in fact make
358 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
364 %************************************************************************
366 \subsection{Record selectors}
368 %************************************************************************
370 We're going to build a record selector unfolding that looks like this:
372 data T a b c = T1 { ..., op :: a, ...}
373 | T2 { ..., op :: a, ...}
376 sel = /\ a b c -> \ d -> case d of
381 Similarly for newtypes
383 newtype N a = MkN { unN :: a->a }
386 unN n = coerce (a->a) n
388 We need to take a little care if the field has a polymorphic type:
390 data R = R { f :: forall a. a->a }
394 f :: forall a. R -> a -> a
395 f = /\ a \ r = case r of
398 (not f :: R -> forall a. a->a, which gives the type inference mechanism
399 problems at call sites)
401 Similarly for (recursive) newtypes
403 newtype N = MkN { unN :: forall a. a->a }
405 unN :: forall b. N -> b -> b
406 unN = /\b -> \n:N -> (coerce (forall a. a->a) n)
409 Note [Naughty record selectors]
410 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
411 A "naughty" field is one for which we can't define a record
412 selector, because an existential type variable would escape. For example:
413 data T = forall a. MkT { x,y::a }
414 We obviously can't define
416 Nevertheless we *do* put a RecordSelId into the type environment
417 so that if the user tries to use 'x' as a selector we can bleat
418 helpfully, rather than saying unhelpfully that 'x' is not in scope.
419 Hence the sel_naughty flag, to identify record selectors that don't really exist.
421 In general, a field is naughty if its type mentions a type variable that
422 isn't in the result type of the constructor.
424 Note [GADT record selectors]
425 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
426 For GADTs, we require that all constructors with a common field 'f' have the same
427 result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
430 T1 { f :: a } :: T [a]
431 T2 { f :: a, y :: b } :: T [a]
432 and now the selector takes that type as its argument:
433 f :: forall a. T [a] -> a
437 Note the forall'd tyvars of the selector are just the free tyvars
438 of the result type; there may be other tyvars in the constructor's
439 type (e.g. 'b' in T2).
443 -- Steps for handling "naughty" vs "non-naughty" selectors:
444 -- 1. Determine naughtiness by comparing field type vs result type
445 -- 2. Install naughty ones with selector_ty of type _|_ and fill in mzero for info
446 -- 3. If it's not naughty, do the normal plan.
448 mkRecordSelId :: TyCon -> FieldLabel -> Id
449 mkRecordSelId tycon field_label
450 -- Assumes that all fields with the same field label have the same type
451 | is_naughty = naughty_id
454 is_naughty = not (tyVarsOfType field_ty `subVarSet` res_tv_set)
455 sel_id_details = RecordSelId tycon field_label is_naughty
457 -- Escapist case here for naughty construcotrs
458 -- We give it no IdInfo, and a type of forall a.a (never looked at)
459 naughty_id = mkGlobalId sel_id_details field_label forall_a_a noCafIdInfo
460 forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
462 -- Normal case starts here
463 sel_id = mkGlobalId sel_id_details field_label selector_ty info
464 data_cons = tyConDataCons tycon
465 data_cons_w_field = filter has_field data_cons -- Can't be empty!
466 has_field con = field_label `elem` dataConFieldLabels con
468 con1 = head data_cons_w_field
469 res_tys = dataConResTys con1
470 res_tv_set = tyVarsOfTypes res_tys
471 res_tvs = varSetElems res_tv_set
472 data_ty = mkTyConApp tycon res_tys
473 field_ty = dataConFieldType con1 field_label
475 -- *Very* tiresomely, the selectors are (unnecessarily!) overloaded over
476 -- just the dictionaries in the types of the constructors that contain
477 -- the relevant field. [The Report says that pattern matching on a
478 -- constructor gives the same constraints as applying it.] Urgh.
480 -- However, not all data cons have all constraints (because of
481 -- BuildTyCl.mkDataConStupidTheta). So we need to find all the data cons
482 -- involved in the pattern match and take the union of their constraints.
483 stupid_dict_tys = mkPredTys (dataConsStupidTheta data_cons_w_field)
484 n_stupid_dicts = length stupid_dict_tys
486 (field_tyvars,pre_field_theta,field_tau) = tcSplitSigmaTy field_ty
488 field_theta = filter (not . isEqPred) pre_field_theta
489 field_dict_tys = mkPredTys field_theta
490 n_field_dict_tys = length field_dict_tys
491 -- If the field has a universally quantified type we have to
492 -- be a bit careful. Suppose we have
493 -- data R = R { op :: forall a. Foo a => a -> a }
494 -- Then we can't give op the type
495 -- op :: R -> forall a. Foo a => a -> a
496 -- because the typechecker doesn't understand foralls to the
497 -- right of an arrow. The "right" type to give it is
498 -- op :: forall a. Foo a => R -> a -> a
499 -- But then we must generate the right unfolding too:
500 -- op = /\a -> \dfoo -> \ r ->
503 -- Note that this is exactly the type we'd infer from a user defn
507 selector_ty = mkForAllTys res_tvs $ mkForAllTys field_tyvars $
508 mkFunTys stupid_dict_tys $ mkFunTys field_dict_tys $
509 mkFunTy data_ty field_tau
511 arity = 1 + n_stupid_dicts + n_field_dict_tys
513 (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
514 -- Use the demand analyser to work out strictness.
515 -- With all this unpackery it's not easy!
518 `setCafInfo` caf_info
520 `setUnfoldingInfo` mkTopUnfolding rhs_w_str
521 `setAllStrictnessInfo` Just strict_sig
523 -- Allocate Ids. We do it a funny way round because field_dict_tys is
524 -- almost always empty. Also note that we use max_dict_tys
525 -- rather than n_dict_tys, because the latter gives an infinite loop:
526 -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
527 -- on arity, which depends on n_dict tys. Sigh! Mega sigh!
528 stupid_dict_ids = mkTemplateLocalsNum 1 stupid_dict_tys
529 max_stupid_dicts = length (tyConStupidTheta tycon)
530 field_dict_base = max_stupid_dicts + 1
531 field_dict_ids = mkTemplateLocalsNum field_dict_base field_dict_tys
532 dict_id_base = field_dict_base + n_field_dict_tys
533 data_id = mkTemplateLocal dict_id_base data_ty
534 arg_base = dict_id_base + 1
536 the_alts :: [CoreAlt]
537 the_alts = map mk_alt data_cons_w_field -- Already sorted by data-con
538 no_default = length data_cons == length data_cons_w_field -- No default needed
540 default_alt | no_default = []
541 | otherwise = [(DEFAULT, [], error_expr)]
543 -- The default branch may have CAF refs, because it calls recSelError etc.
544 caf_info | no_default = NoCafRefs
545 | otherwise = MayHaveCafRefs
547 sel_rhs = mkLams res_tvs $ mkLams field_tyvars $
548 mkLams stupid_dict_ids $ mkLams field_dict_ids $
549 Lam data_id $ mk_result sel_body
551 -- NB: A newtype always has a vanilla DataCon; no existentials etc
552 -- res_tys will simply be the dataConUnivTyVars
553 sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon res_tys (Var data_id)
554 | otherwise = Case (Var data_id) data_id field_ty (default_alt ++ the_alts)
556 mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
557 -- We pull the field lambdas to the top, so we need to
558 -- apply them in the body. For example:
559 -- data T = MkT { foo :: forall a. a->a }
561 -- foo :: forall a. T -> a -> a
562 -- foo = /\a. \t:T. case t of { MkT f -> f a }
565 = ASSERT2( res_ty `tcEqType` field_ty, ppr data_con $$ ppr res_ty $$ ppr field_ty )
566 mkReboxingAlt rebox_uniqs data_con (ex_tvs ++ co_tvs ++ arg_vs) rhs
568 -- get pattern binders with types appropriately instantiated
569 arg_uniqs = map mkBuiltinUnique [arg_base..]
570 (ex_tvs, co_tvs, arg_vs) = dataConOrigInstPat arg_uniqs data_con res_tys
572 rebox_base = arg_base + length ex_tvs + length co_tvs + length arg_vs
573 rebox_uniqs = map mkBuiltinUnique [rebox_base..]
575 -- data T :: *->* where T1 { fld :: Maybe b } -> T [b]
576 -- Hence T1 :: forall a b. (a=[b]) => b -> T a
577 -- fld :: forall b. T [b] -> Maybe b
578 -- fld = /\b.\(t:T[b]). case t of
579 -- T1 b' (c : [b]=[b']) (x:Maybe b')
580 -- -> x `cast` Maybe (sym (right c))
582 Succeeded refinement = gadtRefine emptyRefinement ex_tvs co_tvs
583 (co_fn, res_ty) = refineType refinement (idType the_arg_id)
584 -- Generate the refinement for b'=b,
585 -- and apply to (Maybe b'), to get (Maybe b)
588 ExprCoFn co -> Cast (Var the_arg_id) co
589 id_co -> ASSERT(isIdCoercion id_co) Var the_arg_id
591 field_vs = filter (not . isPredTy . idType) arg_vs
592 the_arg_id = assoc "mkRecordSelId:mk_alt" (field_lbls `zip` field_vs) field_label
593 field_lbls = dataConFieldLabels data_con
595 error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_ty full_msg
596 full_msg = showSDoc (sep [text "No match in record selector", ppr sel_id])
598 -- unbox a product type...
599 -- we will recurse into newtypes, casting along the way, and unbox at the
600 -- first product data constructor we find. e.g.
602 -- data PairInt = PairInt Int Int
603 -- newtype S = MkS PairInt
606 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
607 -- ids, we get (modulo int passing)
609 -- case (e `cast` CoT) `cast` CoS of
610 -- PairInt a b -> body [a,b]
612 -- The Ints passed around are just for creating fresh locals
613 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
614 unboxProduct i arg arg_ty body
617 result = mkUnpackCase the_id arg con_args boxing_con rhs
618 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
619 ([the_id], i') = mkLocals i [arg_ty]
620 (con_args, i'') = mkLocals i' tys
621 rhs = body i'' con_args
623 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
624 -- (mkUnpackCase x e args Con body)
626 -- case (e `cast` ...) of bndr { Con args -> body }
628 -- the type of the bndr passed in is irrelevent
629 mkUnpackCase bndr arg unpk_args boxing_con body
630 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
632 (cast_arg, bndr_ty) = go (idType bndr) arg
634 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
635 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
636 = go (newTyConInstRhs tycon tycon_args)
637 (unwrapNewTypeBody tycon tycon_args arg)
638 | otherwise = (arg, ty)
641 reboxProduct :: [Unique] -- uniques to create new local binders
642 -> Type -- type of product to box
643 -> ([Unique], -- remaining uniques
644 CoreExpr, -- boxed product
645 [Id]) -- Ids being boxed into product
648 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
650 us' = dropList con_arg_tys us
652 arg_ids = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
654 bind_rhs = mkProductBox arg_ids ty
657 (us', bind_rhs, arg_ids)
659 mkProductBox :: [Id] -> Type -> CoreExpr
660 mkProductBox arg_ids ty
663 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
666 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
667 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
668 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
670 wrap expr = wrapNewTypeBody tycon tycon_args expr
673 -- (mkReboxingAlt us con xs rhs) basically constructs the case
674 -- alternative (con, xs, rhs)
675 -- but it does the reboxing necessary to construct the *source*
676 -- arguments, xs, from the representation arguments ys.
678 -- data T = MkT !(Int,Int) Bool
680 -- mkReboxingAlt MkT [x,b] r
681 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
683 -- mkDataAlt should really be in DataCon, but it can't because
684 -- it manipulates CoreSyn.
687 :: [Unique] -- Uniques for the new Ids
689 -> [Var] -- Source-level args, including existential dicts
693 mkReboxingAlt us con args rhs
694 | not (any isMarkedUnboxed stricts)
695 = (DataAlt con, args, rhs)
699 (binds, args') = go args stricts us
701 (DataAlt con, args', mkLets binds rhs)
704 stricts = dataConExStricts con ++ dataConStrictMarks con
706 go [] _stricts _us = ([], [])
708 -- Type variable case
709 go (arg:args) stricts us
711 = let (binds, args') = go args stricts us
712 in (binds, arg:args')
714 -- Term variable case
715 go (arg:args) (str:stricts) us
716 | isMarkedUnboxed str
718 let (binds, unpacked_args') = go args stricts us'
719 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
721 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
723 = let (binds, args') = go args stricts us
724 in (binds, arg:args')
728 %************************************************************************
730 \subsection{Dictionary selectors}
732 %************************************************************************
734 Selecting a field for a dictionary. If there is just one field, then
735 there's nothing to do.
737 Dictionary selectors may get nested forall-types. Thus:
740 op :: forall b. Ord b => a -> b -> b
742 Then the top-level type for op is
744 op :: forall a. Foo a =>
748 This is unlike ordinary record selectors, which have all the for-alls
749 at the outside. When dealing with classes it's very convenient to
750 recover the original type signature from the class op selector.
753 mkDictSelId :: Name -> Class -> Id
754 mkDictSelId name clas
755 = mkGlobalId (ClassOpId clas) name sel_ty info
757 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
758 -- We can't just say (exprType rhs), because that would give a type
760 -- for a single-op class (after all, the selector is the identity)
761 -- But it's type must expose the representation of the dictionary
762 -- to gat (say) C a -> (a -> a)
766 `setUnfoldingInfo` mkTopUnfolding rhs
767 `setAllStrictnessInfo` Just strict_sig
769 -- We no longer use 'must-inline' on record selectors. They'll
770 -- inline like crazy if they scrutinise a constructor
772 -- The strictness signature is of the form U(AAAVAAAA) -> T
773 -- where the V depends on which item we are selecting
774 -- It's worth giving one, so that absence info etc is generated
775 -- even if the selector isn't inlined
776 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
777 arg_dmd | isNewTyCon tycon = evalDmd
778 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
781 tycon = classTyCon clas
782 [data_con] = tyConDataCons tycon
783 tyvars = dataConUnivTyVars data_con
784 arg_tys = ASSERT( isVanillaDataCon data_con ) dataConRepArgTys data_con
785 the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
787 pred = mkClassPred clas (mkTyVarTys tyvars)
788 (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
790 rhs = mkLams tyvars (Lam dict_id rhs_body)
791 rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
792 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
793 [(DataAlt data_con, arg_ids, Var the_arg_id)]
795 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
796 -- The wrapper for the data constructor for a newtype looks like this:
797 -- newtype T a = MkT (a,Int)
798 -- MkT :: forall a. (a,Int) -> T a
799 -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
800 -- where CoT is the coercion TyCon assoicated with the newtype
802 -- The call (wrapNewTypeBody T [a] e) returns the
803 -- body of the wrapper, namely
804 -- e `cast` (CoT [a])
806 -- If a coercion constructor is prodivided in the newtype, then we use
807 -- it, otherwise the wrap/unwrap are both no-ops
809 wrapNewTypeBody tycon args result_expr
810 | Just co_con <- newTyConCo tycon
811 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
815 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
816 unwrapNewTypeBody tycon args result_expr
817 | Just co_con <- newTyConCo tycon
818 = mkCoerce (mkTyConApp co_con args) result_expr
826 %************************************************************************
828 \subsection{Primitive operations
830 %************************************************************************
833 mkPrimOpId :: PrimOp -> Id
837 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
838 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
839 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
840 (mkPrimOpIdUnique (primOpTag prim_op))
841 Nothing (AnId id) UserSyntax
842 id = mkGlobalId (PrimOpId prim_op) name ty info
845 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
847 `setAllStrictnessInfo` Just strict_sig
849 -- For each ccall we manufacture a separate CCallOpId, giving it
850 -- a fresh unique, a type that is correct for this particular ccall,
851 -- and a CCall structure that gives the correct details about calling
854 -- The *name* of this Id is a local name whose OccName gives the full
855 -- details of the ccall, type and all. This means that the interface
856 -- file reader can reconstruct a suitable Id
858 mkFCallId :: Unique -> ForeignCall -> Type -> Id
859 mkFCallId uniq fcall ty
860 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
861 -- A CCallOpId should have no free type variables;
862 -- when doing substitutions won't substitute over it
863 mkGlobalId (FCallId fcall) name ty info
865 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
866 -- The "occurrence name" of a ccall is the full info about the
867 -- ccall; it is encoded, but may have embedded spaces etc!
869 name = mkFCallName uniq occ_str
873 `setAllStrictnessInfo` Just strict_sig
875 (_, tau) = tcSplitForAllTys ty
876 (arg_tys, _) = tcSplitFunTys tau
877 arity = length arg_tys
878 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
882 %************************************************************************
884 \subsection{DictFuns and default methods}
886 %************************************************************************
888 Important notes about dict funs and default methods
889 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
890 Dict funs and default methods are *not* ImplicitIds. Their definition
891 involves user-written code, so we can't figure out their strictness etc
892 based on fixed info, as we can for constructors and record selectors (say).
894 We build them as LocalIds, but with External Names. This ensures that
895 they are taken to account by free-variable finding and dependency
896 analysis (e.g. CoreFVs.exprFreeVars).
898 Why shouldn't they be bound as GlobalIds? Because, in particular, if
899 they are globals, the specialiser floats dict uses above their defns,
900 which prevents good simplifications happening. Also the strictness
901 analyser treats a occurrence of a GlobalId as imported and assumes it
902 contains strictness in its IdInfo, which isn't true if the thing is
903 bound in the same module as the occurrence.
905 It's OK for dfuns to be LocalIds, because we form the instance-env to
906 pass on to the next module (md_insts) in CoreTidy, afer tidying
907 and globalising the top-level Ids.
909 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
910 that they aren't discarded by the occurrence analyser.
913 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
915 mkDictFunId :: Name -- Name to use for the dict fun;
922 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
923 = mkExportedLocalId dfun_name dfun_ty
925 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
927 {- 1 dec 99: disable the Mark Jones optimisation for the sake
928 of compatibility with Hugs.
929 See `types/InstEnv' for a discussion related to this.
931 (class_tyvars, sc_theta, _, _) = classBigSig clas
932 not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
933 sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
934 dfun_theta = case inst_decl_theta of
935 [] -> [] -- If inst_decl_theta is empty, then we don't
936 -- want to have any dict arguments, so that we can
937 -- expose the constant methods.
939 other -> nub (inst_decl_theta ++ filter not_const sc_theta')
940 -- Otherwise we pass the superclass dictionaries to
941 -- the dictionary function; the Mark Jones optimisation.
943 -- NOTE the "nub". I got caught by this one:
944 -- class Monad m => MonadT t m where ...
945 -- instance Monad m => MonadT (EnvT env) m where ...
946 -- Here, the inst_decl_theta has (Monad m); but so
947 -- does the sc_theta'!
949 -- NOTE the "not_const". I got caught by this one too:
950 -- class Foo a => Baz a b where ...
951 -- instance Wob b => Baz T b where..
952 -- Now sc_theta' has Foo T
957 %************************************************************************
959 \subsection{Un-definable}
961 %************************************************************************
963 These Ids can't be defined in Haskell. They could be defined in
964 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
965 ensure that they were definitely, definitely inlined, because there is
966 no curried identifier for them. That's what mkCompulsoryUnfolding
967 does. If we had a way to get a compulsory unfolding from an interface
968 file, we could do that, but we don't right now.
970 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
971 just gets expanded into a type coercion wherever it occurs. Hence we
972 add it as a built-in Id with an unfolding here.
974 The type variables we use here are "open" type variables: this means
975 they can unify with both unlifted and lifted types. Hence we provide
976 another gun with which to shoot yourself in the foot.
979 mkWiredInIdName mod fs uniq id
980 = mkWiredInName mod (mkOccNameFS varName fs) uniq Nothing (AnId id) UserSyntax
982 unsafeCoerceName = mkWiredInIdName gHC_PRIM FSLIT("unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
983 nullAddrName = mkWiredInIdName gHC_PRIM FSLIT("nullAddr#") nullAddrIdKey nullAddrId
984 seqName = mkWiredInIdName gHC_PRIM FSLIT("seq") seqIdKey seqId
985 realWorldName = mkWiredInIdName gHC_PRIM FSLIT("realWorld#") realWorldPrimIdKey realWorldPrimId
986 lazyIdName = mkWiredInIdName gHC_BASE FSLIT("lazy") lazyIdKey lazyId
988 errorName = mkWiredInIdName gHC_ERR FSLIT("error") errorIdKey eRROR_ID
989 recSelErrorName = mkWiredInIdName gHC_ERR FSLIT("recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
990 runtimeErrorName = mkWiredInIdName gHC_ERR FSLIT("runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
991 irrefutPatErrorName = mkWiredInIdName gHC_ERR FSLIT("irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
992 recConErrorName = mkWiredInIdName gHC_ERR FSLIT("recConError") recConErrorIdKey rEC_CON_ERROR_ID
993 patErrorName = mkWiredInIdName gHC_ERR FSLIT("patError") patErrorIdKey pAT_ERROR_ID
994 noMethodBindingErrorName = mkWiredInIdName gHC_ERR FSLIT("noMethodBindingError")
995 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
996 nonExhaustiveGuardsErrorName
997 = mkWiredInIdName gHC_ERR FSLIT("nonExhaustiveGuardsError")
998 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
1002 -- unsafeCoerce# :: forall a b. a -> b
1004 = pcMiscPrelId unsafeCoerceName ty info
1006 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1009 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
1010 (mkFunTy openAlphaTy openBetaTy)
1011 [x] = mkTemplateLocals [openAlphaTy]
1012 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
1013 -- Note (Coerce openBetaTy openAlphaTy) (Var x)
1014 Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
1016 -- nullAddr# :: Addr#
1017 -- The reason is is here is because we don't provide
1018 -- a way to write this literal in Haskell.
1020 = pcMiscPrelId nullAddrName addrPrimTy info
1022 info = noCafIdInfo `setUnfoldingInfo`
1023 mkCompulsoryUnfolding (Lit nullAddrLit)
1026 = pcMiscPrelId seqName ty info
1028 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1031 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
1032 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
1033 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
1034 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
1036 -- lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
1037 -- Used to lazify pseq: pseq a b = a `seq` lazy b
1039 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1040 -- not from GHC.Base.hi. This is important, because the strictness
1041 -- analyser will spot it as strict!
1043 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapper pass
1044 -- (see WorkWrap.wwExpr)
1045 -- We could use inline phases to do this, but that would be vulnerable to changes in
1046 -- phase numbering....we must inline precisely after strictness analysis.
1048 = pcMiscPrelId lazyIdName ty info
1051 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1053 lazyIdUnfolding :: CoreExpr -- Used to expand 'lazyId' after strictness anal
1054 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1056 [x] = mkTemplateLocals [openAlphaTy]
1059 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1060 nasty as-is, change it back to a literal (@Literal@).
1062 voidArgId is a Local Id used simply as an argument in functions
1063 where we just want an arg to avoid having a thunk of unlifted type.
1065 x = \ void :: State# RealWorld -> (# p, q #)
1067 This comes up in strictness analysis
1070 realWorldPrimId -- :: State# RealWorld
1071 = pcMiscPrelId realWorldName realWorldStatePrimTy
1072 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1073 -- The evaldUnfolding makes it look that realWorld# is evaluated
1074 -- which in turn makes Simplify.interestingArg return True,
1075 -- which in turn makes INLINE things applied to realWorld# likely
1078 voidArgId -- :: State# RealWorld
1079 = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
1083 %************************************************************************
1085 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1087 %************************************************************************
1089 GHC randomly injects these into the code.
1091 @patError@ is just a version of @error@ for pattern-matching
1092 failures. It knows various ``codes'' which expand to longer
1093 strings---this saves space!
1095 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
1096 well shouldn't be yanked on, but if one is, then you will get a
1097 friendly message from @absentErr@ (rather than a totally random
1100 @parError@ is a special version of @error@ which the compiler does
1101 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
1102 templates, but we don't ever expect to generate code for it.
1106 :: Id -- Should be of type (forall a. Addr# -> a)
1107 -- where Addr# points to a UTF8 encoded string
1108 -> Type -- The type to instantiate 'a'
1109 -> String -- The string to print
1112 mkRuntimeErrorApp err_id res_ty err_msg
1113 = mkApps (Var err_id) [Type res_ty, err_string]
1115 err_string = Lit (mkStringLit err_msg)
1117 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
1118 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
1119 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
1120 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
1121 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
1122 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
1123 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1125 -- The runtime error Ids take a UTF8-encoded string as argument
1126 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1127 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1131 eRROR_ID = pc_bottoming_Id errorName errorTy
1134 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1135 -- Notice the openAlphaTyVar. It says that "error" can be applied
1136 -- to unboxed as well as boxed types. This is OK because it never
1137 -- returns, so the return type is irrelevant.
1141 %************************************************************************
1143 \subsection{Utilities}
1145 %************************************************************************
1148 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1149 pcMiscPrelId name ty info
1150 = mkVanillaGlobal name ty info
1151 -- We lie and say the thing is imported; otherwise, we get into
1152 -- a mess with dependency analysis; e.g., core2stg may heave in
1153 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1154 -- being compiled, then it's just a matter of luck if the definition
1155 -- will be in "the right place" to be in scope.
1157 pc_bottoming_Id name ty
1158 = pcMiscPrelId name ty bottoming_info
1160 bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1161 -- Do *not* mark them as NoCafRefs, because they can indeed have
1162 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1163 -- which has some CAFs
1164 -- In due course we may arrange that these error-y things are
1165 -- regarded by the GC as permanently live, in which case we
1166 -- can give them NoCaf info. As it is, any function that calls
1167 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1170 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1171 -- These "bottom" out, no matter what their arguments
1173 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
1174 openAlphaTy = mkTyVarTy openAlphaTyVar
1175 openBetaTy = mkTyVarTy openBetaTyVar