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