Introduce coercions for data instance decls
[ghc-hetmet.git] / compiler / basicTypes / MkId.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4 \section[StdIdInfo]{Standard unfoldings}
5
6 This module contains definitions for the IdInfo for things that
7 have a standard form, namely:
8
9         * data constructors
10         * record selectors
11         * method and superclass selectors
12         * primitive operations
13
14 \begin{code}
15 module MkId (
16         mkDictFunId, mkDefaultMethodId,
17         mkDictSelId, 
18
19         mkDataConIds,
20         mkRecordSelId, 
21         mkPrimOpId, mkFCallId,
22
23         mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
24         mkUnpackCase, mkProductBox,
25
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, 
30
31         mkRuntimeErrorApp,
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,
35
36         unsafeCoerceName
37     ) where
38
39 #include "HsVersions.h"
40
41
42 import BasicTypes       ( Arity, StrictnessMark(..), isMarkedUnboxed, isMarkedStrict )
43 import Rules            ( mkSpecInfo )
44 import TysPrim          ( openAlphaTyVars, alphaTyVar, alphaTy, 
45                           realWorldStatePrimTy, addrPrimTy
46                         )
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
59                         )
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, isFamInstTyCon,
66                           tyConFamInst_maybe, newTyConCo ) 
67 import Class            ( Class, classTyCon, classSelIds )
68 import Var              ( Id, TyVar, Var, setIdType )
69 import VarSet           ( isEmptyVarSet, subVarSet, varSetElems )
70 import Name             ( mkFCallName, mkWiredInName, Name, BuiltInSyntax(..))
71 import OccName          ( mkOccNameFS, varName )
72 import PrimOp           ( PrimOp, primOpSig, primOpOcc, primOpTag )
73 import ForeignCall      ( ForeignCall )
74 import DataCon          ( DataCon, DataConIds(..), dataConTyCon,
75                           dataConUnivTyVars, 
76                           dataConFieldLabels, dataConRepArity, dataConResTys,
77                           dataConRepArgTys, dataConRepType, dataConFullSig,
78                           dataConStrictMarks, dataConExStricts, 
79                           splitProductType, isVanillaDataCon, dataConFieldType,
80                           deepSplitProductType, 
81                         )
82 import Id               ( idType, mkGlobalId, mkVanillaGlobal, mkSysLocal, 
83                           mkTemplateLocals, mkTemplateLocalsNum, mkExportedLocalId,
84                           mkTemplateLocal, idName
85                         )
86 import IdInfo           ( IdInfo, noCafIdInfo,  setUnfoldingInfo, 
87                           setArityInfo, setSpecInfo, setCafInfo,
88                           setAllStrictnessInfo, vanillaIdInfo,
89                           GlobalIdDetails(..), CafInfo(..)
90                         )
91 import NewDemand        ( mkStrictSig, DmdResult(..),
92                           mkTopDmdType, topDmd, evalDmd, lazyDmd, retCPR,
93                           Demand(..), Demands(..) )
94 import DmdAnal          ( dmdAnalTopRhs )
95 import CoreSyn
96 import Unique           ( mkBuiltinUnique, mkPrimOpIdUnique )
97 import Maybe            ( fromJust )
98 import Maybes
99 import PrelNames
100 import Util             ( dropList, isSingleton )
101 import Outputable
102 import FastString
103 import ListSetOps       ( assoc, minusList )
104 \end{code}              
105
106 %************************************************************************
107 %*                                                                      *
108 \subsection{Wired in Ids}
109 %*                                                                      *
110 %************************************************************************
111
112 \begin{code}
113 wiredInIds
114   = [   -- These error-y things are wired in because we don't yet have
115         -- a way to express in an interface file that the result type variable
116         -- is 'open'; that is can be unified with an unboxed type
117         -- 
118         -- [The interface file format now carry such information, but there's
119         -- no way yet of expressing at the definition site for these 
120         -- error-reporting functions that they have an 'open' 
121         -- result type. -- sof 1/99]
122
123     eRROR_ID,   -- This one isn't used anywhere else in the compiler
124                 -- But we still need it in wiredInIds so that when GHC
125                 -- compiles a program that mentions 'error' we don't
126                 -- import its type from the interface file; we just get
127                 -- the Id defined here.  Which has an 'open-tyvar' type.
128
129     rUNTIME_ERROR_ID,
130     iRREFUT_PAT_ERROR_ID,
131     nON_EXHAUSTIVE_GUARDS_ERROR_ID,
132     nO_METHOD_BINDING_ERROR_ID,
133     pAT_ERROR_ID,
134     rEC_CON_ERROR_ID,
135
136     lazyId
137     ] ++ ghcPrimIds
138
139 -- These Ids are exported from GHC.Prim
140 ghcPrimIds
141   = [   -- These can't be defined in Haskell, but they have
142         -- perfectly reasonable unfoldings in Core
143     realWorldPrimId,
144     unsafeCoerceId,
145     nullAddrId,
146     seqId
147     ]
148 \end{code}
149
150 %************************************************************************
151 %*                                                                      *
152 \subsection{Data constructors}
153 %*                                                                      *
154 %************************************************************************
155
156 The wrapper for a constructor is an ordinary top-level binding that evaluates
157 any strict args, unboxes any args that are going to be flattened, and calls
158 the worker.
159
160 We're going to build a constructor that looks like:
161
162         data (Data a, C b) =>  T a b = T1 !a !Int b
163
164         T1 = /\ a b -> 
165              \d1::Data a, d2::C b ->
166              \p q r -> case p of { p ->
167                        case q of { q ->
168                        Con T1 [a,b] [p,q,r]}}
169
170 Notice that
171
172 * d2 is thrown away --- a context in a data decl is used to make sure
173   one *could* construct dictionaries at the site the constructor
174   is used, but the dictionary isn't actually used.
175
176 * We have to check that we can construct Data dictionaries for
177   the types a and Int.  Once we've done that we can throw d1 away too.
178
179 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
180   all that matters is that the arguments are evaluated.  "seq" is 
181   very careful to preserve evaluation order, which we don't need
182   to be here.
183
184   You might think that we could simply give constructors some strictness
185   info, like PrimOps, and let CoreToStg do the let-to-case transformation.
186   But we don't do that because in the case of primops and functions strictness
187   is a *property* not a *requirement*.  In the case of constructors we need to
188   do something active to evaluate the argument.
189
190   Making an explicit case expression allows the simplifier to eliminate
191   it in the (common) case where the constructor arg is already evaluated.
192
193 In the case of data instances, the wrapper also applies the coercion turning
194 the representation type into the family instance type to cast the result of
195 the wrapper.
196
197 \begin{code}
198 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
199 mkDataConIds wrap_name wkr_name data_con
200   | isNewTyCon tycon
201   = DCIds Nothing nt_work_id                    -- Newtype, only has a worker
202
203   | any isMarkedStrict all_strict_marks         -- Algebraic, needs wrapper
204     || not (null eq_spec)
205     || isFamInstTyCon tycon
206   = DCIds (Just alg_wrap_id) wrk_id
207
208   | otherwise                                   -- Algebraic, no wrapper
209   = DCIds Nothing wrk_id
210   where
211     (univ_tvs, ex_tvs, eq_spec, 
212      theta, orig_arg_tys)          = dataConFullSig data_con
213     tycon                          = dataConTyCon data_con
214
215         ----------- Wrapper --------------
216         -- We used to include the stupid theta in the wrapper's args
217         -- but now we don't.  Instead the type checker just injects these
218         -- extra constraints where necessary.
219     wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
220     subst          = mkTopTvSubst eq_spec
221     dict_tys       = mkPredTys theta
222     result_ty_args = map (substTyVar subst) univ_tvs
223     result_ty      = case tyConFamInst_maybe tycon of
224                          -- ordinary constructor
225                        Nothing            -> mkTyConApp tycon result_ty_args
226                          -- family instance constructor
227                        Just (familyTyCon, 
228                              instTys)     -> 
229                          mkTyConApp familyTyCon (map (substTy subst) instTys)
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
234
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
240
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,
246                                                         -- even if arity = 0
247
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.
258         --
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.
264
265     cpr_info | isProductTyCon tycon && 
266                isDataTyCon tycon    &&
267                wkr_arity > 0        &&
268                wkr_arity <= mAX_CPR_SIZE        = retCPR
269              | otherwise                        = TopRes
270         -- RetCPR is only true for products that are real data types;
271         -- that is, not unboxed tuples or [non-recursive] newtypes
272
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
285                        (Var id_arg1)
286
287     id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
288
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
297
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.
307         -- For example:
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
311
312     alg_unf = mkTopUnfolding $ Note InlineMe $
313               mkLams wrap_tvs $ 
314               mkLams dict_args $ mkLams id_args $
315               foldr mk_case con_app 
316                     (zip (dict_args ++ id_args) all_strict_marks)
317                     i3 []
318
319     con_app _ rep_ids = wrapFamInstBody tycon result_ty_args $
320                           Var wrk_id `mkTyApps`  result_ty_args
321                                      `mkVarApps` ex_tvs
322                                      `mkTyApps`  map snd eq_spec
323                                      `mkVarApps` reverse rep_ids
324
325     (dict_args,i2) = mkLocals 1  dict_tys
326     (id_args,i3)   = mkLocals i2 orig_arg_tys
327     alg_arity      = i3-1
328
329     mk_case 
330            :: (Id, StrictnessMark)      -- Arg, strictness
331            -> (Int -> [Id] -> CoreExpr) -- Body
332            -> Int                       -- Next rep arg id
333            -> [Id]                      -- Rep args so far, reversed
334            -> CoreExpr
335     mk_case (arg,strict) body i rep_args
336           = case strict of
337                 NotMarkedStrict -> body i (arg:rep_args)
338                 MarkedStrict 
339                    | isUnLiftedType (idType arg) -> body i (arg:rep_args)
340                    | otherwise ->
341                         Case (Var arg) arg result_ty [(DEFAULT,[], body i (arg:rep_args))]
342
343                 MarkedUnboxed
344                    -> unboxProduct i (Var arg) (idType arg) the_body 
345                       where
346                         the_body i con_args = body i (reverse con_args ++ rep_args)
347
348 mAX_CPR_SIZE :: Arity
349 mAX_CPR_SIZE = 10
350 -- We do not treat very big tuples as CPR-ish:
351 --      a) for a start we get into trouble because there aren't 
352 --         "enough" unboxed tuple types (a tiresome restriction, 
353 --         but hard to fix), 
354 --      b) more importantly, big unboxed tuples get returned mainly
355 --         on the stack, and are often then allocated in the heap
356 --         by the caller.  So doing CPR for them may in fact make
357 --         things worse.
358
359 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
360                where
361                  n = length tys
362
363 -- If the type constructor is a representation type of a data instance, wrap
364 -- the expression into a cast adjusting the expression type, which is an
365 -- instance of the representation type, to the corresponding instance of the
366 -- family instance type.
367 --
368 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
369 wrapFamInstBody tycon args result_expr
370   | Just (co_con, _) <- tyConFamInst_maybe tycon
371   = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
372   | otherwise
373   = result_expr
374
375 \end{code}
376
377
378 %************************************************************************
379 %*                                                                      *
380 \subsection{Record selectors}
381 %*                                                                      *
382 %************************************************************************
383
384 We're going to build a record selector unfolding that looks like this:
385
386         data T a b c = T1 { ..., op :: a, ...}
387                      | T2 { ..., op :: a, ...}
388                      | T3
389
390         sel = /\ a b c -> \ d -> case d of
391                                     T1 ... x ... -> x
392                                     T2 ... x ... -> x
393                                     other        -> error "..."
394
395 Similarly for newtypes
396
397         newtype N a = MkN { unN :: a->a }
398
399         unN :: N a -> a -> a
400         unN n = coerce (a->a) n
401         
402 We need to take a little care if the field has a polymorphic type:
403
404         data R = R { f :: forall a. a->a }
405
406 Then we want
407
408         f :: forall a. R -> a -> a
409         f = /\ a \ r = case r of
410                           R f -> f a
411
412 (not f :: R -> forall a. a->a, which gives the type inference mechanism 
413 problems at call sites)
414
415 Similarly for (recursive) newtypes
416
417         newtype N = MkN { unN :: forall a. a->a }
418
419         unN :: forall b. N -> b -> b
420         unN = /\b -> \n:N -> (coerce (forall a. a->a) n)
421
422
423 Note [Naughty record selectors]
424 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
425 A "naughty" field is one for which we can't define a record 
426 selector, because an existential type variable would escape.  For example:
427         data T = forall a. MkT { x,y::a }
428 We obviously can't define       
429         x (MkT v _) = v
430 Nevertheless we *do* put a RecordSelId into the type environment
431 so that if the user tries to use 'x' as a selector we can bleat
432 helpfully, rather than saying unhelpfully that 'x' is not in scope.
433 Hence the sel_naughty flag, to identify record selectors that don't really exist.
434
435 In general, a field is naughty if its type mentions a type variable that
436 isn't in the result type of the constructor.
437
438 Note [GADT record selectors]
439 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
440 For GADTs, we require that all constructors with a common field 'f' have the same
441 result type (modulo alpha conversion).  [Checked in TcTyClsDecls.checkValidTyCon]
442 E.g. 
443         data T where
444           T1 { f :: a } :: T [a]
445           T2 { f :: a, y :: b  } :: T [a]
446 and now the selector takes that type as its argument:
447         f :: forall a. T [a] -> a
448         f t = case t of
449                 T1 { f = v } -> v
450                 T2 { f = v } -> v
451 Note the forall'd tyvars of the selector are just the free tyvars
452 of the result type; there may be other tyvars in the constructor's
453 type (e.g. 'b' in T2).
454
455 \begin{code}
456
457 -- Steps for handling "naughty" vs "non-naughty" selectors:
458 --  1. Determine naughtiness by comparing field type vs result type
459 --  2. Install naughty ones with selector_ty of type _|_ and fill in mzero for info
460 --  3. If it's not naughty, do the normal plan.
461
462 mkRecordSelId :: TyCon -> FieldLabel -> Id
463 mkRecordSelId tycon field_label
464         -- Assumes that all fields with the same field label have the same type
465   | is_naughty = naughty_id
466   | otherwise  = sel_id
467   where
468     is_naughty = not (tyVarsOfType field_ty `subVarSet` res_tv_set)
469     sel_id_details = RecordSelId tycon field_label is_naughty
470
471     -- Escapist case here for naughty construcotrs
472     -- We give it no IdInfo, and a type of forall a.a (never looked at)
473     naughty_id = mkGlobalId sel_id_details field_label forall_a_a noCafIdInfo
474     forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
475
476     -- Normal case starts here
477     sel_id = mkGlobalId sel_id_details field_label selector_ty info
478     data_cons         = tyConDataCons tycon     
479     data_cons_w_field = filter has_field data_cons      -- Can't be empty!
480     has_field con     = field_label `elem` dataConFieldLabels con
481
482     con1        = head data_cons_w_field
483     res_tys     = dataConResTys con1
484     res_tv_set  = tyVarsOfTypes res_tys
485     res_tvs     = varSetElems res_tv_set
486     data_ty     = mkTyConApp tycon res_tys
487     field_ty    = dataConFieldType con1 field_label
488     
489         -- *Very* tiresomely, the selectors are (unnecessarily!) overloaded over
490         -- just the dictionaries in the types of the constructors that contain
491         -- the relevant field.  [The Report says that pattern matching on a
492         -- constructor gives the same constraints as applying it.]  Urgh.  
493         --
494         -- However, not all data cons have all constraints (because of
495         -- BuildTyCl.mkDataConStupidTheta).  So we need to find all the data cons 
496         -- involved in the pattern match and take the union of their constraints.
497     stupid_dict_tys = mkPredTys (dataConsStupidTheta data_cons_w_field)
498     n_stupid_dicts  = length stupid_dict_tys
499
500     (field_tyvars,pre_field_theta,field_tau) = tcSplitSigmaTy field_ty
501   
502     field_theta  = filter (not . isEqPred) pre_field_theta
503     field_dict_tys                       = mkPredTys field_theta
504     n_field_dict_tys                     = length field_dict_tys
505         -- If the field has a universally quantified type we have to 
506         -- be a bit careful.  Suppose we have
507         --      data R = R { op :: forall a. Foo a => a -> a }
508         -- Then we can't give op the type
509         --      op :: R -> forall a. Foo a => a -> a
510         -- because the typechecker doesn't understand foralls to the
511         -- right of an arrow.  The "right" type to give it is
512         --      op :: forall a. Foo a => R -> a -> a
513         -- But then we must generate the right unfolding too:
514         --      op = /\a -> \dfoo -> \ r ->
515         --           case r of
516         --              R op -> op a dfoo
517         -- Note that this is exactly the type we'd infer from a user defn
518         --      op (R op) = op
519
520     selector_ty :: Type
521     selector_ty  = mkForAllTys res_tvs $ mkForAllTys field_tyvars $
522                    mkFunTys stupid_dict_tys  $  mkFunTys field_dict_tys $
523                    mkFunTy data_ty field_tau
524       
525     arity = 1 + n_stupid_dicts + n_field_dict_tys
526
527     (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
528         -- Use the demand analyser to work out strictness.
529         -- With all this unpackery it's not easy!
530
531     info = noCafIdInfo
532            `setCafInfo`           caf_info
533            `setArityInfo`         arity
534            `setUnfoldingInfo`     mkTopUnfolding rhs_w_str
535            `setAllStrictnessInfo` Just strict_sig
536
537         -- Allocate Ids.  We do it a funny way round because field_dict_tys is
538         -- almost always empty.  Also note that we use max_dict_tys
539         -- rather than n_dict_tys, because the latter gives an infinite loop:
540         -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
541         -- on arity, which depends on n_dict tys.  Sigh!  Mega sigh!
542     stupid_dict_ids  = mkTemplateLocalsNum 1 stupid_dict_tys
543     max_stupid_dicts = length (tyConStupidTheta tycon)
544     field_dict_base  = max_stupid_dicts + 1
545     field_dict_ids   = mkTemplateLocalsNum field_dict_base field_dict_tys
546     dict_id_base     = field_dict_base + n_field_dict_tys
547     data_id          = mkTemplateLocal dict_id_base data_ty
548     arg_base         = dict_id_base + 1
549
550     the_alts :: [CoreAlt]
551     the_alts   = map mk_alt data_cons_w_field   -- Already sorted by data-con
552     no_default = length data_cons == length data_cons_w_field   -- No default needed
553
554     default_alt | no_default = []
555                 | otherwise  = [(DEFAULT, [], error_expr)]
556
557         -- The default branch may have CAF refs, because it calls recSelError etc.
558     caf_info    | no_default = NoCafRefs
559                 | otherwise  = MayHaveCafRefs
560
561     sel_rhs = mkLams res_tvs $ mkLams field_tyvars $ 
562               mkLams stupid_dict_ids $ mkLams field_dict_ids $
563               Lam data_id     $ mk_result sel_body
564
565         -- NB: A newtype always has a vanilla DataCon; no existentials etc
566         --     res_tys will simply be the dataConUnivTyVars
567     sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon res_tys (Var data_id)
568              | otherwise        = Case (Var data_id) data_id field_ty (default_alt ++ the_alts)
569
570     mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
571         -- We pull the field lambdas to the top, so we need to 
572         -- apply them in the body.  For example:
573         --      data T = MkT { foo :: forall a. a->a }
574         --
575         --      foo :: forall a. T -> a -> a
576         --      foo = /\a. \t:T. case t of { MkT f -> f a }
577
578     mk_alt data_con 
579       =   ASSERT2( res_ty `tcEqType` field_ty, ppr data_con $$ ppr res_ty $$ ppr field_ty )
580           mkReboxingAlt rebox_uniqs data_con (ex_tvs ++ co_tvs ++ arg_vs) rhs
581       where
582            -- get pattern binders with types appropriately instantiated
583         arg_uniqs = map mkBuiltinUnique [arg_base..]
584         (ex_tvs, co_tvs, arg_vs) = dataConOrigInstPat arg_uniqs data_con res_tys
585
586         rebox_base  = arg_base + length ex_tvs + length co_tvs + length arg_vs
587         rebox_uniqs = map mkBuiltinUnique [rebox_base..]
588
589         -- data T :: *->* where T1 { fld :: Maybe b } -> T [b]
590         --      Hence T1 :: forall a b. (a=[b]) => b -> T a
591         -- fld :: forall b. T [b] -> Maybe b
592         -- fld = /\b.\(t:T[b]). case t of 
593         --              T1 b' (c : [b]=[b']) (x:Maybe b') 
594         --                      -> x `cast` Maybe (sym (right c))
595
596         Succeeded refinement = gadtRefine emptyRefinement ex_tvs co_tvs
597         (co_fn, res_ty) = refineType refinement (idType the_arg_id)
598                 -- Generate the refinement for b'=b, 
599                 -- and apply to (Maybe b'), to get (Maybe b)
600
601         rhs = case co_fn of
602                 ExprCoFn co -> Cast (Var the_arg_id) co
603                 id_co       -> ASSERT(isIdCoercion id_co) Var the_arg_id
604
605         field_vs    = filter (not . isPredTy . idType) arg_vs 
606         the_arg_id  = assoc "mkRecordSelId:mk_alt" (field_lbls `zip` field_vs) field_label
607         field_lbls  = dataConFieldLabels data_con
608
609     error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_ty full_msg
610     full_msg   = showSDoc (sep [text "No match in record selector", ppr sel_id])
611
612 -- unbox a product type...
613 -- we will recurse into newtypes, casting along the way, and unbox at the
614 -- first product data constructor we find. e.g.
615 --  
616 --   data PairInt = PairInt Int Int
617 --   newtype S = MkS PairInt
618 --   newtype T = MkT S
619 --
620 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
621 -- ids, we get (modulo int passing)
622 --
623 --   case (e `cast` CoT) `cast` CoS of
624 --     PairInt a b -> body [a,b]
625 --
626 -- The Ints passed around are just for creating fresh locals
627 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
628 unboxProduct i arg arg_ty body
629   = result
630   where 
631     result = mkUnpackCase the_id arg con_args boxing_con rhs
632     (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
633     ([the_id], i') = mkLocals i [arg_ty]
634     (con_args, i'') = mkLocals i' tys
635     rhs = body i'' con_args
636
637 mkUnpackCase ::  Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
638 -- (mkUnpackCase x e args Con body)
639 --      returns
640 -- case (e `cast` ...) of bndr { Con args -> body }
641 -- 
642 -- the type of the bndr passed in is irrelevent
643 mkUnpackCase bndr arg unpk_args boxing_con body
644   = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
645   where
646   (cast_arg, bndr_ty) = go (idType bndr) arg
647   go ty arg 
648     | (tycon, tycon_args, _, _)  <- splitProductType "mkUnpackCase" ty
649     , isNewTyCon tycon && not (isRecursiveTyCon tycon)
650     = go (newTyConInstRhs tycon tycon_args) 
651          (unwrapNewTypeBody tycon tycon_args arg)
652     | otherwise = (arg, ty)
653
654 -- ...and the dual
655 reboxProduct :: [Unique]     -- uniques to create new local binders
656              -> Type         -- type of product to box
657              -> ([Unique],   -- remaining uniques
658                  CoreExpr,   -- boxed product
659                  [Id])       -- Ids being boxed into product
660 reboxProduct us ty
661   = let 
662         (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
663  
664         us' = dropList con_arg_tys us
665
666         arg_ids  = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
667
668         bind_rhs = mkProductBox arg_ids ty
669
670     in
671       (us', bind_rhs, arg_ids)
672
673 mkProductBox :: [Id] -> Type -> CoreExpr
674 mkProductBox arg_ids ty 
675   = result_expr
676   where 
677     (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
678
679     result_expr
680       | isNewTyCon tycon && not (isRecursiveTyCon tycon) 
681       = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
682       | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
683
684     wrap expr = wrapNewTypeBody tycon tycon_args expr
685
686
687 -- (mkReboxingAlt us con xs rhs) basically constructs the case
688 -- alternative  (con, xs, rhs)
689 -- but it does the reboxing necessary to construct the *source* 
690 -- arguments, xs, from the representation arguments ys.
691 -- For example:
692 --      data T = MkT !(Int,Int) Bool
693 --
694 -- mkReboxingAlt MkT [x,b] r 
695 --      = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
696 --
697 -- mkDataAlt should really be in DataCon, but it can't because
698 -- it manipulates CoreSyn.
699
700 mkReboxingAlt
701   :: [Unique]           -- Uniques for the new Ids
702   -> DataCon
703   -> [Var]              -- Source-level args, including existential dicts
704   -> CoreExpr           -- RHS
705   -> CoreAlt
706
707 mkReboxingAlt us con args rhs
708   | not (any isMarkedUnboxed stricts)
709   = (DataAlt con, args, rhs)
710
711   | otherwise
712   = let
713         (binds, args') = go args stricts us
714     in
715     (DataAlt con, args', mkLets binds rhs)
716
717   where
718     stricts = dataConExStricts con ++ dataConStrictMarks con
719
720     go [] _stricts _us = ([], [])
721
722         -- Type variable case
723     go (arg:args) stricts us 
724       | isTyVar arg
725       = let (binds, args') = go args stricts us
726         in  (binds, arg:args')
727
728         -- Term variable case
729     go (arg:args) (str:stricts) us
730       | isMarkedUnboxed str
731       = 
732         let (binds, unpacked_args')        = go args stricts us'
733             (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
734         in
735             (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
736       | otherwise
737       = let (binds, args') = go args stricts us
738         in  (binds, arg:args')
739 \end{code}
740
741
742 %************************************************************************
743 %*                                                                      *
744 \subsection{Dictionary selectors}
745 %*                                                                      *
746 %************************************************************************
747
748 Selecting a field for a dictionary.  If there is just one field, then
749 there's nothing to do.  
750
751 Dictionary selectors may get nested forall-types.  Thus:
752
753         class Foo a where
754           op :: forall b. Ord b => a -> b -> b
755
756 Then the top-level type for op is
757
758         op :: forall a. Foo a => 
759               forall b. Ord b => 
760               a -> b -> b
761
762 This is unlike ordinary record selectors, which have all the for-alls
763 at the outside.  When dealing with classes it's very convenient to
764 recover the original type signature from the class op selector.
765
766 \begin{code}
767 mkDictSelId :: Name -> Class -> Id
768 mkDictSelId name clas
769   = mkGlobalId (ClassOpId clas) name sel_ty info
770   where
771     sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
772         -- We can't just say (exprType rhs), because that would give a type
773         --      C a -> C a
774         -- for a single-op class (after all, the selector is the identity)
775         -- But it's type must expose the representation of the dictionary
776         -- to gat (say)         C a -> (a -> a)
777
778     info = noCafIdInfo
779                 `setArityInfo`          1
780                 `setUnfoldingInfo`      mkTopUnfolding rhs
781                 `setAllStrictnessInfo`  Just strict_sig
782
783         -- We no longer use 'must-inline' on record selectors.  They'll
784         -- inline like crazy if they scrutinise a constructor
785
786         -- The strictness signature is of the form U(AAAVAAAA) -> T
787         -- where the V depends on which item we are selecting
788         -- It's worth giving one, so that absence info etc is generated
789         -- even if the selector isn't inlined
790     strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
791     arg_dmd | isNewTyCon tycon = evalDmd
792             | otherwise        = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
793                                             | id <- arg_ids ])
794
795     tycon      = classTyCon clas
796     [data_con] = tyConDataCons tycon
797     tyvars     = dataConUnivTyVars data_con
798     arg_tys    = ASSERT( isVanillaDataCon data_con ) dataConRepArgTys data_con
799     the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
800
801     pred              = mkClassPred clas (mkTyVarTys tyvars)
802     (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
803
804     rhs = mkLams tyvars (Lam dict_id rhs_body)
805     rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
806              | otherwise        = Case (Var dict_id) dict_id (idType the_arg_id)
807                                        [(DataAlt data_con, arg_ids, Var the_arg_id)]
808
809 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
810 -- The wrapper for the data constructor for a newtype looks like this:
811 --      newtype T a = MkT (a,Int)
812 --      MkT :: forall a. (a,Int) -> T a
813 --      MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
814 -- where CoT is the coercion TyCon assoicated with the newtype
815 --
816 -- The call (wrapNewTypeBody T [a] e) returns the
817 -- body of the wrapper, namely
818 --      e `cast` (CoT [a])
819 --
820 -- If a coercion constructor is prodivided in the newtype, then we use
821 -- it, otherwise the wrap/unwrap are both no-ops 
822 --
823 wrapNewTypeBody tycon args result_expr
824   | Just co_con <- newTyConCo tycon
825   = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
826   | otherwise
827   = result_expr
828
829 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
830 unwrapNewTypeBody tycon args result_expr
831   | Just co_con <- newTyConCo tycon
832   = mkCoerce (mkTyConApp co_con args) result_expr
833   | otherwise
834   = result_expr
835
836
837 \end{code}
838
839
840 %************************************************************************
841 %*                                                                      *
842 \subsection{Primitive operations
843 %*                                                                      *
844 %************************************************************************
845
846 \begin{code}
847 mkPrimOpId :: PrimOp -> Id
848 mkPrimOpId prim_op 
849   = id
850   where
851     (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
852     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
853     name = mkWiredInName gHC_PRIM (primOpOcc prim_op) 
854                          (mkPrimOpIdUnique (primOpTag prim_op))
855                          Nothing (AnId id) UserSyntax
856     id   = mkGlobalId (PrimOpId prim_op) name ty info
857                 
858     info = noCafIdInfo
859            `setSpecInfo`          mkSpecInfo (primOpRules prim_op name)
860            `setArityInfo`         arity
861            `setAllStrictnessInfo` Just strict_sig
862
863 -- For each ccall we manufacture a separate CCallOpId, giving it
864 -- a fresh unique, a type that is correct for this particular ccall,
865 -- and a CCall structure that gives the correct details about calling
866 -- convention etc.  
867 --
868 -- The *name* of this Id is a local name whose OccName gives the full
869 -- details of the ccall, type and all.  This means that the interface 
870 -- file reader can reconstruct a suitable Id
871
872 mkFCallId :: Unique -> ForeignCall -> Type -> Id
873 mkFCallId uniq fcall ty
874   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
875         -- A CCallOpId should have no free type variables; 
876         -- when doing substitutions won't substitute over it
877     mkGlobalId (FCallId fcall) name ty info
878   where
879     occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
880         -- The "occurrence name" of a ccall is the full info about the
881         -- ccall; it is encoded, but may have embedded spaces etc!
882
883     name = mkFCallName uniq occ_str
884
885     info = noCafIdInfo
886            `setArityInfo`               arity
887            `setAllStrictnessInfo`       Just strict_sig
888
889     (_, tau)     = tcSplitForAllTys ty
890     (arg_tys, _) = tcSplitFunTys tau
891     arity        = length arg_tys
892     strict_sig   = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
893 \end{code}
894
895
896 %************************************************************************
897 %*                                                                      *
898 \subsection{DictFuns and default methods}
899 %*                                                                      *
900 %************************************************************************
901
902 Important notes about dict funs and default methods
903 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
904 Dict funs and default methods are *not* ImplicitIds.  Their definition
905 involves user-written code, so we can't figure out their strictness etc
906 based on fixed info, as we can for constructors and record selectors (say).
907
908 We build them as LocalIds, but with External Names.  This ensures that
909 they are taken to account by free-variable finding and dependency
910 analysis (e.g. CoreFVs.exprFreeVars).
911
912 Why shouldn't they be bound as GlobalIds?  Because, in particular, if
913 they are globals, the specialiser floats dict uses above their defns,
914 which prevents good simplifications happening.  Also the strictness
915 analyser treats a occurrence of a GlobalId as imported and assumes it
916 contains strictness in its IdInfo, which isn't true if the thing is
917 bound in the same module as the occurrence.
918
919 It's OK for dfuns to be LocalIds, because we form the instance-env to
920 pass on to the next module (md_insts) in CoreTidy, afer tidying
921 and globalising the top-level Ids.
922
923 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so 
924 that they aren't discarded by the occurrence analyser.
925
926 \begin{code}
927 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
928
929 mkDictFunId :: Name             -- Name to use for the dict fun;
930             -> [TyVar]
931             -> ThetaType
932             -> Class 
933             -> [Type]
934             -> Id
935
936 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
937   = mkExportedLocalId dfun_name dfun_ty
938   where
939     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
940
941 {-  1 dec 99: disable the Mark Jones optimisation for the sake
942     of compatibility with Hugs.
943     See `types/InstEnv' for a discussion related to this.
944
945     (class_tyvars, sc_theta, _, _) = classBigSig clas
946     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
947     sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
948     dfun_theta = case inst_decl_theta of
949                    []    -> []  -- If inst_decl_theta is empty, then we don't
950                                 -- want to have any dict arguments, so that we can
951                                 -- expose the constant methods.
952
953                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
954                                 -- Otherwise we pass the superclass dictionaries to
955                                 -- the dictionary function; the Mark Jones optimisation.
956                                 --
957                                 -- NOTE the "nub".  I got caught by this one:
958                                 --   class Monad m => MonadT t m where ...
959                                 --   instance Monad m => MonadT (EnvT env) m where ...
960                                 -- Here, the inst_decl_theta has (Monad m); but so
961                                 -- does the sc_theta'!
962                                 --
963                                 -- NOTE the "not_const".  I got caught by this one too:
964                                 --   class Foo a => Baz a b where ...
965                                 --   instance Wob b => Baz T b where..
966                                 -- Now sc_theta' has Foo T
967 -}
968 \end{code}
969
970
971 %************************************************************************
972 %*                                                                      *
973 \subsection{Un-definable}
974 %*                                                                      *
975 %************************************************************************
976
977 These Ids can't be defined in Haskell.  They could be defined in
978 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
979 ensure that they were definitely, definitely inlined, because there is
980 no curried identifier for them.  That's what mkCompulsoryUnfolding
981 does.  If we had a way to get a compulsory unfolding from an interface
982 file, we could do that, but we don't right now.
983
984 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
985 just gets expanded into a type coercion wherever it occurs.  Hence we
986 add it as a built-in Id with an unfolding here.
987
988 The type variables we use here are "open" type variables: this means
989 they can unify with both unlifted and lifted types.  Hence we provide
990 another gun with which to shoot yourself in the foot.
991
992 \begin{code}
993 mkWiredInIdName mod fs uniq id
994  = mkWiredInName mod (mkOccNameFS varName fs) uniq Nothing (AnId id) UserSyntax
995
996 unsafeCoerceName = mkWiredInIdName gHC_PRIM FSLIT("unsafeCoerce#") unsafeCoerceIdKey  unsafeCoerceId
997 nullAddrName     = mkWiredInIdName gHC_PRIM FSLIT("nullAddr#")     nullAddrIdKey      nullAddrId
998 seqName          = mkWiredInIdName gHC_PRIM FSLIT("seq")           seqIdKey           seqId
999 realWorldName    = mkWiredInIdName gHC_PRIM FSLIT("realWorld#")    realWorldPrimIdKey realWorldPrimId
1000 lazyIdName       = mkWiredInIdName gHC_BASE FSLIT("lazy")         lazyIdKey           lazyId
1001
1002 errorName                = mkWiredInIdName gHC_ERR FSLIT("error")            errorIdKey eRROR_ID
1003 recSelErrorName          = mkWiredInIdName gHC_ERR FSLIT("recSelError")     recSelErrorIdKey rEC_SEL_ERROR_ID
1004 runtimeErrorName         = mkWiredInIdName gHC_ERR FSLIT("runtimeError")    runtimeErrorIdKey rUNTIME_ERROR_ID
1005 irrefutPatErrorName      = mkWiredInIdName gHC_ERR FSLIT("irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
1006 recConErrorName          = mkWiredInIdName gHC_ERR FSLIT("recConError")     recConErrorIdKey rEC_CON_ERROR_ID
1007 patErrorName             = mkWiredInIdName gHC_ERR FSLIT("patError")         patErrorIdKey pAT_ERROR_ID
1008 noMethodBindingErrorName = mkWiredInIdName gHC_ERR FSLIT("noMethodBindingError")
1009                                            noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
1010 nonExhaustiveGuardsErrorName 
1011   = mkWiredInIdName gHC_ERR FSLIT("nonExhaustiveGuardsError") 
1012                     nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
1013 \end{code}
1014
1015 \begin{code}
1016 -- unsafeCoerce# :: forall a b. a -> b
1017 unsafeCoerceId
1018   = pcMiscPrelId unsafeCoerceName ty info
1019   where
1020     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1021            
1022
1023     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
1024                       (mkFunTy openAlphaTy openBetaTy)
1025     [x] = mkTemplateLocals [openAlphaTy]
1026     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
1027 --       Note (Coerce openBetaTy openAlphaTy) (Var x)
1028          Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
1029
1030 -- nullAddr# :: Addr#
1031 -- The reason is is here is because we don't provide 
1032 -- a way to write this literal in Haskell.
1033 nullAddrId 
1034   = pcMiscPrelId nullAddrName addrPrimTy info
1035   where
1036     info = noCafIdInfo `setUnfoldingInfo` 
1037            mkCompulsoryUnfolding (Lit nullAddrLit)
1038
1039 seqId
1040   = pcMiscPrelId seqName ty info
1041   where
1042     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1043            
1044
1045     ty  = mkForAllTys [alphaTyVar,openBetaTyVar]
1046                       (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
1047     [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
1048     rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
1049
1050 -- lazy :: forall a?. a? -> a?   (i.e. works for unboxed types too)
1051 -- Used to lazify pseq:         pseq a b = a `seq` lazy b
1052 -- 
1053 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1054 -- not from GHC.Base.hi.   This is important, because the strictness
1055 -- analyser will spot it as strict!
1056 --
1057 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapper pass
1058 --      (see WorkWrap.wwExpr)   
1059 -- We could use inline phases to do this, but that would be vulnerable to changes in 
1060 -- phase numbering....we must inline precisely after strictness analysis.
1061 lazyId
1062   = pcMiscPrelId lazyIdName ty info
1063   where
1064     info = noCafIdInfo
1065     ty  = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1066
1067 lazyIdUnfolding :: CoreExpr     -- Used to expand 'lazyId' after strictness anal
1068 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1069                 where
1070                   [x] = mkTemplateLocals [openAlphaTy]
1071 \end{code}
1072
1073 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
1074 nasty as-is, change it back to a literal (@Literal@).
1075
1076 voidArgId is a Local Id used simply as an argument in functions
1077 where we just want an arg to avoid having a thunk of unlifted type.
1078 E.g.
1079         x = \ void :: State# RealWorld -> (# p, q #)
1080
1081 This comes up in strictness analysis
1082
1083 \begin{code}
1084 realWorldPrimId -- :: State# RealWorld
1085   = pcMiscPrelId realWorldName realWorldStatePrimTy
1086                  (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1087         -- The evaldUnfolding makes it look that realWorld# is evaluated
1088         -- which in turn makes Simplify.interestingArg return True,
1089         -- which in turn makes INLINE things applied to realWorld# likely
1090         -- to be inlined
1091
1092 voidArgId       -- :: State# RealWorld
1093   = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
1094 \end{code}
1095
1096
1097 %************************************************************************
1098 %*                                                                      *
1099 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1100 %*                                                                      *
1101 %************************************************************************
1102
1103 GHC randomly injects these into the code.
1104
1105 @patError@ is just a version of @error@ for pattern-matching
1106 failures.  It knows various ``codes'' which expand to longer
1107 strings---this saves space!
1108
1109 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
1110 well shouldn't be yanked on, but if one is, then you will get a
1111 friendly message from @absentErr@ (rather than a totally random
1112 crash).
1113
1114 @parError@ is a special version of @error@ which the compiler does
1115 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
1116 templates, but we don't ever expect to generate code for it.
1117
1118 \begin{code}
1119 mkRuntimeErrorApp 
1120         :: Id           -- Should be of type (forall a. Addr# -> a)
1121                         --      where Addr# points to a UTF8 encoded string
1122         -> Type         -- The type to instantiate 'a'
1123         -> String       -- The string to print
1124         -> CoreExpr
1125
1126 mkRuntimeErrorApp err_id res_ty err_msg 
1127   = mkApps (Var err_id) [Type res_ty, err_string]
1128   where
1129     err_string = Lit (mkStringLit err_msg)
1130
1131 rEC_SEL_ERROR_ID                = mkRuntimeErrorId recSelErrorName
1132 rUNTIME_ERROR_ID                = mkRuntimeErrorId runtimeErrorName
1133 iRREFUT_PAT_ERROR_ID            = mkRuntimeErrorId irrefutPatErrorName
1134 rEC_CON_ERROR_ID                = mkRuntimeErrorId recConErrorName
1135 pAT_ERROR_ID                    = mkRuntimeErrorId patErrorName
1136 nO_METHOD_BINDING_ERROR_ID      = mkRuntimeErrorId noMethodBindingErrorName
1137 nON_EXHAUSTIVE_GUARDS_ERROR_ID  = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1138
1139 -- The runtime error Ids take a UTF8-encoded string as argument
1140 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1141 runtimeErrorTy        = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1142 \end{code}
1143
1144 \begin{code}
1145 eRROR_ID = pc_bottoming_Id errorName errorTy
1146
1147 errorTy  :: Type
1148 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1149     -- Notice the openAlphaTyVar.  It says that "error" can be applied
1150     -- to unboxed as well as boxed types.  This is OK because it never
1151     -- returns, so the return type is irrelevant.
1152 \end{code}
1153
1154
1155 %************************************************************************
1156 %*                                                                      *
1157 \subsection{Utilities}
1158 %*                                                                      *
1159 %************************************************************************
1160
1161 \begin{code}
1162 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1163 pcMiscPrelId name ty info
1164   = mkVanillaGlobal name ty info
1165     -- We lie and say the thing is imported; otherwise, we get into
1166     -- a mess with dependency analysis; e.g., core2stg may heave in
1167     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
1168     -- being compiled, then it's just a matter of luck if the definition
1169     -- will be in "the right place" to be in scope.
1170
1171 pc_bottoming_Id name ty
1172  = pcMiscPrelId name ty bottoming_info
1173  where
1174     bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1175         -- Do *not* mark them as NoCafRefs, because they can indeed have
1176         -- CAF refs.  For example, pAT_ERROR_ID calls GHC.Err.untangle,
1177         -- which has some CAFs
1178         -- In due course we may arrange that these error-y things are
1179         -- regarded by the GC as permanently live, in which case we
1180         -- can give them NoCaf info.  As it is, any function that calls
1181         -- any pc_bottoming_Id will itself have CafRefs, which bloats
1182         -- SRTs.
1183
1184     strict_sig     = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1185         -- These "bottom" out, no matter what their arguments
1186
1187 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
1188 openAlphaTy  = mkTyVarTy openAlphaTyVar
1189 openBetaTy   = mkTyVarTy openBetaTyVar
1190 \end{code}
1191