2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1998
6 This module contains definitions for the IdInfo for things that
7 have a standard form, namely:
11 * method and superclass selectors
12 * primitive operations
16 mkDictFunId, mkDefaultMethodId,
21 mkPrimOpId, mkFCallId, mkTickBoxOpId, mkBreakPointOpId,
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"
61 import Var ( Var, TyVar)
69 import BasicTypes hiding ( SuccessFlag(..) )
77 %************************************************************************
79 \subsection{Wired in Ids}
81 %************************************************************************
85 = [ -- These error-y things are wired in because we don't yet have
86 -- a way to express in an interface file that the result type variable
87 -- is 'open'; that is can be unified with an unboxed type
89 -- [The interface file format now carry such information, but there's
90 -- no way yet of expressing at the definition site for these
91 -- error-reporting functions that they have an 'open'
92 -- result type. -- sof 1/99]
94 eRROR_ID, -- This one isn't used anywhere else in the compiler
95 -- But we still need it in wiredInIds so that when GHC
96 -- compiles a program that mentions 'error' we don't
97 -- import its type from the interface file; we just get
98 -- the Id defined here. Which has an 'open-tyvar' type.
101 iRREFUT_PAT_ERROR_ID,
102 nON_EXHAUSTIVE_GUARDS_ERROR_ID,
103 nO_METHOD_BINDING_ERROR_ID,
110 -- These Ids are exported from GHC.Prim
112 = [ -- These can't be defined in Haskell, but they have
113 -- perfectly reasonable unfoldings in Core
121 %************************************************************************
123 \subsection{Data constructors}
125 %************************************************************************
127 The wrapper for a constructor is an ordinary top-level binding that evaluates
128 any strict args, unboxes any args that are going to be flattened, and calls
131 We're going to build a constructor that looks like:
133 data (Data a, C b) => T a b = T1 !a !Int b
136 \d1::Data a, d2::C b ->
137 \p q r -> case p of { p ->
139 Con T1 [a,b] [p,q,r]}}
143 * d2 is thrown away --- a context in a data decl is used to make sure
144 one *could* construct dictionaries at the site the constructor
145 is used, but the dictionary isn't actually used.
147 * We have to check that we can construct Data dictionaries for
148 the types a and Int. Once we've done that we can throw d1 away too.
150 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
151 all that matters is that the arguments are evaluated. "seq" is
152 very careful to preserve evaluation order, which we don't need
155 You might think that we could simply give constructors some strictness
156 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
157 But we don't do that because in the case of primops and functions strictness
158 is a *property* not a *requirement*. In the case of constructors we need to
159 do something active to evaluate the argument.
161 Making an explicit case expression allows the simplifier to eliminate
162 it in the (common) case where the constructor arg is already evaluated.
164 Note [Wrappers for data instance tycons]
165 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
166 In the case of data instances, the wrapper also applies the coercion turning
167 the representation type into the family instance type to cast the result of
168 the wrapper. For example, consider the declarations
170 data family Map k :: * -> *
171 data instance Map (a, b) v = MapPair (Map a (Pair b v))
173 The tycon to which the datacon MapPair belongs gets a unique internal
174 name of the form :R123Map, and we call it the representation tycon.
175 In contrast, Map is the family tycon (accessible via
176 tyConFamInst_maybe). A coercion allows you to move between
177 representation and family type. It is accessible from :R123Map via
178 tyConFamilyCoercion_maybe and has kind
180 Co123Map a b v :: {Map (a, b) v :=: :R123Map a b v}
182 The wrapper and worker of MapPair get the types
184 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
185 $WMapPair a b v = $wMapPair a b v `cast` sym (Co123Map a b v)
187 $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
189 This coercion is conditionally applied by wrapFamInstBody.
191 It's a bit more complicated if the data instance is a GADT as well!
193 data instance T [a] where
194 T1 :: forall b. b -> T [Maybe b]
196 Co7T a :: T [a] ~ :R7T a
200 $WT1 :: forall b. b -> T [Maybe b]
201 $WT1 a b v = $wT1 b (Maybe b) (Maybe b)
202 `cast` sym (Co7T (Maybe b))
204 $wT1 :: forall b c. (b ~ Maybe c) => b -> :R7T c
207 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
208 mkDataConIds wrap_name wkr_name data_con
209 | isNewTyCon tycon -- Newtype, only has a worker
210 , not (isFamInstTyCon tycon) -- unless it's a family instancex
211 = DCIds Nothing nt_work_id
213 | any isMarkedStrict all_strict_marks -- Algebraic, needs wrapper
214 || not (null eq_spec) -- NB: LoadIface.ifaceDeclSubBndrs
215 || isFamInstTyCon tycon -- depends on this test
216 = DCIds (Just alg_wrap_id) wrk_id
218 | otherwise -- Algebraic, no wrapper
219 = DCIds Nothing wrk_id
221 (univ_tvs, ex_tvs, eq_spec,
222 theta, orig_arg_tys, res_ty) = dataConFullSig data_con
223 res_ty_args = tyConAppArgs res_ty
224 tycon = dataConTyCon data_con
226 ----------- Wrapper --------------
227 -- We used to include the stupid theta in the wrapper's args
228 -- but now we don't. Instead the type checker just injects these
229 -- extra constraints where necessary.
230 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
231 dict_tys = mkPredTys theta
232 wrap_ty = mkForAllTys wrap_tvs $ mkFunTys dict_tys $
233 mkFunTys orig_arg_tys $ res_ty
234 -- NB: watch out here if you allow user-written equality
235 -- constraints in data constructor signatures
237 ----------- Worker (algebraic data types only) --------------
238 -- The *worker* for the data constructor is the function that
239 -- takes the representation arguments and builds the constructor.
240 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
241 (dataConRepType data_con) wkr_info
243 wkr_arity = dataConRepArity data_con
244 wkr_info = noCafIdInfo
245 `setArityInfo` wkr_arity
246 `setAllStrictnessInfo` Just wkr_sig
247 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
250 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
251 -- Note [Data-con worker strictness]
252 -- Notice that we do *not* say the worker is strict
253 -- even if the data constructor is declared strict
254 -- e.g. data T = MkT !(Int,Int)
255 -- Why? Because the *wrapper* is strict (and its unfolding has case
256 -- expresssions that do the evals) but the *worker* itself is not.
257 -- If we pretend it is strict then when we see
258 -- case x of y -> $wMkT y
259 -- the simplifier thinks that y is "sure to be evaluated" (because
260 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
262 -- When the simplifer sees a pattern
263 -- case e of MkT x -> ...
264 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
265 -- but that's fine... dataConRepStrictness comes from the data con
266 -- not from the worker Id.
268 cpr_info | isProductTyCon tycon &&
271 wkr_arity <= mAX_CPR_SIZE = retCPR
273 -- RetCPR is only true for products that are real data types;
274 -- that is, not unboxed tuples or [non-recursive] newtypes
276 ----------- Workers for newtypes --------------
277 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
278 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
279 `setArityInfo` 1 -- Arity 1
280 `setUnfoldingInfo` newtype_unf
281 newtype_unf = ASSERT( isVanillaDataCon data_con &&
282 isSingleton orig_arg_tys )
283 -- No existentials on a newtype, but it can have a context
284 -- e.g. newtype Eq a => T a = MkT (...)
285 mkCompulsoryUnfolding $
286 mkLams wrap_tvs $ Lam id_arg1 $
287 wrapNewTypeBody tycon res_ty_args
290 id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
292 ----------- Wrappers for algebraic data types --------------
293 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
294 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
295 `setArityInfo` alg_arity
296 -- It's important to specify the arity, so that partial
297 -- applications are treated as values
298 `setUnfoldingInfo` alg_unf
299 `setAllStrictnessInfo` Just wrap_sig
301 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
302 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
303 arg_dmds = map mk_dmd all_strict_marks
304 mk_dmd str | isMarkedStrict str = evalDmd
305 | otherwise = lazyDmd
306 -- The Cpr info can be important inside INLINE rhss, where the
307 -- wrapper constructor isn't inlined.
308 -- And the argument strictness can be important too; we
309 -- may not inline a contructor when it is partially applied.
311 -- data W = C !Int !Int !Int
312 -- ...(let w = C x in ...(w p q)...)...
313 -- we want to see that w is strict in its two arguments
315 alg_unf = mkTopUnfolding $ Note InlineMe $
317 mkLams dict_args $ mkLams id_args $
318 foldr mk_case con_app
319 (zip (dict_args ++ id_args) all_strict_marks)
322 con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
323 Var wrk_id `mkTyApps` res_ty_args
325 `mkTyApps` map snd eq_spec -- Equality evidence
326 `mkVarApps` reverse rep_ids
328 (dict_args,i2) = mkLocals 1 dict_tys
329 (id_args,i3) = mkLocals i2 orig_arg_tys
333 :: (Id, StrictnessMark) -- Arg, strictness
334 -> (Int -> [Id] -> CoreExpr) -- Body
335 -> Int -- Next rep arg id
336 -> [Id] -- Rep args so far, reversed
338 mk_case (arg,strict) body i rep_args
340 NotMarkedStrict -> body i (arg:rep_args)
342 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
344 Case (Var arg) arg res_ty [(DEFAULT,[], body i (arg:rep_args))]
347 -> unboxProduct i (Var arg) (idType arg) the_body
349 the_body i con_args = body i (reverse con_args ++ rep_args)
351 mAX_CPR_SIZE :: Arity
353 -- We do not treat very big tuples as CPR-ish:
354 -- a) for a start we get into trouble because there aren't
355 -- "enough" unboxed tuple types (a tiresome restriction,
357 -- b) more importantly, big unboxed tuples get returned mainly
358 -- on the stack, and are often then allocated in the heap
359 -- by the caller. So doing CPR for them may in fact make
362 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
368 %************************************************************************
370 \subsection{Record selectors}
372 %************************************************************************
374 We're going to build a record selector unfolding that looks like this:
376 data T a b c = T1 { ..., op :: a, ...}
377 | T2 { ..., op :: a, ...}
380 sel = /\ a b c -> \ d -> case d of
385 Similarly for newtypes
387 newtype N a = MkN { unN :: a->a }
390 unN n = coerce (a->a) n
392 We need to take a little care if the field has a polymorphic type:
394 data R = R { f :: forall a. a->a }
398 f :: forall a. R -> a -> a
399 f = /\ a \ r = case r of
402 (not f :: R -> forall a. a->a, which gives the type inference mechanism
403 problems at call sites)
405 Similarly for (recursive) newtypes
407 newtype N = MkN { unN :: forall a. a->a }
409 unN :: forall b. N -> b -> b
410 unN = /\b -> \n:N -> (coerce (forall a. a->a) n)
413 Note [Naughty record selectors]
414 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
415 A "naughty" field is one for which we can't define a record
416 selector, because an existential type variable would escape. For example:
417 data T = forall a. MkT { x,y::a }
418 We obviously can't define
420 Nevertheless we *do* put a RecordSelId into the type environment
421 so that if the user tries to use 'x' as a selector we can bleat
422 helpfully, rather than saying unhelpfully that 'x' is not in scope.
423 Hence the sel_naughty flag, to identify record selectors that don't really exist.
425 In general, a field is naughty if its type mentions a type variable that
426 isn't in the result type of the constructor.
428 Note [GADT record selectors]
429 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
430 For GADTs, we require that all constructors with a common field 'f' have the same
431 result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
434 T1 { f :: a } :: T [a]
435 T2 { f :: a, y :: b } :: T [a]
436 and now the selector takes that type as its argument:
437 f :: forall a. T [a] -> a
441 Note the forall'd tyvars of the selector are just the free tyvars
442 of the result type; there may be other tyvars in the constructor's
443 type (e.g. 'b' in T2).
445 Note [Selector running example]
446 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
447 It's OK to combine GADTs and type families. Here's a running example:
449 data instance T [a] where
450 T1 { fld :: b } :: T [Maybe b]
452 The representation type looks like this
454 T1 { fld :: b } :: :R7T (Maybe b)
456 and there's coercion from the family type to the representation type
457 :CoR7T a :: T [a] ~ :R7T a
459 The selector we want for fld looks like this:
461 fld :: forall b. T [Maybe b] -> b
462 fld = /\b. \(d::T [Maybe b]).
463 case d `cast` :CoR7T (Maybe b) of
466 The scrutinee of the case has type :R7T (Maybe b), which can be
467 gotten by appying the eq_spec to the univ_tvs of the data con.
470 mkRecordSelId :: TyCon -> FieldLabel -> Id
471 mkRecordSelId tycon field_label
472 -- Assumes that all fields with the same field label have the same type
473 | is_naughty = naughty_id
476 is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tv_set)
477 sel_id_details = RecordSelId tycon field_label is_naughty
479 -- Escapist case here for naughty constructors
480 -- We give it no IdInfo, and a type of forall a.a (never looked at)
481 naughty_id = mkGlobalId sel_id_details field_label forall_a_a noCafIdInfo
482 forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
484 -- Normal case starts here
485 sel_id = mkGlobalId sel_id_details field_label selector_ty info
486 data_cons = tyConDataCons tycon
487 data_cons_w_field = filter has_field data_cons -- Can't be empty!
488 has_field con = field_label `elem` dataConFieldLabels con
490 con1 = head data_cons_w_field
491 (univ_tvs, _, eq_spec, _, _, data_ty) = dataConFullSig con1
492 data_tv_set = tyVarsOfType data_ty
493 data_tvs = varSetElems data_tv_set
494 field_ty = dataConFieldType con1 field_label
496 -- *Very* tiresomely, the selectors are (unnecessarily!) overloaded over
497 -- just the dictionaries in the types of the constructors that contain
498 -- the relevant field. [The Report says that pattern matching on a
499 -- constructor gives the same constraints as applying it.] Urgh.
501 -- However, not all data cons have all constraints (because of
502 -- BuildTyCl.mkDataConStupidTheta). So we need to find all the data cons
503 -- involved in the pattern match and take the union of their constraints.
504 stupid_dict_tys = mkPredTys (dataConsStupidTheta data_cons_w_field)
505 n_stupid_dicts = length stupid_dict_tys
507 (field_tyvars,pre_field_theta,field_tau) = tcSplitSigmaTy field_ty
508 field_theta = filter (not . isEqPred) pre_field_theta
509 field_dict_tys = mkPredTys field_theta
510 n_field_dict_tys = length field_dict_tys
511 -- If the field has a universally quantified type we have to
512 -- be a bit careful. Suppose we have
513 -- data R = R { op :: forall a. Foo a => a -> a }
514 -- Then we can't give op the type
515 -- op :: R -> forall a. Foo a => a -> a
516 -- because the typechecker doesn't understand foralls to the
517 -- right of an arrow. The "right" type to give it is
518 -- op :: forall a. Foo a => R -> a -> a
519 -- But then we must generate the right unfolding too:
520 -- op = /\a -> \dfoo -> \ r ->
523 -- Note that this is exactly the type we'd infer from a user defn
527 selector_ty = mkForAllTys data_tvs $ mkForAllTys field_tyvars $
528 mkFunTys stupid_dict_tys $ mkFunTys field_dict_tys $
529 mkFunTy data_ty field_tau
531 arity = 1 + n_stupid_dicts + n_field_dict_tys
533 (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
534 -- Use the demand analyser to work out strictness.
535 -- With all this unpackery it's not easy!
538 `setCafInfo` caf_info
540 `setUnfoldingInfo` mkTopUnfolding rhs_w_str
541 `setAllStrictnessInfo` Just strict_sig
543 -- Allocate Ids. We do it a funny way round because field_dict_tys is
544 -- almost always empty. Also note that we use max_dict_tys
545 -- rather than n_dict_tys, because the latter gives an infinite loop:
546 -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
547 -- on arity, which depends on n_dict tys. Sigh! Mega sigh!
548 stupid_dict_ids = mkTemplateLocalsNum 1 stupid_dict_tys
549 max_stupid_dicts = length (tyConStupidTheta tycon)
550 field_dict_base = max_stupid_dicts + 1
551 field_dict_ids = mkTemplateLocalsNum field_dict_base field_dict_tys
552 dict_id_base = field_dict_base + n_field_dict_tys
553 data_id = mkTemplateLocal dict_id_base data_ty
554 scrut_id = mkTemplateLocal (dict_id_base+1) scrut_ty
555 arg_base = dict_id_base + 2
557 the_alts :: [CoreAlt]
558 the_alts = map mk_alt data_cons_w_field -- Already sorted by data-con
559 no_default = length data_cons == length data_cons_w_field -- No default needed
561 default_alt | no_default = []
562 | otherwise = [(DEFAULT, [], error_expr)]
564 -- The default branch may have CAF refs, because it calls recSelError etc.
565 caf_info | no_default = NoCafRefs
566 | otherwise = MayHaveCafRefs
568 sel_rhs = mkLams data_tvs $ mkLams field_tyvars $
569 mkLams stupid_dict_ids $ mkLams field_dict_ids $
570 Lam data_id $ mk_result sel_body
572 scrut_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
573 scrut_ty = mkTyConApp tycon scrut_ty_args
574 scrut = unwrapFamInstScrut tycon scrut_ty_args (Var data_id)
575 -- First coerce from the type family to the representation type
577 -- NB: A newtype always has a vanilla DataCon; no existentials etc
578 -- data_tys will simply be the dataConUnivTyVars
579 sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon scrut_ty_args scrut
580 | otherwise = Case scrut scrut_id field_ty (default_alt ++ the_alts)
582 mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
583 -- We pull the field lambdas to the top, so we need to
584 -- apply them in the body. For example:
585 -- data T = MkT { foo :: forall a. a->a }
587 -- foo :: forall a. T -> a -> a
588 -- foo = /\a. \t:T. case t of { MkT f -> f a }
591 = ASSERT2( data_ty `tcEqType` field_ty, ppr data_con $$ ppr data_ty $$ ppr field_ty )
592 mkReboxingAlt rebox_uniqs data_con (ex_tvs ++ co_tvs ++ arg_vs) rhs
594 -- get pattern binders with types appropriately instantiated
595 arg_uniqs = map mkBuiltinUnique [arg_base..]
596 (ex_tvs, co_tvs, arg_vs) = dataConOrigInstPat arg_uniqs data_con scrut_ty_args
598 rebox_base = arg_base + length ex_tvs + length co_tvs + length arg_vs
599 rebox_uniqs = map mkBuiltinUnique [rebox_base..]
601 -- data T :: *->* where T1 { fld :: Maybe b } -> T [b]
602 -- Hence T1 :: forall a b. (a=[b]) => b -> T a
603 -- fld :: forall b. T [b] -> Maybe b
604 -- fld = /\b.\(t:T[b]). case t of
605 -- T1 b' (c : [b]=[b']) (x:Maybe b')
606 -- -> x `cast` Maybe (sym (right c))
609 -- Generate the refinement for b'=b,
610 -- and apply to (Maybe b'), to get (Maybe b)
611 Succeeded refinement = gadtRefine emptyRefinement ex_tvs co_tvs
612 the_arg_id_ty = idType the_arg_id
613 (rhs, data_ty) = case refineType refinement the_arg_id_ty of
614 Just (co, data_ty) -> (Cast (Var the_arg_id) co, data_ty)
615 Nothing -> (Var the_arg_id, the_arg_id_ty)
617 field_vs = filter (not . isPredTy . idType) arg_vs
618 the_arg_id = assoc "mkRecordSelId:mk_alt" (field_lbls `zip` field_vs) field_label
619 field_lbls = dataConFieldLabels data_con
621 error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_ty full_msg
622 full_msg = showSDoc (sep [text "No match in record selector", ppr sel_id])
624 -- unbox a product type...
625 -- we will recurse into newtypes, casting along the way, and unbox at the
626 -- first product data constructor we find. e.g.
628 -- data PairInt = PairInt Int Int
629 -- newtype S = MkS PairInt
632 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
633 -- ids, we get (modulo int passing)
635 -- case (e `cast` CoT) `cast` CoS of
636 -- PairInt a b -> body [a,b]
638 -- The Ints passed around are just for creating fresh locals
639 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
640 unboxProduct i arg arg_ty body
643 result = mkUnpackCase the_id arg con_args boxing_con rhs
644 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
645 ([the_id], i') = mkLocals i [arg_ty]
646 (con_args, i'') = mkLocals i' tys
647 rhs = body i'' con_args
649 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
650 -- (mkUnpackCase x e args Con body)
652 -- case (e `cast` ...) of bndr { Con args -> body }
654 -- the type of the bndr passed in is irrelevent
655 mkUnpackCase bndr arg unpk_args boxing_con body
656 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
658 (cast_arg, bndr_ty) = go (idType bndr) arg
660 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
661 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
662 = go (newTyConInstRhs tycon tycon_args)
663 (unwrapNewTypeBody tycon tycon_args arg)
664 | otherwise = (arg, ty)
667 reboxProduct :: [Unique] -- uniques to create new local binders
668 -> Type -- type of product to box
669 -> ([Unique], -- remaining uniques
670 CoreExpr, -- boxed product
671 [Id]) -- Ids being boxed into product
674 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
676 us' = dropList con_arg_tys us
678 arg_ids = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
680 bind_rhs = mkProductBox arg_ids ty
683 (us', bind_rhs, arg_ids)
685 mkProductBox :: [Id] -> Type -> CoreExpr
686 mkProductBox arg_ids ty
689 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
692 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
693 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
694 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
696 wrap expr = wrapNewTypeBody tycon tycon_args expr
699 -- (mkReboxingAlt us con xs rhs) basically constructs the case
700 -- alternative (con, xs, rhs)
701 -- but it does the reboxing necessary to construct the *source*
702 -- arguments, xs, from the representation arguments ys.
704 -- data T = MkT !(Int,Int) Bool
706 -- mkReboxingAlt MkT [x,b] r
707 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
709 -- mkDataAlt should really be in DataCon, but it can't because
710 -- it manipulates CoreSyn.
713 :: [Unique] -- Uniques for the new Ids
715 -> [Var] -- Source-level args, including existential dicts
719 mkReboxingAlt us con args rhs
720 | not (any isMarkedUnboxed stricts)
721 = (DataAlt con, args, rhs)
725 (binds, args') = go args stricts us
727 (DataAlt con, args', mkLets binds rhs)
730 stricts = dataConExStricts con ++ dataConStrictMarks con
732 go [] _stricts _us = ([], [])
734 -- Type variable case
735 go (arg:args) stricts us
737 = let (binds, args') = go args stricts us
738 in (binds, arg:args')
740 -- Term variable case
741 go (arg:args) (str:stricts) us
742 | isMarkedUnboxed str
744 let (binds, unpacked_args') = go args stricts us'
745 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
747 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
749 = let (binds, args') = go args stricts us
750 in (binds, arg:args')
754 %************************************************************************
756 \subsection{Dictionary selectors}
758 %************************************************************************
760 Selecting a field for a dictionary. If there is just one field, then
761 there's nothing to do.
763 Dictionary selectors may get nested forall-types. Thus:
766 op :: forall b. Ord b => a -> b -> b
768 Then the top-level type for op is
770 op :: forall a. Foo a =>
774 This is unlike ordinary record selectors, which have all the for-alls
775 at the outside. When dealing with classes it's very convenient to
776 recover the original type signature from the class op selector.
779 mkDictSelId :: Name -> Class -> Id
780 mkDictSelId name clas
781 = mkGlobalId (ClassOpId clas) name sel_ty info
783 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
784 -- We can't just say (exprType rhs), because that would give a type
786 -- for a single-op class (after all, the selector is the identity)
787 -- But it's type must expose the representation of the dictionary
788 -- to gat (say) C a -> (a -> a)
792 `setUnfoldingInfo` mkTopUnfolding rhs
793 `setAllStrictnessInfo` Just strict_sig
795 -- We no longer use 'must-inline' on record selectors. They'll
796 -- inline like crazy if they scrutinise a constructor
798 -- The strictness signature is of the form U(AAAVAAAA) -> T
799 -- where the V depends on which item we are selecting
800 -- It's worth giving one, so that absence info etc is generated
801 -- even if the selector isn't inlined
802 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
803 arg_dmd | isNewTyCon tycon = evalDmd
804 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
807 tycon = classTyCon clas
808 [data_con] = tyConDataCons tycon
809 tyvars = dataConUnivTyVars data_con
810 arg_tys = ASSERT( isVanillaDataCon data_con ) dataConRepArgTys data_con
811 the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
813 pred = mkClassPred clas (mkTyVarTys tyvars)
814 (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
816 rhs = mkLams tyvars (Lam dict_id rhs_body)
817 rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
818 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
819 [(DataAlt data_con, arg_ids, Var the_arg_id)]
823 %************************************************************************
825 Wrapping and unwrapping newtypes and type families
827 %************************************************************************
830 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
831 -- The wrapper for the data constructor for a newtype looks like this:
832 -- newtype T a = MkT (a,Int)
833 -- MkT :: forall a. (a,Int) -> T a
834 -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
835 -- where CoT is the coercion TyCon assoicated with the newtype
837 -- The call (wrapNewTypeBody T [a] e) returns the
838 -- body of the wrapper, namely
839 -- e `cast` (CoT [a])
841 -- If a coercion constructor is provided in the newtype, then we use
842 -- it, otherwise the wrap/unwrap are both no-ops
844 -- If the we are dealing with a newtype *instance*, we have a second coercion
845 -- identifying the family instance with the constructor of the newtype
846 -- instance. This coercion is applied in any case (ie, composed with the
847 -- coercion constructor of the newtype or applied by itself).
849 wrapNewTypeBody tycon args result_expr
850 = wrapFamInstBody tycon args inner
853 | Just co_con <- newTyConCo_maybe tycon
854 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
858 -- When unwrapping, we do *not* apply any family coercion, because this will
859 -- be done via a CoPat by the type checker. We have to do it this way as
860 -- computing the right type arguments for the coercion requires more than just
861 -- a spliting operation (cf, TcPat.tcConPat).
863 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
864 unwrapNewTypeBody tycon args result_expr
865 | Just co_con <- newTyConCo_maybe tycon
866 = mkCoerce (mkTyConApp co_con args) result_expr
870 -- If the type constructor is a representation type of a data instance, wrap
871 -- the expression into a cast adjusting the expression type, which is an
872 -- instance of the representation type, to the corresponding instance of the
873 -- family instance type.
874 -- See Note [Wrappers for data instance tycons]
875 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
876 wrapFamInstBody tycon args body
877 | Just co_con <- tyConFamilyCoercion_maybe tycon
878 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
882 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
883 unwrapFamInstScrut tycon args scrut
884 | Just co_con <- tyConFamilyCoercion_maybe tycon
885 = mkCoerce (mkTyConApp co_con args) scrut
891 %************************************************************************
893 \subsection{Primitive operations
895 %************************************************************************
898 mkPrimOpId :: PrimOp -> Id
902 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
903 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
904 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
905 (mkPrimOpIdUnique (primOpTag prim_op))
907 id = mkGlobalId (PrimOpId prim_op) name ty info
910 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
912 `setAllStrictnessInfo` Just strict_sig
914 -- For each ccall we manufacture a separate CCallOpId, giving it
915 -- a fresh unique, a type that is correct for this particular ccall,
916 -- and a CCall structure that gives the correct details about calling
919 -- The *name* of this Id is a local name whose OccName gives the full
920 -- details of the ccall, type and all. This means that the interface
921 -- file reader can reconstruct a suitable Id
923 mkFCallId :: Unique -> ForeignCall -> Type -> Id
924 mkFCallId uniq fcall ty
925 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
926 -- A CCallOpId should have no free type variables;
927 -- when doing substitutions won't substitute over it
928 mkGlobalId (FCallId fcall) name ty info
930 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
931 -- The "occurrence name" of a ccall is the full info about the
932 -- ccall; it is encoded, but may have embedded spaces etc!
934 name = mkFCallName uniq occ_str
938 `setAllStrictnessInfo` Just strict_sig
940 (_, tau) = tcSplitForAllTys ty
941 (arg_tys, _) = tcSplitFunTys tau
942 arity = length arg_tys
943 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
945 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
946 -- except for the type:
948 -- a plain HPC tick box has type (State# RealWorld)
949 -- a breakpoint Id has type forall a.a
951 -- The breakpoint Id will be applied to a list of arbitrary free variables,
952 -- which is why it needs a polymorphic type.
954 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
955 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
957 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
958 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
959 where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
961 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info
963 tickbox = TickBox mod ix
964 occ_str = showSDoc (braces (ppr tickbox))
965 name = mkTickBoxOpName uniq occ_str
970 %************************************************************************
972 \subsection{DictFuns and default methods}
974 %************************************************************************
976 Important notes about dict funs and default methods
977 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
978 Dict funs and default methods are *not* ImplicitIds. Their definition
979 involves user-written code, so we can't figure out their strictness etc
980 based on fixed info, as we can for constructors and record selectors (say).
982 We build them as LocalIds, but with External Names. This ensures that
983 they are taken to account by free-variable finding and dependency
984 analysis (e.g. CoreFVs.exprFreeVars).
986 Why shouldn't they be bound as GlobalIds? Because, in particular, if
987 they are globals, the specialiser floats dict uses above their defns,
988 which prevents good simplifications happening. Also the strictness
989 analyser treats a occurrence of a GlobalId as imported and assumes it
990 contains strictness in its IdInfo, which isn't true if the thing is
991 bound in the same module as the occurrence.
993 It's OK for dfuns to be LocalIds, because we form the instance-env to
994 pass on to the next module (md_insts) in CoreTidy, afer tidying
995 and globalising the top-level Ids.
997 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
998 that they aren't discarded by the occurrence analyser.
1001 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
1003 mkDictFunId :: Name -- Name to use for the dict fun;
1010 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
1011 = mkExportedLocalId dfun_name dfun_ty
1013 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
1015 {- 1 dec 99: disable the Mark Jones optimisation for the sake
1016 of compatibility with Hugs.
1017 See `types/InstEnv' for a discussion related to this.
1019 (class_tyvars, sc_theta, _, _) = classBigSig clas
1020 not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
1021 sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
1022 dfun_theta = case inst_decl_theta of
1023 [] -> [] -- If inst_decl_theta is empty, then we don't
1024 -- want to have any dict arguments, so that we can
1025 -- expose the constant methods.
1027 other -> nub (inst_decl_theta ++ filter not_const sc_theta')
1028 -- Otherwise we pass the superclass dictionaries to
1029 -- the dictionary function; the Mark Jones optimisation.
1031 -- NOTE the "nub". I got caught by this one:
1032 -- class Monad m => MonadT t m where ...
1033 -- instance Monad m => MonadT (EnvT env) m where ...
1034 -- Here, the inst_decl_theta has (Monad m); but so
1035 -- does the sc_theta'!
1037 -- NOTE the "not_const". I got caught by this one too:
1038 -- class Foo a => Baz a b where ...
1039 -- instance Wob b => Baz T b where..
1040 -- Now sc_theta' has Foo T
1045 %************************************************************************
1047 \subsection{Un-definable}
1049 %************************************************************************
1051 These Ids can't be defined in Haskell. They could be defined in
1052 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
1053 ensure that they were definitely, definitely inlined, because there is
1054 no curried identifier for them. That's what mkCompulsoryUnfolding
1055 does. If we had a way to get a compulsory unfolding from an interface
1056 file, we could do that, but we don't right now.
1058 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
1059 just gets expanded into a type coercion wherever it occurs. Hence we
1060 add it as a built-in Id with an unfolding here.
1062 The type variables we use here are "open" type variables: this means
1063 they can unify with both unlifted and lifted types. Hence we provide
1064 another gun with which to shoot yourself in the foot.
1067 mkWiredInIdName mod fs uniq id
1068 = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
1070 unsafeCoerceName = mkWiredInIdName gHC_PRIM FSLIT("unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
1071 nullAddrName = mkWiredInIdName gHC_PRIM FSLIT("nullAddr#") nullAddrIdKey nullAddrId
1072 seqName = mkWiredInIdName gHC_PRIM FSLIT("seq") seqIdKey seqId
1073 realWorldName = mkWiredInIdName gHC_PRIM FSLIT("realWorld#") realWorldPrimIdKey realWorldPrimId
1074 lazyIdName = mkWiredInIdName gHC_BASE FSLIT("lazy") lazyIdKey lazyId
1076 errorName = mkWiredInIdName gHC_ERR FSLIT("error") errorIdKey eRROR_ID
1077 recSelErrorName = mkWiredInIdName gHC_ERR FSLIT("recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
1078 runtimeErrorName = mkWiredInIdName gHC_ERR FSLIT("runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
1079 irrefutPatErrorName = mkWiredInIdName gHC_ERR FSLIT("irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
1080 recConErrorName = mkWiredInIdName gHC_ERR FSLIT("recConError") recConErrorIdKey rEC_CON_ERROR_ID
1081 patErrorName = mkWiredInIdName gHC_ERR FSLIT("patError") patErrorIdKey pAT_ERROR_ID
1082 noMethodBindingErrorName = mkWiredInIdName gHC_ERR FSLIT("noMethodBindingError")
1083 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
1084 nonExhaustiveGuardsErrorName
1085 = mkWiredInIdName gHC_ERR FSLIT("nonExhaustiveGuardsError")
1086 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
1090 -- unsafeCoerce# :: forall a b. a -> b
1092 = pcMiscPrelId unsafeCoerceName ty info
1094 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1097 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
1098 (mkFunTy openAlphaTy openBetaTy)
1099 [x] = mkTemplateLocals [openAlphaTy]
1100 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
1101 Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
1103 -- nullAddr# :: Addr#
1104 -- The reason is is here is because we don't provide
1105 -- a way to write this literal in Haskell.
1107 = pcMiscPrelId nullAddrName addrPrimTy info
1109 info = noCafIdInfo `setUnfoldingInfo`
1110 mkCompulsoryUnfolding (Lit nullAddrLit)
1113 = pcMiscPrelId seqName ty info
1115 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1118 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
1119 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
1120 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
1121 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
1123 -- lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
1124 -- Used to lazify pseq: pseq a b = a `seq` lazy b
1126 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1127 -- not from GHC.Base.hi. This is important, because the strictness
1128 -- analyser will spot it as strict!
1130 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapper pass
1131 -- (see WorkWrap.wwExpr)
1132 -- We could use inline phases to do this, but that would be vulnerable to changes in
1133 -- phase numbering....we must inline precisely after strictness analysis.
1135 = pcMiscPrelId lazyIdName ty info
1138 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1140 lazyIdUnfolding :: CoreExpr -- Used to expand 'lazyId' after strictness anal
1141 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1143 [x] = mkTemplateLocals [openAlphaTy]
1146 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1147 nasty as-is, change it back to a literal (@Literal@).
1149 voidArgId is a Local Id used simply as an argument in functions
1150 where we just want an arg to avoid having a thunk of unlifted type.
1152 x = \ void :: State# RealWorld -> (# p, q #)
1154 This comes up in strictness analysis
1157 realWorldPrimId -- :: State# RealWorld
1158 = pcMiscPrelId realWorldName realWorldStatePrimTy
1159 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1160 -- The evaldUnfolding makes it look that realWorld# is evaluated
1161 -- which in turn makes Simplify.interestingArg return True,
1162 -- which in turn makes INLINE things applied to realWorld# likely
1165 voidArgId -- :: State# RealWorld
1166 = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
1170 %************************************************************************
1172 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1174 %************************************************************************
1176 GHC randomly injects these into the code.
1178 @patError@ is just a version of @error@ for pattern-matching
1179 failures. It knows various ``codes'' which expand to longer
1180 strings---this saves space!
1182 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
1183 well shouldn't be yanked on, but if one is, then you will get a
1184 friendly message from @absentErr@ (rather than a totally random
1187 @parError@ is a special version of @error@ which the compiler does
1188 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
1189 templates, but we don't ever expect to generate code for it.
1193 :: Id -- Should be of type (forall a. Addr# -> a)
1194 -- where Addr# points to a UTF8 encoded string
1195 -> Type -- The type to instantiate 'a'
1196 -> String -- The string to print
1199 mkRuntimeErrorApp err_id res_ty err_msg
1200 = mkApps (Var err_id) [Type res_ty, err_string]
1202 err_string = Lit (mkStringLit err_msg)
1204 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
1205 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
1206 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
1207 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
1208 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
1209 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
1210 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1212 -- The runtime error Ids take a UTF8-encoded string as argument
1213 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1214 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1218 eRROR_ID = pc_bottoming_Id errorName errorTy
1221 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1222 -- Notice the openAlphaTyVar. It says that "error" can be applied
1223 -- to unboxed as well as boxed types. This is OK because it never
1224 -- returns, so the return type is irrelevant.
1228 %************************************************************************
1230 \subsection{Utilities}
1232 %************************************************************************
1235 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1236 pcMiscPrelId name ty info
1237 = mkVanillaGlobal name ty info
1238 -- We lie and say the thing is imported; otherwise, we get into
1239 -- a mess with dependency analysis; e.g., core2stg may heave in
1240 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1241 -- being compiled, then it's just a matter of luck if the definition
1242 -- will be in "the right place" to be in scope.
1244 pc_bottoming_Id name ty
1245 = pcMiscPrelId name ty bottoming_info
1247 bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1248 -- Do *not* mark them as NoCafRefs, because they can indeed have
1249 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1250 -- which has some CAFs
1251 -- In due course we may arrange that these error-y things are
1252 -- regarded by the GC as permanently live, in which case we
1253 -- can give them NoCaf info. As it is, any function that calls
1254 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1257 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1258 -- These "bottom" out, no matter what their arguments