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