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