Comment
[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 x e args Con body)
591 --      returns
592 -- case (e `cast` ...) of bndr { Con args -> body }
593 mkUnpackCase bndr arg unpk_args boxing_con body
594   = Case cast_arg bndr (exprType body) [(DataAlt boxing_con, unpk_args, body)]
595   where
596   cast_arg = go (idType bndr) arg
597   go ty arg 
598     | res@(tycon, tycon_args, _, _)  <- splitProductType "mkUnpackCase" ty
599     , isNewTyCon tycon && not (isRecursiveTyCon tycon)
600     = go (newTyConInstRhs tycon tycon_args) 
601          (unwrapNewTypeBody tycon tycon_args arg)
602     | otherwise = arg
603
604 -- ...and the dual
605 reboxProduct :: [Unique]     -- uniques to create new local binders
606              -> Type         -- type of product to box
607              -> ([Unique],   -- remaining uniques
608                  CoreExpr,   -- boxed product
609                  [Id])       -- Ids being boxed into product
610 reboxProduct us ty
611   = let 
612         (tycon, tycon_args, pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
613  
614         us' = dropList con_arg_tys us
615
616         arg_ids  = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
617
618         bind_rhs = mkProductBox arg_ids ty
619
620     in
621       (us', bind_rhs, arg_ids)
622
623 mkProductBox :: [Id] -> Type -> CoreExpr
624 mkProductBox arg_ids ty 
625   = result_expr
626   where 
627     (tycon, tycon_args, pack_con, con_arg_tys) = splitProductType "mkProductBox" ty
628
629     result_expr
630       | isNewTyCon tycon 
631       = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
632       | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
633
634     wrap expr = wrapNewTypeBody tycon tycon_args expr
635
636
637 -- (mkReboxingAlt us con xs rhs) basically constructs the case
638 -- alternative  (con, xs, rhs)
639 -- but it does the reboxing necessary to construct the *source* 
640 -- arguments, xs, from the representation arguments ys.
641 -- For example:
642 --      data T = MkT !(Int,Int) Bool
643 --
644 -- mkReboxingAlt MkT [x,b] r 
645 --      = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
646 --
647 -- mkDataAlt should really be in DataCon, but it can't because
648 -- it manipulates CoreSyn.
649
650 mkReboxingAlt
651   :: [Unique]           -- Uniques for the new Ids
652   -> DataCon
653   -> [Var]              -- Source-level args, including existential dicts
654   -> CoreExpr           -- RHS
655   -> CoreAlt
656
657 mkReboxingAlt us con args rhs
658   | not (any isMarkedUnboxed stricts)
659   = (DataAlt con, args, rhs)
660
661   | otherwise
662   = let
663         (binds, args') = go args stricts us
664     in
665     (DataAlt con, args', mkLets binds rhs)
666
667   where
668     stricts = dataConExStricts con ++ dataConStrictMarks con
669
670     go [] stricts us = ([], [])
671
672         -- Type variable case
673     go (arg:args) stricts us 
674       | isTyVar arg
675       = let (binds, args') = go args stricts us
676         in  (binds, arg:args')
677
678         -- Term variable case
679     go (arg:args) (str:stricts) us
680       | isMarkedUnboxed str
681       = 
682         let (binds, unpacked_args')        = go args stricts us'
683             (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
684         in
685             (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
686       | otherwise
687       = let (binds, args') = go args stricts us
688         in  (binds, arg:args')
689 \end{code}
690
691
692 %************************************************************************
693 %*                                                                      *
694 \subsection{Dictionary selectors}
695 %*                                                                      *
696 %************************************************************************
697
698 Selecting a field for a dictionary.  If there is just one field, then
699 there's nothing to do.  
700
701 Dictionary selectors may get nested forall-types.  Thus:
702
703         class Foo a where
704           op :: forall b. Ord b => a -> b -> b
705
706 Then the top-level type for op is
707
708         op :: forall a. Foo a => 
709               forall b. Ord b => 
710               a -> b -> b
711
712 This is unlike ordinary record selectors, which have all the for-alls
713 at the outside.  When dealing with classes it's very convenient to
714 recover the original type signature from the class op selector.
715
716 \begin{code}
717 mkDictSelId :: Name -> Class -> Id
718 mkDictSelId name clas
719   = mkGlobalId (ClassOpId clas) name sel_ty info
720   where
721     sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
722         -- We can't just say (exprType rhs), because that would give a type
723         --      C a -> C a
724         -- for a single-op class (after all, the selector is the identity)
725         -- But it's type must expose the representation of the dictionary
726         -- to gat (say)         C a -> (a -> a)
727
728     info = noCafIdInfo
729                 `setArityInfo`          1
730                 `setUnfoldingInfo`      mkTopUnfolding rhs
731                 `setAllStrictnessInfo`  Just strict_sig
732
733         -- We no longer use 'must-inline' on record selectors.  They'll
734         -- inline like crazy if they scrutinise a constructor
735
736         -- The strictness signature is of the form U(AAAVAAAA) -> T
737         -- where the V depends on which item we are selecting
738         -- It's worth giving one, so that absence info etc is generated
739         -- even if the selector isn't inlined
740     strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
741     arg_dmd | isNewTyCon tycon = evalDmd
742             | otherwise        = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
743                                             | id <- arg_ids ])
744
745     tycon      = classTyCon clas
746     [data_con] = tyConDataCons tycon
747     tyvars     = dataConUnivTyVars data_con
748     arg_tys    = ASSERT( isVanillaDataCon data_con ) dataConRepArgTys data_con
749     the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
750
751     pred              = mkClassPred clas (mkTyVarTys tyvars)
752     (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
753
754     rhs = mkLams tyvars (Lam dict_id rhs_body)
755     rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
756              | otherwise        = Case (Var dict_id) dict_id (idType the_arg_id)
757                                        [(DataAlt data_con, arg_ids, Var the_arg_id)]
758
759 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
760 -- The wrapper for the data constructor for a newtype looks like this:
761 --      newtype T a = MkT (a,Int)
762 --      MkT :: forall a. (a,Int) -> T a
763 --      MkT = /\a. \(x:(a,Int)). x `cast` CoT a
764 -- where CoT is the coercion TyCon assoicated with the newtype
765 --
766 -- The call (wrapNewTypeBody T [a] e) returns the
767 -- body of the wrapper, namely
768 --      e `cast` CoT [a]
769 --
770 -- If a coercion constructor is prodivided in the newtype, then we use
771 -- it, otherwise the wrap/unwrap are both no-ops 
772 --
773 wrapNewTypeBody tycon args result_expr
774   | Just co_con <- newTyConCo tycon
775   = Cast result_expr (mkTyConApp co_con args)
776   | otherwise
777   = result_expr
778
779 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
780 unwrapNewTypeBody tycon args result_expr
781   | Just co_con <- newTyConCo tycon
782   = Cast result_expr (mkSymCoercion (mkTyConApp co_con args))
783   | otherwise
784   = result_expr
785
786
787 \end{code}
788
789
790 %************************************************************************
791 %*                                                                      *
792 \subsection{Primitive operations
793 %*                                                                      *
794 %************************************************************************
795
796 \begin{code}
797 mkPrimOpId :: PrimOp -> Id
798 mkPrimOpId prim_op 
799   = id
800   where
801     (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
802     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
803     name = mkWiredInName gHC_PRIM (primOpOcc prim_op) 
804                          (mkPrimOpIdUnique (primOpTag prim_op))
805                          Nothing (AnId id) UserSyntax
806     id   = mkGlobalId (PrimOpId prim_op) name ty info
807                 
808     info = noCafIdInfo
809            `setSpecInfo`          mkSpecInfo (primOpRules prim_op name)
810            `setArityInfo`         arity
811            `setAllStrictnessInfo` Just strict_sig
812
813 -- For each ccall we manufacture a separate CCallOpId, giving it
814 -- a fresh unique, a type that is correct for this particular ccall,
815 -- and a CCall structure that gives the correct details about calling
816 -- convention etc.  
817 --
818 -- The *name* of this Id is a local name whose OccName gives the full
819 -- details of the ccall, type and all.  This means that the interface 
820 -- file reader can reconstruct a suitable Id
821
822 mkFCallId :: Unique -> ForeignCall -> Type -> Id
823 mkFCallId uniq fcall ty
824   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
825         -- A CCallOpId should have no free type variables; 
826         -- when doing substitutions won't substitute over it
827     mkGlobalId (FCallId fcall) name ty info
828   where
829     occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
830         -- The "occurrence name" of a ccall is the full info about the
831         -- ccall; it is encoded, but may have embedded spaces etc!
832
833     name = mkFCallName uniq occ_str
834
835     info = noCafIdInfo
836            `setArityInfo`               arity
837            `setAllStrictnessInfo`       Just strict_sig
838
839     (_, tau)     = tcSplitForAllTys ty
840     (arg_tys, _) = tcSplitFunTys tau
841     arity        = length arg_tys
842     strict_sig   = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
843 \end{code}
844
845
846 %************************************************************************
847 %*                                                                      *
848 \subsection{DictFuns and default methods}
849 %*                                                                      *
850 %************************************************************************
851
852 Important notes about dict funs and default methods
853 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
854 Dict funs and default methods are *not* ImplicitIds.  Their definition
855 involves user-written code, so we can't figure out their strictness etc
856 based on fixed info, as we can for constructors and record selectors (say).
857
858 We build them as LocalIds, but with External Names.  This ensures that
859 they are taken to account by free-variable finding and dependency
860 analysis (e.g. CoreFVs.exprFreeVars).
861
862 Why shouldn't they be bound as GlobalIds?  Because, in particular, if
863 they are globals, the specialiser floats dict uses above their defns,
864 which prevents good simplifications happening.  Also the strictness
865 analyser treats a occurrence of a GlobalId as imported and assumes it
866 contains strictness in its IdInfo, which isn't true if the thing is
867 bound in the same module as the occurrence.
868
869 It's OK for dfuns to be LocalIds, because we form the instance-env to
870 pass on to the next module (md_insts) in CoreTidy, afer tidying
871 and globalising the top-level Ids.
872
873 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so 
874 that they aren't discarded by the occurrence analyser.
875
876 \begin{code}
877 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
878
879 mkDictFunId :: Name             -- Name to use for the dict fun;
880             -> [TyVar]
881             -> ThetaType
882             -> Class 
883             -> [Type]
884             -> Id
885
886 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
887   = mkExportedLocalId dfun_name dfun_ty
888   where
889     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
890
891 {-  1 dec 99: disable the Mark Jones optimisation for the sake
892     of compatibility with Hugs.
893     See `types/InstEnv' for a discussion related to this.
894
895     (class_tyvars, sc_theta, _, _) = classBigSig clas
896     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
897     sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
898     dfun_theta = case inst_decl_theta of
899                    []    -> []  -- If inst_decl_theta is empty, then we don't
900                                 -- want to have any dict arguments, so that we can
901                                 -- expose the constant methods.
902
903                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
904                                 -- Otherwise we pass the superclass dictionaries to
905                                 -- the dictionary function; the Mark Jones optimisation.
906                                 --
907                                 -- NOTE the "nub".  I got caught by this one:
908                                 --   class Monad m => MonadT t m where ...
909                                 --   instance Monad m => MonadT (EnvT env) m where ...
910                                 -- Here, the inst_decl_theta has (Monad m); but so
911                                 -- does the sc_theta'!
912                                 --
913                                 -- NOTE the "not_const".  I got caught by this one too:
914                                 --   class Foo a => Baz a b where ...
915                                 --   instance Wob b => Baz T b where..
916                                 -- Now sc_theta' has Foo T
917 -}
918 \end{code}
919
920
921 %************************************************************************
922 %*                                                                      *
923 \subsection{Un-definable}
924 %*                                                                      *
925 %************************************************************************
926
927 These Ids can't be defined in Haskell.  They could be defined in
928 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
929 ensure that they were definitely, definitely inlined, because there is
930 no curried identifier for them.  That's what mkCompulsoryUnfolding
931 does.  If we had a way to get a compulsory unfolding from an interface
932 file, we could do that, but we don't right now.
933
934 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
935 just gets expanded into a type coercion wherever it occurs.  Hence we
936 add it as a built-in Id with an unfolding here.
937
938 The type variables we use here are "open" type variables: this means
939 they can unify with both unlifted and lifted types.  Hence we provide
940 another gun with which to shoot yourself in the foot.
941
942 \begin{code}
943 mkWiredInIdName mod fs uniq id
944  = mkWiredInName mod (mkOccNameFS varName fs) uniq Nothing (AnId id) UserSyntax
945
946 unsafeCoerceName = mkWiredInIdName gHC_PRIM FSLIT("unsafeCoerce#") unsafeCoerceIdKey  unsafeCoerceId
947 nullAddrName     = mkWiredInIdName gHC_PRIM FSLIT("nullAddr#")     nullAddrIdKey      nullAddrId
948 seqName          = mkWiredInIdName gHC_PRIM FSLIT("seq")           seqIdKey           seqId
949 realWorldName    = mkWiredInIdName gHC_PRIM FSLIT("realWorld#")    realWorldPrimIdKey realWorldPrimId
950 lazyIdName       = mkWiredInIdName gHC_BASE FSLIT("lazy")         lazyIdKey           lazyId
951
952 errorName                = mkWiredInIdName gHC_ERR FSLIT("error")            errorIdKey eRROR_ID
953 recSelErrorName          = mkWiredInIdName gHC_ERR FSLIT("recSelError")     recSelErrorIdKey rEC_SEL_ERROR_ID
954 runtimeErrorName         = mkWiredInIdName gHC_ERR FSLIT("runtimeError")    runtimeErrorIdKey rUNTIME_ERROR_ID
955 irrefutPatErrorName      = mkWiredInIdName gHC_ERR FSLIT("irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
956 recConErrorName          = mkWiredInIdName gHC_ERR FSLIT("recConError")     recConErrorIdKey rEC_CON_ERROR_ID
957 patErrorName             = mkWiredInIdName gHC_ERR FSLIT("patError")         patErrorIdKey pAT_ERROR_ID
958 noMethodBindingErrorName = mkWiredInIdName gHC_ERR FSLIT("noMethodBindingError")
959                                            noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
960 nonExhaustiveGuardsErrorName 
961   = mkWiredInIdName gHC_ERR FSLIT("nonExhaustiveGuardsError") 
962                     nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
963 \end{code}
964
965 \begin{code}
966 -- unsafeCoerce# :: forall a b. a -> b
967 unsafeCoerceId
968   = pcMiscPrelId unsafeCoerceName ty info
969   where
970     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
971            
972
973     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
974                       (mkFunTy openAlphaTy openBetaTy)
975     [x] = mkTemplateLocals [openAlphaTy]
976     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
977 --       Note (Coerce openBetaTy openAlphaTy) (Var x)
978          Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
979
980 -- nullAddr# :: Addr#
981 -- The reason is is here is because we don't provide 
982 -- a way to write this literal in Haskell.
983 nullAddrId 
984   = pcMiscPrelId nullAddrName addrPrimTy info
985   where
986     info = noCafIdInfo `setUnfoldingInfo` 
987            mkCompulsoryUnfolding (Lit nullAddrLit)
988
989 seqId
990   = pcMiscPrelId seqName ty info
991   where
992     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
993            
994
995     ty  = mkForAllTys [alphaTyVar,openBetaTyVar]
996                       (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
997     [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
998     rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
999
1000 -- lazy :: forall a?. a? -> a?   (i.e. works for unboxed types too)
1001 -- Used to lazify pseq:         pseq a b = a `seq` lazy b
1002 -- 
1003 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1004 -- not from GHC.Base.hi.   This is important, because the strictness
1005 -- analyser will spot it as strict!
1006 --
1007 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapper pass
1008 --      (see WorkWrap.wwExpr)   
1009 -- We could use inline phases to do this, but that would be vulnerable to changes in 
1010 -- phase numbering....we must inline precisely after strictness analysis.
1011 lazyId
1012   = pcMiscPrelId lazyIdName ty info
1013   where
1014     info = noCafIdInfo
1015     ty  = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1016
1017 lazyIdUnfolding :: CoreExpr     -- Used to expand 'lazyId' after strictness anal
1018 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1019                 where
1020                   [x] = mkTemplateLocals [openAlphaTy]
1021 \end{code}
1022
1023 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
1024 nasty as-is, change it back to a literal (@Literal@).
1025
1026 voidArgId is a Local Id used simply as an argument in functions
1027 where we just want an arg to avoid having a thunk of unlifted type.
1028 E.g.
1029         x = \ void :: State# RealWorld -> (# p, q #)
1030
1031 This comes up in strictness analysis
1032
1033 \begin{code}
1034 realWorldPrimId -- :: State# RealWorld
1035   = pcMiscPrelId realWorldName realWorldStatePrimTy
1036                  (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1037         -- The evaldUnfolding makes it look that realWorld# is evaluated
1038         -- which in turn makes Simplify.interestingArg return True,
1039         -- which in turn makes INLINE things applied to realWorld# likely
1040         -- to be inlined
1041
1042 voidArgId       -- :: State# RealWorld
1043   = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
1044 \end{code}
1045
1046
1047 %************************************************************************
1048 %*                                                                      *
1049 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1050 %*                                                                      *
1051 %************************************************************************
1052
1053 GHC randomly injects these into the code.
1054
1055 @patError@ is just a version of @error@ for pattern-matching
1056 failures.  It knows various ``codes'' which expand to longer
1057 strings---this saves space!
1058
1059 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
1060 well shouldn't be yanked on, but if one is, then you will get a
1061 friendly message from @absentErr@ (rather than a totally random
1062 crash).
1063
1064 @parError@ is a special version of @error@ which the compiler does
1065 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
1066 templates, but we don't ever expect to generate code for it.
1067
1068 \begin{code}
1069 mkRuntimeErrorApp 
1070         :: Id           -- Should be of type (forall a. Addr# -> a)
1071                         --      where Addr# points to a UTF8 encoded string
1072         -> Type         -- The type to instantiate 'a'
1073         -> String       -- The string to print
1074         -> CoreExpr
1075
1076 mkRuntimeErrorApp err_id res_ty err_msg 
1077   = mkApps (Var err_id) [Type res_ty, err_string]
1078   where
1079     err_string = Lit (mkStringLit err_msg)
1080
1081 rEC_SEL_ERROR_ID                = mkRuntimeErrorId recSelErrorName
1082 rUNTIME_ERROR_ID                = mkRuntimeErrorId runtimeErrorName
1083 iRREFUT_PAT_ERROR_ID            = mkRuntimeErrorId irrefutPatErrorName
1084 rEC_CON_ERROR_ID                = mkRuntimeErrorId recConErrorName
1085 pAT_ERROR_ID                    = mkRuntimeErrorId patErrorName
1086 nO_METHOD_BINDING_ERROR_ID      = mkRuntimeErrorId noMethodBindingErrorName
1087 nON_EXHAUSTIVE_GUARDS_ERROR_ID  = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1088
1089 -- The runtime error Ids take a UTF8-encoded string as argument
1090 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1091 runtimeErrorTy        = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1092 \end{code}
1093
1094 \begin{code}
1095 eRROR_ID = pc_bottoming_Id errorName errorTy
1096
1097 errorTy  :: Type
1098 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1099     -- Notice the openAlphaTyVar.  It says that "error" can be applied
1100     -- to unboxed as well as boxed types.  This is OK because it never
1101     -- returns, so the return type is irrelevant.
1102 \end{code}
1103
1104
1105 %************************************************************************
1106 %*                                                                      *
1107 \subsection{Utilities}
1108 %*                                                                      *
1109 %************************************************************************
1110
1111 \begin{code}
1112 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1113 pcMiscPrelId name ty info
1114   = mkVanillaGlobal name ty info
1115     -- We lie and say the thing is imported; otherwise, we get into
1116     -- a mess with dependency analysis; e.g., core2stg may heave in
1117     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
1118     -- being compiled, then it's just a matter of luck if the definition
1119     -- will be in "the right place" to be in scope.
1120
1121 pc_bottoming_Id name ty
1122  = pcMiscPrelId name ty bottoming_info
1123  where
1124     bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1125         -- Do *not* mark them as NoCafRefs, because they can indeed have
1126         -- CAF refs.  For example, pAT_ERROR_ID calls GHC.Err.untangle,
1127         -- which has some CAFs
1128         -- In due course we may arrange that these error-y things are
1129         -- regarded by the GC as permanently live, in which case we
1130         -- can give them NoCaf info.  As it is, any function that calls
1131         -- any pc_bottoming_Id will itself have CafRefs, which bloats
1132         -- SRTs.
1133
1134     strict_sig     = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1135         -- These "bottom" out, no matter what their arguments
1136
1137 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
1138 openAlphaTy  = mkTyVarTy openAlphaTyVar
1139 openBetaTy   = mkTyVarTy openBetaTyVar
1140 \end{code}
1141