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