2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1998
6 This module contains definitions for the IdInfo for things that
7 have a standard form, namely:
11 - method and superclass selectors
12 - primitive operations
15 {-# OPTIONS -fno-warn-missing-signatures #-}
16 -- The above warning supression flag is a temporary kludge.
17 -- While working on this module you are encouraged to remove it and fix
18 -- any warnings in the module. See
19 -- <http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings>
23 mkDictFunId, mkDefaultMethodId,
28 mkPrimOpId, mkFCallId, mkTickBoxOpId, mkBreakPointOpId,
30 mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
31 wrapFamInstBody, unwrapFamInstScrut,
32 mkUnpackCase, mkProductBox,
34 -- And some particular Ids; see below for why they are wired in
35 wiredInIds, ghcPrimIds,
36 unsafeCoerceId, realWorldPrimId, voidArgId, nullAddrId, seqId,
37 lazyId, lazyIdUnfolding, lazyIdKey,
40 rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
41 nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
42 pAT_ERROR_ID, eRROR_ID,
47 #include "HsVersions.h"
70 import Var ( Var, TyVar, mkCoVar)
78 import BasicTypes hiding ( SuccessFlag(..) )
86 %************************************************************************
88 \subsection{Wired in Ids}
90 %************************************************************************
95 = [ -- These error-y things are wired in because we don't yet have
96 -- a way to express in an interface file that the result type variable
97 -- is 'open'; that is can be unified with an unboxed type
99 -- [The interface file format now carry such information, but there's
100 -- no way yet of expressing at the definition site for these
101 -- error-reporting functions that they have an 'open'
102 -- result type. -- sof 1/99]
104 eRROR_ID, -- This one isn't used anywhere else in the compiler
105 -- But we still need it in wiredInIds so that when GHC
106 -- compiles a program that mentions 'error' we don't
107 -- import its type from the interface file; we just get
108 -- the Id defined here. Which has an 'open-tyvar' type.
111 iRREFUT_PAT_ERROR_ID,
112 nON_EXHAUSTIVE_GUARDS_ERROR_ID,
113 nO_METHOD_BINDING_ERROR_ID,
120 -- These Ids are exported from GHC.Prim
123 = [ -- These can't be defined in Haskell, but they have
124 -- perfectly reasonable unfoldings in Core
132 %************************************************************************
134 \subsection{Data constructors}
136 %************************************************************************
138 The wrapper for a constructor is an ordinary top-level binding that evaluates
139 any strict args, unboxes any args that are going to be flattened, and calls
142 We're going to build a constructor that looks like:
144 data (Data a, C b) => T a b = T1 !a !Int b
147 \d1::Data a, d2::C b ->
148 \p q r -> case p of { p ->
150 Con T1 [a,b] [p,q,r]}}
154 * d2 is thrown away --- a context in a data decl is used to make sure
155 one *could* construct dictionaries at the site the constructor
156 is used, but the dictionary isn't actually used.
158 * We have to check that we can construct Data dictionaries for
159 the types a and Int. Once we've done that we can throw d1 away too.
161 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
162 all that matters is that the arguments are evaluated. "seq" is
163 very careful to preserve evaluation order, which we don't need
166 You might think that we could simply give constructors some strictness
167 info, like PrimOps, and let CoreToStg do the let-to-case transformation.
168 But we don't do that because in the case of primops and functions strictness
169 is a *property* not a *requirement*. In the case of constructors we need to
170 do something active to evaluate the argument.
172 Making an explicit case expression allows the simplifier to eliminate
173 it in the (common) case where the constructor arg is already evaluated.
175 Note [Wrappers for data instance tycons]
176 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
177 In the case of data instances, the wrapper also applies the coercion turning
178 the representation type into the family instance type to cast the result of
179 the wrapper. For example, consider the declarations
181 data family Map k :: * -> *
182 data instance Map (a, b) v = MapPair (Map a (Pair b v))
184 The tycon to which the datacon MapPair belongs gets a unique internal
185 name of the form :R123Map, and we call it the representation tycon.
186 In contrast, Map is the family tycon (accessible via
187 tyConFamInst_maybe). A coercion allows you to move between
188 representation and family type. It is accessible from :R123Map via
189 tyConFamilyCoercion_maybe and has kind
191 Co123Map a b v :: {Map (a, b) v :=: :R123Map a b v}
193 The wrapper and worker of MapPair get the types
196 $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
197 $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v)
200 MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
202 This coercion is conditionally applied by wrapFamInstBody.
204 It's a bit more complicated if the data instance is a GADT as well!
206 data instance T [a] where
207 T1 :: forall b. b -> T [Maybe b]
209 Co7T a :: T [a] ~ :R7T a
214 $WT1 :: forall b. b -> T [Maybe b]
215 $WT1 b v = T1 (Maybe b) b (Maybe b) v
216 `cast` sym (Co7T (Maybe b))
219 T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
222 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
223 mkDataConIds wrap_name wkr_name data_con
224 | isNewTyCon tycon -- Newtype, only has a worker
225 = DCIds Nothing nt_work_id
227 | any isMarkedStrict all_strict_marks -- Algebraic, needs wrapper
228 || not (null eq_spec) -- NB: LoadIface.ifaceDeclSubBndrs
229 || isFamInstTyCon tycon -- depends on this test
230 = DCIds (Just alg_wrap_id) wrk_id
232 | otherwise -- Algebraic, no wrapper
233 = DCIds Nothing wrk_id
235 (univ_tvs, ex_tvs, eq_spec,
236 eq_theta, dict_theta, orig_arg_tys, res_ty) = dataConFullSig data_con
237 tycon = dataConTyCon data_con -- The representation TyCon (not family)
239 ----------- Worker (algebraic data types only) --------------
240 -- The *worker* for the data constructor is the function that
241 -- takes the representation arguments and builds the constructor.
242 wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
243 (dataConRepType data_con) wkr_info
245 wkr_arity = dataConRepArity data_con
246 wkr_info = noCafIdInfo
247 `setArityInfo` wkr_arity
248 `setAllStrictnessInfo` Just wkr_sig
249 `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
252 wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
253 -- Note [Data-con worker strictness]
254 -- Notice that we do *not* say the worker is strict
255 -- even if the data constructor is declared strict
256 -- e.g. data T = MkT !(Int,Int)
257 -- Why? Because the *wrapper* is strict (and its unfolding has case
258 -- expresssions that do the evals) but the *worker* itself is not.
259 -- If we pretend it is strict then when we see
260 -- case x of y -> $wMkT y
261 -- the simplifier thinks that y is "sure to be evaluated" (because
262 -- $wMkT is strict) and drops the case. No, $wMkT is not strict.
264 -- When the simplifer sees a pattern
265 -- case e of MkT x -> ...
266 -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
267 -- but that's fine... dataConRepStrictness comes from the data con
268 -- not from the worker Id.
270 cpr_info | isProductTyCon tycon &&
273 wkr_arity <= mAX_CPR_SIZE = retCPR
275 -- RetCPR is only true for products that are real data types;
276 -- that is, not unboxed tuples or [non-recursive] newtypes
278 ----------- Workers for newtypes --------------
279 nt_work_id = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
280 nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
281 `setArityInfo` 1 -- Arity 1
282 `setUnfoldingInfo` newtype_unf
283 newtype_unf = -- The assertion below is no longer correct:
284 -- there may be a dict theta rather than a singleton orig_arg_ty
285 -- ASSERT( isVanillaDataCon data_con &&
286 -- isSingleton orig_arg_tys )
288 -- No existentials on a newtype, but it can have a context
289 -- e.g. newtype Eq a => T a = MkT (...)
290 mkCompulsoryUnfolding $
291 mkLams wrap_tvs $ Lam id_arg1 $
292 wrapNewTypeBody tycon res_ty_args
295 id_arg1 = mkTemplateLocal 1
296 (if null orig_arg_tys
297 then ASSERT(not (null $ dataConDictTheta data_con)) mkPredTy $ head (dataConDictTheta data_con)
298 else head orig_arg_tys
301 ----------- Wrapper --------------
302 -- We used to include the stupid theta in the wrapper's args
303 -- but now we don't. Instead the type checker just injects these
304 -- extra constraints where necessary.
305 wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
306 res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
307 eq_tys = mkPredTys eq_theta
308 dict_tys = mkPredTys dict_theta
309 wrap_ty = mkForAllTys wrap_tvs $ mkFunTys eq_tys $ mkFunTys dict_tys $
310 mkFunTys orig_arg_tys $ res_ty
311 -- NB: watch out here if you allow user-written equality
312 -- constraints in data constructor signatures
314 ----------- Wrappers for algebraic data types --------------
315 alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
316 alg_wrap_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
317 `setArityInfo` wrap_arity
318 -- It's important to specify the arity, so that partial
319 -- applications are treated as values
320 `setUnfoldingInfo` wrap_unf
321 `setAllStrictnessInfo` Just wrap_sig
323 all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
324 wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
325 arg_dmds = map mk_dmd all_strict_marks
326 mk_dmd str | isMarkedStrict str = evalDmd
327 | otherwise = lazyDmd
328 -- The Cpr info can be important inside INLINE rhss, where the
329 -- wrapper constructor isn't inlined.
330 -- And the argument strictness can be important too; we
331 -- may not inline a contructor when it is partially applied.
333 -- data W = C !Int !Int !Int
334 -- ...(let w = C x in ...(w p q)...)...
335 -- we want to see that w is strict in its two arguments
337 wrap_unf = mkImplicitUnfolding $ Note InlineMe $
340 mkLams dict_args $ mkLams id_args $
341 foldr mk_case con_app
342 (zip (dict_args ++ id_args) all_strict_marks)
345 con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
346 Var wrk_id `mkTyApps` res_ty_args
348 -- Equality evidence:
349 `mkTyApps` map snd eq_spec
351 `mkVarApps` reverse rep_ids
353 (dict_args,i2) = mkLocals 1 dict_tys
354 (id_args,i3) = mkLocals i2 orig_arg_tys
356 (eq_args,_) = mkCoVarLocals i3 eq_tys
358 mkCoVarLocals i [] = ([],i)
359 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
360 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
364 :: (Id, StrictnessMark) -- Arg, strictness
365 -> (Int -> [Id] -> CoreExpr) -- Body
366 -> Int -- Next rep arg id
367 -> [Id] -- Rep args so far, reversed
369 mk_case (arg,strict) body i rep_args
371 NotMarkedStrict -> body i (arg:rep_args)
373 | isUnLiftedType (idType arg) -> body i (arg:rep_args)
375 Case (Var arg) arg res_ty [(DEFAULT,[], body i (arg:rep_args))]
378 -> unboxProduct i (Var arg) (idType arg) the_body
380 the_body i con_args = body i (reverse con_args ++ rep_args)
382 mAX_CPR_SIZE :: Arity
384 -- We do not treat very big tuples as CPR-ish:
385 -- a) for a start we get into trouble because there aren't
386 -- "enough" unboxed tuple types (a tiresome restriction,
388 -- b) more importantly, big unboxed tuples get returned mainly
389 -- on the stack, and are often then allocated in the heap
390 -- by the caller. So doing CPR for them may in fact make
393 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
399 %************************************************************************
401 \subsection{Record selectors}
403 %************************************************************************
405 We're going to build a record selector unfolding that looks like this:
407 data T a b c = T1 { ..., op :: a, ...}
408 | T2 { ..., op :: a, ...}
411 sel = /\ a b c -> \ d -> case d of
416 Similarly for newtypes
418 newtype N a = MkN { unN :: a->a }
421 unN n = coerce (a->a) n
423 We need to take a little care if the field has a polymorphic type:
425 data R = R { f :: forall a. a->a }
429 f :: forall a. R -> a -> a
430 f = /\ a \ r = case r of
433 (not f :: R -> forall a. a->a, which gives the type inference mechanism
434 problems at call sites)
436 Similarly for (recursive) newtypes
438 newtype N = MkN { unN :: forall a. a->a }
440 unN :: forall b. N -> b -> b
441 unN = /\b -> \n:N -> (coerce (forall a. a->a) n)
444 Note [Naughty record selectors]
445 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
446 A "naughty" field is one for which we can't define a record
447 selector, because an existential type variable would escape. For example:
448 data T = forall a. MkT { x,y::a }
449 We obviously can't define
451 Nevertheless we *do* put a RecordSelId into the type environment
452 so that if the user tries to use 'x' as a selector we can bleat
453 helpfully, rather than saying unhelpfully that 'x' is not in scope.
454 Hence the sel_naughty flag, to identify record selectors that don't really exist.
456 In general, a field is naughty if its type mentions a type variable that
457 isn't in the result type of the constructor.
459 Note [GADT record selectors]
460 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
461 For GADTs, we require that all constructors with a common field 'f' have the same
462 result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
465 T1 { f :: Maybe a } :: T [a]
466 T2 { f :: Maybe a, y :: b } :: T [a]
468 and now the selector takes that result type as its argument:
469 f :: forall a. T [a] -> Maybe a
471 Details: the "real" types of T1,T2 are:
472 T1 :: forall r a. (r~[a]) => a -> T r
473 T2 :: forall r a b. (r~[a]) => a -> b -> T r
475 So the selector loooks like this:
476 f :: forall a. T [a] -> Maybe a
479 T1 c (g:[a]~[c]) (v:Maybe c) -> v `cast` Maybe (right (sym g))
480 T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
482 Note the forall'd tyvars of the selector are just the free tyvars
483 of the result type; there may be other tyvars in the constructor's
484 type (e.g. 'b' in T2).
486 Note the need for casts in the result!
488 Note [Selector running example]
489 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
490 It's OK to combine GADTs and type families. Here's a running example:
492 data instance T [a] where
493 T1 { fld :: b } :: T [Maybe b]
495 The representation type looks like this
497 T1 { fld :: b } :: :R7T (Maybe b)
499 and there's coercion from the family type to the representation type
500 :CoR7T a :: T [a] ~ :R7T a
502 The selector we want for fld looks like this:
504 fld :: forall b. T [Maybe b] -> b
505 fld = /\b. \(d::T [Maybe b]).
506 case d `cast` :CoR7T (Maybe b) of
509 The scrutinee of the case has type :R7T (Maybe b), which can be
510 gotten by appying the eq_spec to the univ_tvs of the data con.
513 mkRecordSelId :: TyCon -> FieldLabel -> Id
514 mkRecordSelId tycon field_label
515 -- Assumes that all fields with the same field label have the same type
518 -- Because this function gets called by implicitTyThings, we need to
519 -- produce the OccName of the Id without doing any suspend type checks.
520 -- (see the note [Tricky iface loop]).
521 -- A suspended type-check is sometimes necessary to compute field_ty,
522 -- so we need to make sure that we suspend anything that depends on field_ty.
524 -- the overall result
525 sel_id = mkGlobalId sel_id_details field_label theType theInfo
527 -- check whether the type is naughty: this thunk does not get forced
528 -- until the type is actually needed
529 field_ty = dataConFieldType con1 field_label
530 is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tv_set)
532 -- it's important that this doesn't force the if
533 (theType, theInfo) = if is_naughty
534 -- Escapist case here for naughty constructors
535 -- We give it no IdInfo, and a type of
536 -- forall a.a (never looked at)
537 then (forall_a_a, noCafIdInfo)
538 -- otherwise do the real case
539 else (selector_ty, info)
541 sel_id_details = RecordSelId { sel_tycon = tycon,
542 sel_label = field_label,
543 sel_naughty = is_naughty }
544 -- For a data type family, the tycon is the *instance* TyCon
547 forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
549 -- real case starts here:
550 data_cons = tyConDataCons tycon
551 data_cons_w_field = filter has_field data_cons -- Can't be empty!
552 has_field con = field_label `elem` dataConFieldLabels con
554 con1 = ASSERT( not (null data_cons_w_field) ) head data_cons_w_field
555 (univ_tvs, _, eq_spec, _, _, _, data_ty) = dataConFullSig con1
556 -- For a data type family, the data_ty (and hence selector_ty) mentions
557 -- only the family TyCon, not the instance TyCon
558 data_tv_set = tyVarsOfType data_ty
559 data_tvs = varSetElems data_tv_set
561 -- _Very_ tiresomely, the selectors are (unnecessarily!) overloaded over
562 -- just the dictionaries in the types of the constructors that contain
563 -- the relevant field. [The Report says that pattern matching on a
564 -- constructor gives the same constraints as applying it.] Urgh.
566 -- However, not all data cons have all constraints (because of
567 -- BuildTyCl.mkDataConStupidTheta). So we need to find all the data cons
568 -- involved in the pattern match and take the union of their constraints.
569 stupid_dict_tys = mkPredTys (dataConsStupidTheta data_cons_w_field)
570 n_stupid_dicts = length stupid_dict_tys
572 (field_tyvars,pre_field_theta,field_tau) = tcSplitSigmaTy field_ty
573 field_theta = filter (not . isEqPred) pre_field_theta
574 field_dict_tys = mkPredTys field_theta
575 n_field_dict_tys = length field_dict_tys
576 -- If the field has a universally quantified type we have to
577 -- be a bit careful. Suppose we have
578 -- data R = R { op :: forall a. Foo a => a -> a }
579 -- Then we can't give op the type
580 -- op :: R -> forall a. Foo a => a -> a
581 -- because the typechecker doesn't understand foralls to the
582 -- right of an arrow. The "right" type to give it is
583 -- op :: forall a. Foo a => R -> a -> a
584 -- But then we must generate the right unfolding too:
585 -- op = /\a -> \dfoo -> \ r ->
588 -- Note that this is exactly the type we'd infer from a user defn
592 selector_ty = mkForAllTys data_tvs $ mkForAllTys field_tyvars $
593 mkFunTys stupid_dict_tys $ mkFunTys field_dict_tys $
594 mkFunTy data_ty field_tau
596 arity = 1 + n_stupid_dicts + n_field_dict_tys
598 (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
599 -- Use the demand analyser to work out strictness.
600 -- With all this unpackery it's not easy!
603 `setCafInfo` caf_info
605 `setUnfoldingInfo` unfolding
606 `setAllStrictnessInfo` Just strict_sig
608 unfolding = mkImplicitUnfolding rhs_w_str
610 -- Allocate Ids. We do it a funny way round because field_dict_tys is
611 -- almost always empty. Also note that we use max_dict_tys
612 -- rather than n_dict_tys, because the latter gives an infinite loop:
613 -- n_dict tys depends on the_alts, which depens on arg_ids, which
614 -- depends on arity, which depends on n_dict tys. Sigh! Mega sigh!
615 stupid_dict_ids = mkTemplateLocalsNum 1 stupid_dict_tys
616 max_stupid_dicts = length (tyConStupidTheta tycon)
617 field_dict_base = max_stupid_dicts + 1
618 field_dict_ids = mkTemplateLocalsNum field_dict_base field_dict_tys
619 dict_id_base = field_dict_base + n_field_dict_tys
620 data_id = mkTemplateLocal dict_id_base data_ty
621 scrut_id = mkTemplateLocal (dict_id_base+1) scrut_ty
622 arg_base = dict_id_base + 2
624 the_alts :: [CoreAlt]
625 the_alts = map mk_alt data_cons_w_field -- Already sorted by data-con
626 no_default = length data_cons == length data_cons_w_field -- No default needed
628 default_alt | no_default = []
629 | otherwise = [(DEFAULT, [], error_expr)]
631 -- The default branch may have CAF refs, because it calls recSelError etc.
632 caf_info | no_default = NoCafRefs
633 | otherwise = MayHaveCafRefs
635 sel_rhs = mkLams data_tvs $ mkLams field_tyvars $
636 mkLams stupid_dict_ids $ mkLams field_dict_ids $
637 Lam data_id $ mk_result sel_body
639 scrut_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
640 scrut_ty = mkTyConApp tycon scrut_ty_args
641 scrut = unwrapFamInstScrut tycon scrut_ty_args (Var data_id)
642 -- First coerce from the type family to the representation type
644 -- NB: A newtype always has a vanilla DataCon; no existentials etc
645 -- data_tys will simply be the dataConUnivTyVars
646 sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon scrut_ty_args scrut
647 | otherwise = Case scrut scrut_id field_ty (default_alt ++ the_alts)
649 mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
650 -- We pull the field lambdas to the top, so we need to
651 -- apply them in the body. For example:
652 -- data T = MkT { foo :: forall a. a->a }
654 -- foo :: forall a. T -> a -> a
655 -- foo = /\a. \t:T. case t of { MkT f -> f a }
658 = mkReboxingAlt rebox_uniqs data_con (ex_tvs ++ co_tvs ++ arg_vs) rhs
660 -- get pattern binders with types appropriately instantiated
661 arg_uniqs = map mkBuiltinUnique [arg_base..]
662 (ex_tvs, co_tvs, arg_vs) = dataConOrigInstPat arg_uniqs data_con
665 rebox_base = arg_base + length ex_tvs + length co_tvs + length arg_vs
666 rebox_uniqs = map mkBuiltinUnique [rebox_base..]
668 -- data T :: *->* where T1 { fld :: Maybe b } -> T [b]
669 -- Hence T1 :: forall a b. (a~[b]) => b -> T a
670 -- fld :: forall b. T [b] -> Maybe b
671 -- fld = /\b.\(t:T[b]). case t of
672 -- T1 b' (c : [b]=[b']) (x:Maybe b')
673 -- -> x `cast` Maybe (sym (right c))
675 -- Generate the cast for the result
676 -- See Note [GADT record selectors] for why a cast is needed
677 in_scope_tvs = ex_tvs ++ co_tvs ++ data_tvs
678 reft = matchRefine in_scope_tvs (map (mkSymCoercion . mkTyVarTy) co_tvs)
679 rhs = case refineType reft (idType the_arg_id) of
680 Nothing -> Var the_arg_id
681 Just (co, data_ty) -> ASSERT2( data_ty `tcEqType` field_ty,
682 ppr data_con $$ ppr data_ty $$ ppr field_ty )
683 Cast (Var the_arg_id) co
685 field_vs = filter (not . isPredTy . idType) arg_vs
686 the_arg_id = assoc "mkRecordSelId:mk_alt"
687 (field_lbls `zip` field_vs) field_label
688 field_lbls = dataConFieldLabels data_con
690 error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_ty full_msg
691 full_msg = showSDoc (sep [text "No match in record selector", ppr sel_id])
693 -- unbox a product type...
694 -- we will recurse into newtypes, casting along the way, and unbox at the
695 -- first product data constructor we find. e.g.
697 -- data PairInt = PairInt Int Int
698 -- newtype S = MkS PairInt
701 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
702 -- ids, we get (modulo int passing)
704 -- case (e `cast` CoT) `cast` CoS of
705 -- PairInt a b -> body [a,b]
707 -- The Ints passed around are just for creating fresh locals
708 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
709 unboxProduct i arg arg_ty body
712 result = mkUnpackCase the_id arg con_args boxing_con rhs
713 (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
714 ([the_id], i') = mkLocals i [arg_ty]
715 (con_args, i'') = mkLocals i' tys
716 rhs = body i'' con_args
718 mkUnpackCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
719 -- (mkUnpackCase x e args Con body)
721 -- case (e `cast` ...) of bndr { Con args -> body }
723 -- the type of the bndr passed in is irrelevent
724 mkUnpackCase bndr arg unpk_args boxing_con body
725 = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
727 (cast_arg, bndr_ty) = go (idType bndr) arg
729 | (tycon, tycon_args, _, _) <- splitProductType "mkUnpackCase" ty
730 , isNewTyCon tycon && not (isRecursiveTyCon tycon)
731 = go (newTyConInstRhs tycon tycon_args)
732 (unwrapNewTypeBody tycon tycon_args arg)
733 | otherwise = (arg, ty)
736 reboxProduct :: [Unique] -- uniques to create new local binders
737 -> Type -- type of product to box
738 -> ([Unique], -- remaining uniques
739 CoreExpr, -- boxed product
740 [Id]) -- Ids being boxed into product
743 (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
745 us' = dropList con_arg_tys us
747 arg_ids = zipWith (mkSysLocal (fsLit "rb")) us con_arg_tys
749 bind_rhs = mkProductBox arg_ids ty
752 (us', bind_rhs, arg_ids)
754 mkProductBox :: [Id] -> Type -> CoreExpr
755 mkProductBox arg_ids ty
758 (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
761 | isNewTyCon tycon && not (isRecursiveTyCon tycon)
762 = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
763 | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
765 wrap expr = wrapNewTypeBody tycon tycon_args expr
768 -- (mkReboxingAlt us con xs rhs) basically constructs the case
769 -- alternative (con, xs, rhs)
770 -- but it does the reboxing necessary to construct the *source*
771 -- arguments, xs, from the representation arguments ys.
773 -- data T = MkT !(Int,Int) Bool
775 -- mkReboxingAlt MkT [x,b] r
776 -- = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
778 -- mkDataAlt should really be in DataCon, but it can't because
779 -- it manipulates CoreSyn.
782 :: [Unique] -- Uniques for the new Ids
784 -> [Var] -- Source-level args, including existential dicts
788 mkReboxingAlt us con args rhs
789 | not (any isMarkedUnboxed stricts)
790 = (DataAlt con, args, rhs)
794 (binds, args') = go args stricts us
796 (DataAlt con, args', mkLets binds rhs)
799 stricts = dataConExStricts con ++ dataConStrictMarks con
801 go [] _stricts _us = ([], [])
803 -- Type variable case
804 go (arg:args) stricts us
806 = let (binds, args') = go args stricts us
807 in (binds, arg:args')
809 -- Term variable case
810 go (arg:args) (str:stricts) us
811 | isMarkedUnboxed str
813 let (binds, unpacked_args') = go args stricts us'
814 (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
816 (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
818 = let (binds, args') = go args stricts us
819 in (binds, arg:args')
820 go (_ : _) [] _ = panic "mkReboxingAlt"
824 %************************************************************************
826 \subsection{Dictionary selectors}
828 %************************************************************************
830 Selecting a field for a dictionary. If there is just one field, then
831 there's nothing to do.
833 Dictionary selectors may get nested forall-types. Thus:
836 op :: forall b. Ord b => a -> b -> b
838 Then the top-level type for op is
840 op :: forall a. Foo a =>
844 This is unlike ordinary record selectors, which have all the for-alls
845 at the outside. When dealing with classes it's very convenient to
846 recover the original type signature from the class op selector.
849 mkDictSelId :: Bool -- True <=> don't include the unfolding
850 -- Little point on imports without -O, because the
851 -- dictionary itself won't be visible
852 -> Name -> Class -> Id
853 mkDictSelId no_unf name clas
854 = mkGlobalId (ClassOpId clas) name sel_ty info
856 sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
857 -- We can't just say (exprType rhs), because that would give a type
859 -- for a single-op class (after all, the selector is the identity)
860 -- But it's type must expose the representation of the dictionary
861 -- to get (say) C a -> (a -> a)
865 `setAllStrictnessInfo` Just strict_sig
866 `setUnfoldingInfo` (if no_unf then noUnfolding
867 else mkImplicitUnfolding rhs)
869 -- We no longer use 'must-inline' on record selectors. They'll
870 -- inline like crazy if they scrutinise a constructor
872 -- The strictness signature is of the form U(AAAVAAAA) -> T
873 -- where the V depends on which item we are selecting
874 -- It's worth giving one, so that absence info etc is generated
875 -- even if the selector isn't inlined
876 strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
877 arg_dmd | isNewTyCon tycon = evalDmd
878 | otherwise = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
881 tycon = classTyCon clas
882 [data_con] = tyConDataCons tycon
883 tyvars = dataConUnivTyVars data_con
884 arg_tys = {- ASSERT( isVanillaDataCon data_con ) -} dataConRepArgTys data_con
885 eq_theta = dataConEqTheta data_con
886 the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
888 pred = mkClassPred clas (mkTyVarTys tyvars)
889 dict_id = mkTemplateLocal 1 $ mkPredTy pred
890 (eq_ids,n) = mkCoVarLocals 2 $ mkPredTys eq_theta
891 arg_ids = mkTemplateLocalsNum n arg_tys
893 mkCoVarLocals i [] = ([],i)
894 mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
895 y = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
898 rhs = mkLams tyvars (Lam dict_id rhs_body)
899 rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
900 | otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
901 [(DataAlt data_con, eq_ids ++ arg_ids, Var the_arg_id)]
905 %************************************************************************
907 Wrapping and unwrapping newtypes and type families
909 %************************************************************************
912 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
913 -- The wrapper for the data constructor for a newtype looks like this:
914 -- newtype T a = MkT (a,Int)
915 -- MkT :: forall a. (a,Int) -> T a
916 -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
917 -- where CoT is the coercion TyCon assoicated with the newtype
919 -- The call (wrapNewTypeBody T [a] e) returns the
920 -- body of the wrapper, namely
921 -- e `cast` (CoT [a])
923 -- If a coercion constructor is provided in the newtype, then we use
924 -- it, otherwise the wrap/unwrap are both no-ops
926 -- If the we are dealing with a newtype *instance*, we have a second coercion
927 -- identifying the family instance with the constructor of the newtype
928 -- instance. This coercion is applied in any case (ie, composed with the
929 -- coercion constructor of the newtype or applied by itself).
931 wrapNewTypeBody tycon args result_expr
932 = wrapFamInstBody tycon args inner
935 | Just co_con <- newTyConCo_maybe tycon
936 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
940 -- When unwrapping, we do *not* apply any family coercion, because this will
941 -- be done via a CoPat by the type checker. We have to do it this way as
942 -- computing the right type arguments for the coercion requires more than just
943 -- a spliting operation (cf, TcPat.tcConPat).
945 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
946 unwrapNewTypeBody tycon args result_expr
947 | Just co_con <- newTyConCo_maybe tycon
948 = mkCoerce (mkTyConApp co_con args) result_expr
952 -- If the type constructor is a representation type of a data instance, wrap
953 -- the expression into a cast adjusting the expression type, which is an
954 -- instance of the representation type, to the corresponding instance of the
955 -- family instance type.
956 -- See Note [Wrappers for data instance tycons]
957 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
958 wrapFamInstBody tycon args body
959 | Just co_con <- tyConFamilyCoercion_maybe tycon
960 = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
964 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
965 unwrapFamInstScrut tycon args scrut
966 | Just co_con <- tyConFamilyCoercion_maybe tycon
967 = mkCoerce (mkTyConApp co_con args) scrut
973 %************************************************************************
975 \subsection{Primitive operations}
977 %************************************************************************
980 mkPrimOpId :: PrimOp -> Id
984 (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
985 ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
986 name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
987 (mkPrimOpIdUnique (primOpTag prim_op))
989 id = mkGlobalId (PrimOpId prim_op) name ty info
992 `setSpecInfo` mkSpecInfo (primOpRules prim_op name)
994 `setAllStrictnessInfo` Just strict_sig
996 -- For each ccall we manufacture a separate CCallOpId, giving it
997 -- a fresh unique, a type that is correct for this particular ccall,
998 -- and a CCall structure that gives the correct details about calling
1001 -- The *name* of this Id is a local name whose OccName gives the full
1002 -- details of the ccall, type and all. This means that the interface
1003 -- file reader can reconstruct a suitable Id
1005 mkFCallId :: Unique -> ForeignCall -> Type -> Id
1006 mkFCallId uniq fcall ty
1007 = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
1008 -- A CCallOpId should have no free type variables;
1009 -- when doing substitutions won't substitute over it
1010 mkGlobalId (FCallId fcall) name ty info
1012 occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
1013 -- The "occurrence name" of a ccall is the full info about the
1014 -- ccall; it is encoded, but may have embedded spaces etc!
1016 name = mkFCallName uniq occ_str
1019 `setArityInfo` arity
1020 `setAllStrictnessInfo` Just strict_sig
1022 (_, tau) = tcSplitForAllTys ty
1023 (arg_tys, _) = tcSplitFunTys tau
1024 arity = length arg_tys
1025 strict_sig = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
1027 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
1028 -- except for the type:
1030 -- a plain HPC tick box has type (State# RealWorld)
1031 -- a breakpoint Id has type forall a.a
1033 -- The breakpoint Id will be applied to a list of arbitrary free variables,
1034 -- which is why it needs a polymorphic type.
1036 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
1037 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
1039 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
1040 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
1041 where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
1043 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info
1045 tickbox = TickBox mod ix
1046 occ_str = showSDoc (braces (ppr tickbox))
1047 name = mkTickBoxOpName uniq occ_str
1052 %************************************************************************
1054 \subsection{DictFuns and default methods}
1056 %************************************************************************
1058 Important notes about dict funs and default methods
1059 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1060 Dict funs and default methods are *not* ImplicitIds. Their definition
1061 involves user-written code, so we can't figure out their strictness etc
1062 based on fixed info, as we can for constructors and record selectors (say).
1064 We build them as LocalIds, but with External Names. This ensures that
1065 they are taken to account by free-variable finding and dependency
1066 analysis (e.g. CoreFVs.exprFreeVars).
1068 Why shouldn't they be bound as GlobalIds? Because, in particular, if
1069 they are globals, the specialiser floats dict uses above their defns,
1070 which prevents good simplifications happening. Also the strictness
1071 analyser treats a occurrence of a GlobalId as imported and assumes it
1072 contains strictness in its IdInfo, which isn't true if the thing is
1073 bound in the same module as the occurrence.
1075 It's OK for dfuns to be LocalIds, because we form the instance-env to
1076 pass on to the next module (md_insts) in CoreTidy, afer tidying
1077 and globalising the top-level Ids.
1079 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so
1080 that they aren't discarded by the occurrence analyser.
1083 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
1085 mkDictFunId :: Name -- Name to use for the dict fun;
1092 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
1093 = mkExportedLocalId dfun_name dfun_ty
1095 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
1097 {- 1 dec 99: disable the Mark Jones optimisation for the sake
1098 of compatibility with Hugs.
1099 See `types/InstEnv' for a discussion related to this.
1101 (class_tyvars, sc_theta, _, _) = classBigSig clas
1102 not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
1103 sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
1104 dfun_theta = case inst_decl_theta of
1105 [] -> [] -- If inst_decl_theta is empty, then we don't
1106 -- want to have any dict arguments, so that we can
1107 -- expose the constant methods.
1109 other -> nub (inst_decl_theta ++ filter not_const sc_theta')
1110 -- Otherwise we pass the superclass dictionaries to
1111 -- the dictionary function; the Mark Jones optimisation.
1113 -- NOTE the "nub". I got caught by this one:
1114 -- class Monad m => MonadT t m where ...
1115 -- instance Monad m => MonadT (EnvT env) m where ...
1116 -- Here, the inst_decl_theta has (Monad m); but so
1117 -- does the sc_theta'!
1119 -- NOTE the "not_const". I got caught by this one too:
1120 -- class Foo a => Baz a b where ...
1121 -- instance Wob b => Baz T b where..
1122 -- Now sc_theta' has Foo T
1127 %************************************************************************
1129 \subsection{Un-definable}
1131 %************************************************************************
1133 These Ids can't be defined in Haskell. They could be defined in
1134 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
1135 ensure that they were definitely, definitely inlined, because there is
1136 no curried identifier for them. That's what mkCompulsoryUnfolding
1137 does. If we had a way to get a compulsory unfolding from an interface
1138 file, we could do that, but we don't right now.
1140 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
1141 just gets expanded into a type coercion wherever it occurs. Hence we
1142 add it as a built-in Id with an unfolding here.
1144 The type variables we use here are "open" type variables: this means
1145 they can unify with both unlifted and lifted types. Hence we provide
1146 another gun with which to shoot yourself in the foot.
1149 mkWiredInIdName mod fs uniq id
1150 = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
1152 unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
1153 nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId
1154 seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId
1155 realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId
1156 lazyIdName = mkWiredInIdName gHC_BASE (fsLit "lazy") lazyIdKey lazyId
1158 errorName = mkWiredInIdName gHC_ERR (fsLit "error") errorIdKey eRROR_ID
1159 recSelErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recSelError") recSelErrorIdKey rEC_SEL_ERROR_ID
1160 runtimeErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "runtimeError") runtimeErrorIdKey rUNTIME_ERROR_ID
1161 irrefutPatErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
1162 recConErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recConError") recConErrorIdKey rEC_CON_ERROR_ID
1163 patErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "patError") patErrorIdKey pAT_ERROR_ID
1164 noMethodBindingErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "noMethodBindingError")
1165 noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
1166 nonExhaustiveGuardsErrorName
1167 = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "nonExhaustiveGuardsError")
1168 nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
1172 ------------------------------------------------
1173 -- unsafeCoerce# :: forall a b. a -> b
1175 = pcMiscPrelId unsafeCoerceName ty info
1177 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1180 ty = mkForAllTys [openAlphaTyVar,openBetaTyVar]
1181 (mkFunTy openAlphaTy openBetaTy)
1182 [x] = mkTemplateLocals [openAlphaTy]
1183 rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
1184 Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
1186 ------------------------------------------------
1188 -- nullAddr# :: Addr#
1189 -- The reason is is here is because we don't provide
1190 -- a way to write this literal in Haskell.
1191 nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info
1193 info = noCafIdInfo `setUnfoldingInfo`
1194 mkCompulsoryUnfolding (Lit nullAddrLit)
1196 ------------------------------------------------
1198 -- 'seq' is very special. See notes with
1199 -- See DsUtils.lhs Note [Desugaring seq (1)] and
1200 -- Note [Desugaring seq (2)] and
1201 -- Fixity is set in LoadIface.ghcPrimIface
1202 seqId = pcMiscPrelId seqName ty info
1204 info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1207 ty = mkForAllTys [alphaTyVar,openBetaTyVar]
1208 (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
1209 [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
1210 rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
1212 ------------------------------------------------
1214 -- lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
1215 -- Used to lazify pseq: pseq a b = a `seq` lazy b
1217 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1218 -- not from GHC.Base.hi. This is important, because the strictness
1219 -- analyser will spot it as strict!
1221 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapperpass
1222 -- (see WorkWrap.wwExpr)
1223 -- We could use inline phases to do this, but that would be vulnerable to changes in
1224 -- phase numbering....we must inline precisely after strictness analysis.
1225 lazyId = pcMiscPrelId lazyIdName ty info
1228 ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1230 lazyIdUnfolding :: CoreExpr -- Used to expand 'lazyId' after strictness anal
1231 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1233 [x] = mkTemplateLocals [openAlphaTy]
1236 @realWorld#@ used to be a magic literal, \tr{void#}. If things get
1237 nasty as-is, change it back to a literal (@Literal@).
1239 voidArgId is a Local Id used simply as an argument in functions
1240 where we just want an arg to avoid having a thunk of unlifted type.
1242 x = \ void :: State# RealWorld -> (# p, q #)
1244 This comes up in strictness analysis
1247 realWorldPrimId -- :: State# RealWorld
1248 = pcMiscPrelId realWorldName realWorldStatePrimTy
1249 (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1250 -- The evaldUnfolding makes it look that realWorld# is evaluated
1251 -- which in turn makes Simplify.interestingArg return True,
1252 -- which in turn makes INLINE things applied to realWorld# likely
1256 voidArgId -- :: State# RealWorld
1257 = mkSysLocal (fsLit "void") voidArgIdKey realWorldStatePrimTy
1261 %************************************************************************
1263 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1265 %************************************************************************
1267 GHC randomly injects these into the code.
1269 @patError@ is just a version of @error@ for pattern-matching
1270 failures. It knows various ``codes'' which expand to longer
1271 strings---this saves space!
1273 @absentErr@ is a thing we put in for ``absent'' arguments. They jolly
1274 well shouldn't be yanked on, but if one is, then you will get a
1275 friendly message from @absentErr@ (rather than a totally random
1278 @parError@ is a special version of @error@ which the compiler does
1279 not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
1280 templates, but we don't ever expect to generate code for it.
1284 :: Id -- Should be of type (forall a. Addr# -> a)
1285 -- where Addr# points to a UTF8 encoded string
1286 -> Type -- The type to instantiate 'a'
1287 -> String -- The string to print
1290 mkRuntimeErrorApp err_id res_ty err_msg
1291 = mkApps (Var err_id) [Type res_ty, err_string]
1293 err_string = Lit (mkMachString err_msg)
1295 rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
1296 rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
1297 iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
1298 rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
1299 pAT_ERROR_ID = mkRuntimeErrorId patErrorName
1300 nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
1301 nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1303 -- The runtime error Ids take a UTF8-encoded string as argument
1305 mkRuntimeErrorId :: Name -> Id
1306 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1308 runtimeErrorTy :: Type
1309 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1313 eRROR_ID = pc_bottoming_Id errorName errorTy
1316 errorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1317 -- Notice the openAlphaTyVar. It says that "error" can be applied
1318 -- to unboxed as well as boxed types. This is OK because it never
1319 -- returns, so the return type is irrelevant.
1323 %************************************************************************
1325 \subsection{Utilities}
1327 %************************************************************************
1330 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1331 pcMiscPrelId name ty info
1332 = mkVanillaGlobalWithInfo name ty info
1333 -- We lie and say the thing is imported; otherwise, we get into
1334 -- a mess with dependency analysis; e.g., core2stg may heave in
1335 -- random calls to GHCbase.unpackPS__. If GHCbase is the module
1336 -- being compiled, then it's just a matter of luck if the definition
1337 -- will be in "the right place" to be in scope.
1339 pc_bottoming_Id :: Name -> Type -> Id
1340 -- Function of arity 1, which diverges after being given one argument
1341 pc_bottoming_Id name ty
1342 = pcMiscPrelId name ty bottoming_info
1344 bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1346 -- Make arity and strictness agree
1348 -- Do *not* mark them as NoCafRefs, because they can indeed have
1349 -- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
1350 -- which has some CAFs
1351 -- In due course we may arrange that these error-y things are
1352 -- regarded by the GC as permanently live, in which case we
1353 -- can give them NoCaf info. As it is, any function that calls
1354 -- any pc_bottoming_Id will itself have CafRefs, which bloats
1357 strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1358 -- These "bottom" out, no matter what their arguments