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