Add {-# OPTIONS_GHC -w #-} and some blurb to all compiler modules
[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_GHC -w #-}
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/WorkingConventions#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                                      `mkTyApps`  map snd eq_spec        -- Equality evidence 
347                                      `mkVarApps` eq_args
348                                      `mkVarApps` reverse rep_ids
349
350     (dict_args,i2) = mkLocals 1  dict_tys
351     (id_args,i3)   = mkLocals i2 orig_arg_tys
352     wrap_arity     = i3-1
353     (eq_args,_)    = mkCoVarLocals i3 eq_tys
354
355     mkCoVarLocals i []     = ([],i)
356     mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
357                                  y      = mkCoVar (mkSysTvName (mkBuiltinUnique i) FSLIT("dc_co")) x
358                              in (y:ys,j)
359
360     mk_case 
361            :: (Id, StrictnessMark)      -- Arg, strictness
362            -> (Int -> [Id] -> CoreExpr) -- Body
363            -> Int                       -- Next rep arg id
364            -> [Id]                      -- Rep args so far, reversed
365            -> CoreExpr
366     mk_case (arg,strict) body i rep_args
367           = case strict of
368                 NotMarkedStrict -> body i (arg:rep_args)
369                 MarkedStrict 
370                    | isUnLiftedType (idType arg) -> body i (arg:rep_args)
371                    | otherwise ->
372                         Case (Var arg) arg res_ty [(DEFAULT,[], body i (arg:rep_args))]
373
374                 MarkedUnboxed
375                    -> unboxProduct i (Var arg) (idType arg) the_body 
376                       where
377                         the_body i con_args = body i (reverse con_args ++ rep_args)
378
379 mAX_CPR_SIZE :: Arity
380 mAX_CPR_SIZE = 10
381 -- We do not treat very big tuples as CPR-ish:
382 --      a) for a start we get into trouble because there aren't 
383 --         "enough" unboxed tuple types (a tiresome restriction, 
384 --         but hard to fix), 
385 --      b) more importantly, big unboxed tuples get returned mainly
386 --         on the stack, and are often then allocated in the heap
387 --         by the caller.  So doing CPR for them may in fact make
388 --         things worse.
389
390 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
391                where
392                  n = length tys
393 \end{code}
394
395
396 %************************************************************************
397 %*                                                                      *
398 \subsection{Record selectors}
399 %*                                                                      *
400 %************************************************************************
401
402 We're going to build a record selector unfolding that looks like this:
403
404         data T a b c = T1 { ..., op :: a, ...}
405                      | T2 { ..., op :: a, ...}
406                      | T3
407
408         sel = /\ a b c -> \ d -> case d of
409                                     T1 ... x ... -> x
410                                     T2 ... x ... -> x
411                                     other        -> error "..."
412
413 Similarly for newtypes
414
415         newtype N a = MkN { unN :: a->a }
416
417         unN :: N a -> a -> a
418         unN n = coerce (a->a) n
419         
420 We need to take a little care if the field has a polymorphic type:
421
422         data R = R { f :: forall a. a->a }
423
424 Then we want
425
426         f :: forall a. R -> a -> a
427         f = /\ a \ r = case r of
428                           R f -> f a
429
430 (not f :: R -> forall a. a->a, which gives the type inference mechanism 
431 problems at call sites)
432
433 Similarly for (recursive) newtypes
434
435         newtype N = MkN { unN :: forall a. a->a }
436
437         unN :: forall b. N -> b -> b
438         unN = /\b -> \n:N -> (coerce (forall a. a->a) n)
439
440
441 Note [Naughty record selectors]
442 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
443 A "naughty" field is one for which we can't define a record 
444 selector, because an existential type variable would escape.  For example:
445         data T = forall a. MkT { x,y::a }
446 We obviously can't define       
447         x (MkT v _) = v
448 Nevertheless we *do* put a RecordSelId into the type environment
449 so that if the user tries to use 'x' as a selector we can bleat
450 helpfully, rather than saying unhelpfully that 'x' is not in scope.
451 Hence the sel_naughty flag, to identify record selectors that don't really exist.
452
453 In general, a field is naughty if its type mentions a type variable that
454 isn't in the result type of the constructor.
455
456 Note [GADT record selectors]
457 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
458 For GADTs, we require that all constructors with a common field 'f' have the same
459 result type (modulo alpha conversion).  [Checked in TcTyClsDecls.checkValidTyCon]
460 E.g. 
461         data T where
462           T1 { f :: a } :: T [a]
463           T2 { f :: a, y :: b  } :: T [a]
464 and now the selector takes that type as its argument:
465         f :: forall a. T [a] -> a
466         f t = case t of
467                 T1 { f = v } -> v
468                 T2 { f = v } -> v
469 Note the forall'd tyvars of the selector are just the free tyvars
470 of the result type; there may be other tyvars in the constructor's
471 type (e.g. 'b' in T2).
472
473 Note [Selector running example]
474 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
475 It's OK to combine GADTs and type families.  Here's a running example:
476
477         data instance T [a] where 
478           T1 { fld :: b } :: T [Maybe b]
479
480 The representation type looks like this
481         data :R7T a where
482           T1 { fld :: b } :: :R7T (Maybe b)
483
484 and there's coercion from the family type to the representation type
485         :CoR7T a :: T [a] ~ :R7T a
486
487 The selector we want for fld looks like this:
488
489         fld :: forall b. T [Maybe b] -> b
490         fld = /\b. \(d::T [Maybe b]).
491               case d `cast` :CoR7T (Maybe b) of 
492                 T1 (x::b) -> x
493
494 The scrutinee of the case has type :R7T (Maybe b), which can be
495 gotten by appying the eq_spec to the univ_tvs of the data con.
496
497 \begin{code}
498 mkRecordSelId :: TyCon -> FieldLabel -> Id
499 mkRecordSelId tycon field_label
500         -- Assumes that all fields with the same field label have the same type
501   | is_naughty = naughty_id
502   | otherwise  = sel_id
503   where
504     is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tv_set)
505     sel_id_details = RecordSelId { sel_tycon = tycon, sel_label = field_label, sel_naughty = is_naughty }
506         -- For a data type family, the tycon is the *instance* TyCon
507
508     -- Escapist case here for naughty constructors
509     -- We give it no IdInfo, and a type of forall a.a (never looked at)
510     naughty_id = mkGlobalId sel_id_details field_label forall_a_a noCafIdInfo
511     forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
512
513     -- Normal case starts here
514     sel_id = mkGlobalId sel_id_details field_label selector_ty info
515     data_cons         = tyConDataCons tycon     
516     data_cons_w_field = filter has_field data_cons      -- Can't be empty!
517     has_field con     = field_label `elem` dataConFieldLabels con
518
519     con1        = ASSERT( not (null data_cons_w_field) ) head data_cons_w_field
520     (univ_tvs, _, eq_spec, _, _, _, data_ty) = dataConFullSig con1
521         -- For a data type family, the data_ty (and hence selector_ty) mentions
522         -- only the family TyCon, not the instance TyCon
523     data_tv_set = tyVarsOfType data_ty
524     data_tvs    = varSetElems data_tv_set
525     field_ty    = dataConFieldType con1 field_label
526     
527         -- *Very* tiresomely, the selectors are (unnecessarily!) overloaded over
528         -- just the dictionaries in the types of the constructors that contain
529         -- the relevant field.  [The Report says that pattern matching on a
530         -- constructor gives the same constraints as applying it.]  Urgh.  
531         --
532         -- However, not all data cons have all constraints (because of
533         -- BuildTyCl.mkDataConStupidTheta).  So we need to find all the data cons 
534         -- involved in the pattern match and take the union of their constraints.
535     stupid_dict_tys = mkPredTys (dataConsStupidTheta data_cons_w_field)
536     n_stupid_dicts  = length stupid_dict_tys
537
538     (field_tyvars,pre_field_theta,field_tau) = tcSplitSigmaTy field_ty
539     field_theta       = filter (not . isEqPred) pre_field_theta
540     field_dict_tys    = mkPredTys field_theta
541     n_field_dict_tys  = length field_dict_tys
542         -- If the field has a universally quantified type we have to 
543         -- be a bit careful.  Suppose we have
544         --      data R = R { op :: forall a. Foo a => a -> a }
545         -- Then we can't give op the type
546         --      op :: R -> forall a. Foo a => a -> a
547         -- because the typechecker doesn't understand foralls to the
548         -- right of an arrow.  The "right" type to give it is
549         --      op :: forall a. Foo a => R -> a -> a
550         -- But then we must generate the right unfolding too:
551         --      op = /\a -> \dfoo -> \ r ->
552         --           case r of
553         --              R op -> op a dfoo
554         -- Note that this is exactly the type we'd infer from a user defn
555         --      op (R op) = op
556
557     selector_ty :: Type
558     selector_ty  = mkForAllTys data_tvs $ mkForAllTys field_tyvars $
559                    mkFunTys stupid_dict_tys  $  mkFunTys field_dict_tys $
560                    mkFunTy data_ty field_tau
561       
562     arity = 1 + n_stupid_dicts + n_field_dict_tys
563
564     (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
565         -- Use the demand analyser to work out strictness.
566         -- With all this unpackery it's not easy!
567
568     info = noCafIdInfo
569            `setCafInfo`           caf_info
570            `setArityInfo`         arity
571            `setUnfoldingInfo`     mkTopUnfolding rhs_w_str
572            `setAllStrictnessInfo` Just strict_sig
573
574         -- Allocate Ids.  We do it a funny way round because field_dict_tys is
575         -- almost always empty.  Also note that we use max_dict_tys
576         -- rather than n_dict_tys, because the latter gives an infinite loop:
577         -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
578         -- on arity, which depends on n_dict tys.  Sigh!  Mega sigh!
579     stupid_dict_ids  = mkTemplateLocalsNum 1 stupid_dict_tys
580     max_stupid_dicts = length (tyConStupidTheta tycon)
581     field_dict_base  = max_stupid_dicts + 1
582     field_dict_ids   = mkTemplateLocalsNum field_dict_base field_dict_tys
583     dict_id_base     = field_dict_base + n_field_dict_tys
584     data_id          = mkTemplateLocal dict_id_base data_ty
585     scrut_id         = mkTemplateLocal (dict_id_base+1) scrut_ty
586     arg_base         = dict_id_base + 2
587
588     the_alts :: [CoreAlt]
589     the_alts   = map mk_alt data_cons_w_field   -- Already sorted by data-con
590     no_default = length data_cons == length data_cons_w_field   -- No default needed
591
592     default_alt | no_default = []
593                 | otherwise  = [(DEFAULT, [], error_expr)]
594
595         -- The default branch may have CAF refs, because it calls recSelError etc.
596     caf_info    | no_default = NoCafRefs
597                 | otherwise  = MayHaveCafRefs
598
599     sel_rhs = mkLams data_tvs $ mkLams field_tyvars $ 
600               mkLams stupid_dict_ids $ mkLams field_dict_ids $
601               Lam data_id $ mk_result sel_body
602
603     scrut_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
604     scrut_ty      = mkTyConApp tycon scrut_ty_args
605     scrut = unwrapFamInstScrut tycon scrut_ty_args (Var data_id)
606         -- First coerce from the type family to the representation type
607
608         -- NB: A newtype always has a vanilla DataCon; no existentials etc
609         --     data_tys will simply be the dataConUnivTyVars
610     sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon scrut_ty_args scrut
611              | otherwise        = Case scrut scrut_id field_ty (default_alt ++ the_alts)
612
613     mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
614         -- We pull the field lambdas to the top, so we need to 
615         -- apply them in the body.  For example:
616         --      data T = MkT { foo :: forall a. a->a }
617         --
618         --      foo :: forall a. T -> a -> a
619         --      foo = /\a. \t:T. case t of { MkT f -> f a }
620
621     mk_alt data_con 
622       =   ASSERT2( data_ty `tcEqType` field_ty, ppr data_con $$ ppr data_ty $$ ppr field_ty )
623           mkReboxingAlt rebox_uniqs data_con (ex_tvs ++ co_tvs ++ arg_vs) rhs
624       where
625            -- get pattern binders with types appropriately instantiated
626         arg_uniqs = map mkBuiltinUnique [arg_base..]
627         (ex_tvs, co_tvs, arg_vs) = dataConOrigInstPat arg_uniqs data_con scrut_ty_args
628
629         rebox_base  = arg_base + length ex_tvs + length co_tvs + length arg_vs
630         rebox_uniqs = map mkBuiltinUnique [rebox_base..]
631
632         -- data T :: *->* where T1 { fld :: Maybe b } -> T [b]
633         --      Hence T1 :: forall a b. (a=[b]) => b -> T a
634         -- fld :: forall b. T [b] -> Maybe b
635         -- fld = /\b.\(t:T[b]). case t of 
636         --              T1 b' (c : [b]=[b']) (x:Maybe b') 
637         --                      -> x `cast` Maybe (sym (right c))
638
639
640                 -- Generate the refinement for b'=b, 
641                 -- and apply to (Maybe b'), to get (Maybe b)
642         Succeeded refinement = gadtRefine emptyRefinement ex_tvs co_tvs
643         the_arg_id_ty = idType the_arg_id
644         (rhs, data_ty) = case refineType refinement the_arg_id_ty of
645                           Just (co, data_ty) -> (Cast (Var the_arg_id) co, data_ty)
646                           Nothing            -> (Var the_arg_id, the_arg_id_ty)
647
648         field_vs    = filter (not . isPredTy . idType) arg_vs 
649         the_arg_id  = assoc "mkRecordSelId:mk_alt" (field_lbls `zip` field_vs) field_label
650         field_lbls  = dataConFieldLabels data_con
651
652     error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_ty full_msg
653     full_msg   = showSDoc (sep [text "No match in record selector", ppr sel_id])
654
655 -- unbox a product type...
656 -- we will recurse into newtypes, casting along the way, and unbox at the
657 -- first product data constructor we find. e.g.
658 --  
659 --   data PairInt = PairInt Int Int
660 --   newtype S = MkS PairInt
661 --   newtype T = MkT S
662 --
663 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
664 -- ids, we get (modulo int passing)
665 --
666 --   case (e `cast` CoT) `cast` CoS of
667 --     PairInt a b -> body [a,b]
668 --
669 -- The Ints passed around are just for creating fresh locals
670 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
671 unboxProduct i arg arg_ty body
672   = result
673   where 
674     result = mkUnpackCase the_id arg con_args boxing_con rhs
675     (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
676     ([the_id], i') = mkLocals i [arg_ty]
677     (con_args, i'') = mkLocals i' tys
678     rhs = body i'' con_args
679
680 mkUnpackCase ::  Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
681 -- (mkUnpackCase x e args Con body)
682 --      returns
683 -- case (e `cast` ...) of bndr { Con args -> body }
684 -- 
685 -- the type of the bndr passed in is irrelevent
686 mkUnpackCase bndr arg unpk_args boxing_con body
687   = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
688   where
689   (cast_arg, bndr_ty) = go (idType bndr) arg
690   go ty arg 
691     | (tycon, tycon_args, _, _)  <- splitProductType "mkUnpackCase" ty
692     , isNewTyCon tycon && not (isRecursiveTyCon tycon)
693     = go (newTyConInstRhs tycon tycon_args) 
694          (unwrapNewTypeBody tycon tycon_args arg)
695     | otherwise = (arg, ty)
696
697 -- ...and the dual
698 reboxProduct :: [Unique]     -- uniques to create new local binders
699              -> Type         -- type of product to box
700              -> ([Unique],   -- remaining uniques
701                  CoreExpr,   -- boxed product
702                  [Id])       -- Ids being boxed into product
703 reboxProduct us ty
704   = let 
705         (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
706  
707         us' = dropList con_arg_tys us
708
709         arg_ids  = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
710
711         bind_rhs = mkProductBox arg_ids ty
712
713     in
714       (us', bind_rhs, arg_ids)
715
716 mkProductBox :: [Id] -> Type -> CoreExpr
717 mkProductBox arg_ids ty 
718   = result_expr
719   where 
720     (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
721
722     result_expr
723       | isNewTyCon tycon && not (isRecursiveTyCon tycon) 
724       = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
725       | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
726
727     wrap expr = wrapNewTypeBody tycon tycon_args expr
728
729
730 -- (mkReboxingAlt us con xs rhs) basically constructs the case
731 -- alternative  (con, xs, rhs)
732 -- but it does the reboxing necessary to construct the *source* 
733 -- arguments, xs, from the representation arguments ys.
734 -- For example:
735 --      data T = MkT !(Int,Int) Bool
736 --
737 -- mkReboxingAlt MkT [x,b] r 
738 --      = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
739 --
740 -- mkDataAlt should really be in DataCon, but it can't because
741 -- it manipulates CoreSyn.
742
743 mkReboxingAlt
744   :: [Unique]           -- Uniques for the new Ids
745   -> DataCon
746   -> [Var]              -- Source-level args, including existential dicts
747   -> CoreExpr           -- RHS
748   -> CoreAlt
749
750 mkReboxingAlt us con args rhs
751   | not (any isMarkedUnboxed stricts)
752   = (DataAlt con, args, rhs)
753
754   | otherwise
755   = let
756         (binds, args') = go args stricts us
757     in
758     (DataAlt con, args', mkLets binds rhs)
759
760   where
761     stricts = dataConExStricts con ++ dataConStrictMarks con
762
763     go [] _stricts _us = ([], [])
764
765         -- Type variable case
766     go (arg:args) stricts us 
767       | isTyVar arg
768       = let (binds, args') = go args stricts us
769         in  (binds, arg:args')
770
771         -- Term variable case
772     go (arg:args) (str:stricts) us
773       | isMarkedUnboxed str
774       = 
775         let (binds, unpacked_args')        = go args stricts us'
776             (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
777         in
778             (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
779       | otherwise
780       = let (binds, args') = go args stricts us
781         in  (binds, arg:args')
782 \end{code}
783
784
785 %************************************************************************
786 %*                                                                      *
787 \subsection{Dictionary selectors}
788 %*                                                                      *
789 %************************************************************************
790
791 Selecting a field for a dictionary.  If there is just one field, then
792 there's nothing to do.  
793
794 Dictionary selectors may get nested forall-types.  Thus:
795
796         class Foo a where
797           op :: forall b. Ord b => a -> b -> b
798
799 Then the top-level type for op is
800
801         op :: forall a. Foo a => 
802               forall b. Ord b => 
803               a -> b -> b
804
805 This is unlike ordinary record selectors, which have all the for-alls
806 at the outside.  When dealing with classes it's very convenient to
807 recover the original type signature from the class op selector.
808
809 \begin{code}
810 mkDictSelId :: Name -> Class -> Id
811 mkDictSelId name clas
812   = mkGlobalId (ClassOpId clas) name sel_ty info
813   where
814     sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
815         -- We can't just say (exprType rhs), because that would give a type
816         --      C a -> C a
817         -- for a single-op class (after all, the selector is the identity)
818         -- But it's type must expose the representation of the dictionary
819         -- to get (say)         C a -> (a -> a)
820
821     info = noCafIdInfo
822                 `setArityInfo`          1
823                 `setUnfoldingInfo`      mkTopUnfolding rhs
824                 `setAllStrictnessInfo`  Just strict_sig
825
826         -- We no longer use 'must-inline' on record selectors.  They'll
827         -- inline like crazy if they scrutinise a constructor
828
829         -- The strictness signature is of the form U(AAAVAAAA) -> T
830         -- where the V depends on which item we are selecting
831         -- It's worth giving one, so that absence info etc is generated
832         -- even if the selector isn't inlined
833     strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
834     arg_dmd | isNewTyCon tycon = evalDmd
835             | otherwise        = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
836                                             | id <- arg_ids ])
837
838     tycon      = classTyCon clas
839     [data_con] = tyConDataCons tycon
840     tyvars     = dataConUnivTyVars data_con
841     arg_tys    = {- ASSERT( isVanillaDataCon data_con ) -} dataConRepArgTys data_con
842     eq_theta   = dataConEqTheta data_con
843     the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
844
845     pred       = mkClassPred clas (mkTyVarTys tyvars)
846     dict_id    = mkTemplateLocal     1 $ mkPredTy pred
847     (eq_ids,n) = mkCoVarLocals 2 $ mkPredTys eq_theta
848     arg_ids    = mkTemplateLocalsNum n arg_tys
849
850     mkCoVarLocals i []     = ([],i)
851     mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
852                                  y      = mkCoVar (mkSysTvName (mkBuiltinUnique i) FSLIT("dc_co")) x
853                              in (y:ys,j)
854
855     rhs = mkLams tyvars  (Lam dict_id   rhs_body)
856     rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
857              | otherwise        = Case (Var dict_id) dict_id (idType the_arg_id)
858                                        [(DataAlt data_con, eq_ids ++ arg_ids, Var the_arg_id)]
859 \end{code}
860
861
862 %************************************************************************
863 %*                                                                      *
864         Wrapping and unwrapping newtypes and type families
865 %*                                                                      *
866 %************************************************************************
867
868 \begin{code}
869 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
870 -- The wrapper for the data constructor for a newtype looks like this:
871 --      newtype T a = MkT (a,Int)
872 --      MkT :: forall a. (a,Int) -> T a
873 --      MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
874 -- where CoT is the coercion TyCon assoicated with the newtype
875 --
876 -- The call (wrapNewTypeBody T [a] e) returns the
877 -- body of the wrapper, namely
878 --      e `cast` (CoT [a])
879 --
880 -- If a coercion constructor is provided in the newtype, then we use
881 -- it, otherwise the wrap/unwrap are both no-ops 
882 --
883 -- If the we are dealing with a newtype *instance*, we have a second coercion
884 -- identifying the family instance with the constructor of the newtype
885 -- instance.  This coercion is applied in any case (ie, composed with the
886 -- coercion constructor of the newtype or applied by itself).
887
888 wrapNewTypeBody tycon args result_expr
889   = wrapFamInstBody tycon args inner
890   where
891     inner
892       | Just co_con <- newTyConCo_maybe tycon
893       = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
894       | otherwise
895       = result_expr
896
897 -- When unwrapping, we do *not* apply any family coercion, because this will
898 -- be done via a CoPat by the type checker.  We have to do it this way as
899 -- computing the right type arguments for the coercion requires more than just
900 -- a spliting operation (cf, TcPat.tcConPat).
901
902 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
903 unwrapNewTypeBody tycon args result_expr
904   | Just co_con <- newTyConCo_maybe tycon
905   = mkCoerce (mkTyConApp co_con args) result_expr
906   | otherwise
907   = result_expr
908
909 -- If the type constructor is a representation type of a data instance, wrap
910 -- the expression into a cast adjusting the expression type, which is an
911 -- instance of the representation type, to the corresponding instance of the
912 -- family instance type.
913 -- See Note [Wrappers for data instance tycons]
914 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
915 wrapFamInstBody tycon args body
916   | Just co_con <- tyConFamilyCoercion_maybe tycon
917   = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
918   | otherwise
919   = body
920
921 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
922 unwrapFamInstScrut tycon args scrut
923   | Just co_con <- tyConFamilyCoercion_maybe tycon
924   = mkCoerce (mkTyConApp co_con args) scrut
925   | otherwise
926   = scrut
927 \end{code}
928
929
930 %************************************************************************
931 %*                                                                      *
932 \subsection{Primitive operations
933 %*                                                                      *
934 %************************************************************************
935
936 \begin{code}
937 mkPrimOpId :: PrimOp -> Id
938 mkPrimOpId prim_op 
939   = id
940   where
941     (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
942     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
943     name = mkWiredInName gHC_PRIM (primOpOcc prim_op) 
944                          (mkPrimOpIdUnique (primOpTag prim_op))
945                          (AnId id) UserSyntax
946     id   = mkGlobalId (PrimOpId prim_op) name ty info
947                 
948     info = noCafIdInfo
949            `setSpecInfo`          mkSpecInfo (primOpRules prim_op name)
950            `setArityInfo`         arity
951            `setAllStrictnessInfo` Just strict_sig
952
953 -- For each ccall we manufacture a separate CCallOpId, giving it
954 -- a fresh unique, a type that is correct for this particular ccall,
955 -- and a CCall structure that gives the correct details about calling
956 -- convention etc.  
957 --
958 -- The *name* of this Id is a local name whose OccName gives the full
959 -- details of the ccall, type and all.  This means that the interface 
960 -- file reader can reconstruct a suitable Id
961
962 mkFCallId :: Unique -> ForeignCall -> Type -> Id
963 mkFCallId uniq fcall ty
964   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
965         -- A CCallOpId should have no free type variables; 
966         -- when doing substitutions won't substitute over it
967     mkGlobalId (FCallId fcall) name ty info
968   where
969     occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
970         -- The "occurrence name" of a ccall is the full info about the
971         -- ccall; it is encoded, but may have embedded spaces etc!
972
973     name = mkFCallName uniq occ_str
974
975     info = noCafIdInfo
976            `setArityInfo`               arity
977            `setAllStrictnessInfo`       Just strict_sig
978
979     (_, tau)     = tcSplitForAllTys ty
980     (arg_tys, _) = tcSplitFunTys tau
981     arity        = length arg_tys
982     strict_sig   = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
983
984 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
985 -- except for the type:
986 --
987 --    a plain HPC tick box has type (State# RealWorld)
988 --    a breakpoint Id has type forall a.a
989 --
990 -- The breakpoint Id will be applied to a list of arbitrary free variables,
991 -- which is why it needs a polymorphic type.
992
993 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
994 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
995
996 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
997 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
998  where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
999
1000 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info    
1001   where
1002     tickbox = TickBox mod ix
1003     occ_str = showSDoc (braces (ppr tickbox))
1004     name    = mkTickBoxOpName uniq occ_str
1005     info    = noCafIdInfo
1006 \end{code}
1007
1008
1009 %************************************************************************
1010 %*                                                                      *
1011 \subsection{DictFuns and default methods}
1012 %*                                                                      *
1013 %************************************************************************
1014
1015 Important notes about dict funs and default methods
1016 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1017 Dict funs and default methods are *not* ImplicitIds.  Their definition
1018 involves user-written code, so we can't figure out their strictness etc
1019 based on fixed info, as we can for constructors and record selectors (say).
1020
1021 We build them as LocalIds, but with External Names.  This ensures that
1022 they are taken to account by free-variable finding and dependency
1023 analysis (e.g. CoreFVs.exprFreeVars).
1024
1025 Why shouldn't they be bound as GlobalIds?  Because, in particular, if
1026 they are globals, the specialiser floats dict uses above their defns,
1027 which prevents good simplifications happening.  Also the strictness
1028 analyser treats a occurrence of a GlobalId as imported and assumes it
1029 contains strictness in its IdInfo, which isn't true if the thing is
1030 bound in the same module as the occurrence.
1031
1032 It's OK for dfuns to be LocalIds, because we form the instance-env to
1033 pass on to the next module (md_insts) in CoreTidy, afer tidying
1034 and globalising the top-level Ids.
1035
1036 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so 
1037 that they aren't discarded by the occurrence analyser.
1038
1039 \begin{code}
1040 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
1041
1042 mkDictFunId :: Name             -- Name to use for the dict fun;
1043             -> [TyVar]
1044             -> ThetaType
1045             -> Class 
1046             -> [Type]
1047             -> Id
1048
1049 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
1050   = mkExportedLocalId dfun_name dfun_ty
1051   where
1052     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
1053
1054 {-  1 dec 99: disable the Mark Jones optimisation for the sake
1055     of compatibility with Hugs.
1056     See `types/InstEnv' for a discussion related to this.
1057
1058     (class_tyvars, sc_theta, _, _) = classBigSig clas
1059     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
1060     sc_theta' = substClasses (zipTopTvSubst class_tyvars inst_tys) sc_theta
1061     dfun_theta = case inst_decl_theta of
1062                    []    -> []  -- If inst_decl_theta is empty, then we don't
1063                                 -- want to have any dict arguments, so that we can
1064                                 -- expose the constant methods.
1065
1066                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
1067                                 -- Otherwise we pass the superclass dictionaries to
1068                                 -- the dictionary function; the Mark Jones optimisation.
1069                                 --
1070                                 -- NOTE the "nub".  I got caught by this one:
1071                                 --   class Monad m => MonadT t m where ...
1072                                 --   instance Monad m => MonadT (EnvT env) m where ...
1073                                 -- Here, the inst_decl_theta has (Monad m); but so
1074                                 -- does the sc_theta'!
1075                                 --
1076                                 -- NOTE the "not_const".  I got caught by this one too:
1077                                 --   class Foo a => Baz a b where ...
1078                                 --   instance Wob b => Baz T b where..
1079                                 -- Now sc_theta' has Foo T
1080 -}
1081 \end{code}
1082
1083
1084 %************************************************************************
1085 %*                                                                      *
1086 \subsection{Un-definable}
1087 %*                                                                      *
1088 %************************************************************************
1089
1090 These Ids can't be defined in Haskell.  They could be defined in
1091 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
1092 ensure that they were definitely, definitely inlined, because there is
1093 no curried identifier for them.  That's what mkCompulsoryUnfolding
1094 does.  If we had a way to get a compulsory unfolding from an interface
1095 file, we could do that, but we don't right now.
1096
1097 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
1098 just gets expanded into a type coercion wherever it occurs.  Hence we
1099 add it as a built-in Id with an unfolding here.
1100
1101 The type variables we use here are "open" type variables: this means
1102 they can unify with both unlifted and lifted types.  Hence we provide
1103 another gun with which to shoot yourself in the foot.
1104
1105 \begin{code}
1106 mkWiredInIdName mod fs uniq id
1107  = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
1108
1109 unsafeCoerceName = mkWiredInIdName gHC_PRIM FSLIT("unsafeCoerce#") unsafeCoerceIdKey  unsafeCoerceId
1110 nullAddrName     = mkWiredInIdName gHC_PRIM FSLIT("nullAddr#")     nullAddrIdKey      nullAddrId
1111 seqName          = mkWiredInIdName gHC_PRIM FSLIT("seq")           seqIdKey           seqId
1112 realWorldName    = mkWiredInIdName gHC_PRIM FSLIT("realWorld#")    realWorldPrimIdKey realWorldPrimId
1113 lazyIdName       = mkWiredInIdName gHC_BASE FSLIT("lazy")         lazyIdKey           lazyId
1114
1115 errorName                = mkWiredInIdName gHC_ERR FSLIT("error")            errorIdKey eRROR_ID
1116 recSelErrorName          = mkWiredInIdName gHC_ERR FSLIT("recSelError")     recSelErrorIdKey rEC_SEL_ERROR_ID
1117 runtimeErrorName         = mkWiredInIdName gHC_ERR FSLIT("runtimeError")    runtimeErrorIdKey rUNTIME_ERROR_ID
1118 irrefutPatErrorName      = mkWiredInIdName gHC_ERR FSLIT("irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
1119 recConErrorName          = mkWiredInIdName gHC_ERR FSLIT("recConError")     recConErrorIdKey rEC_CON_ERROR_ID
1120 patErrorName             = mkWiredInIdName gHC_ERR FSLIT("patError")         patErrorIdKey pAT_ERROR_ID
1121 noMethodBindingErrorName = mkWiredInIdName gHC_ERR FSLIT("noMethodBindingError")
1122                                            noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
1123 nonExhaustiveGuardsErrorName 
1124   = mkWiredInIdName gHC_ERR FSLIT("nonExhaustiveGuardsError") 
1125                     nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
1126 \end{code}
1127
1128 \begin{code}
1129 -- unsafeCoerce# :: forall a b. a -> b
1130 unsafeCoerceId
1131   = pcMiscPrelId unsafeCoerceName ty info
1132   where
1133     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1134            
1135
1136     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
1137                       (mkFunTy openAlphaTy openBetaTy)
1138     [x] = mkTemplateLocals [openAlphaTy]
1139     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
1140           Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
1141
1142 -- nullAddr# :: Addr#
1143 -- The reason is is here is because we don't provide 
1144 -- a way to write this literal in Haskell.
1145 nullAddrId 
1146   = pcMiscPrelId nullAddrName addrPrimTy info
1147   where
1148     info = noCafIdInfo `setUnfoldingInfo` 
1149            mkCompulsoryUnfolding (Lit nullAddrLit)
1150
1151 seqId
1152   = pcMiscPrelId seqName ty info
1153   where
1154     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
1155            
1156
1157     ty  = mkForAllTys [alphaTyVar,openBetaTyVar]
1158                       (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
1159     [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
1160     rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
1161
1162 -- lazy :: forall a?. a? -> a?   (i.e. works for unboxed types too)
1163 -- Used to lazify pseq:         pseq a b = a `seq` lazy b
1164 -- 
1165 -- Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
1166 -- not from GHC.Base.hi.   This is important, because the strictness
1167 -- analyser will spot it as strict!
1168 --
1169 -- Also no unfolding in lazyId: it gets "inlined" by a HACK in the worker/wrapperpass
1170 --      (see WorkWrap.wwExpr)   
1171 -- We could use inline phases to do this, but that would be vulnerable to changes in 
1172 -- phase numbering....we must inline precisely after strictness analysis.
1173 lazyId
1174   = pcMiscPrelId lazyIdName ty info
1175   where
1176     info = noCafIdInfo
1177     ty  = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
1178
1179 lazyIdUnfolding :: CoreExpr     -- Used to expand 'lazyId' after strictness anal
1180 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
1181                 where
1182                   [x] = mkTemplateLocals [openAlphaTy]
1183 \end{code}
1184
1185 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
1186 nasty as-is, change it back to a literal (@Literal@).
1187
1188 voidArgId is a Local Id used simply as an argument in functions
1189 where we just want an arg to avoid having a thunk of unlifted type.
1190 E.g.
1191         x = \ void :: State# RealWorld -> (# p, q #)
1192
1193 This comes up in strictness analysis
1194
1195 \begin{code}
1196 realWorldPrimId -- :: State# RealWorld
1197   = pcMiscPrelId realWorldName realWorldStatePrimTy
1198                  (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
1199         -- The evaldUnfolding makes it look that realWorld# is evaluated
1200         -- which in turn makes Simplify.interestingArg return True,
1201         -- which in turn makes INLINE things applied to realWorld# likely
1202         -- to be inlined
1203
1204 voidArgId       -- :: State# RealWorld
1205   = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
1206 \end{code}
1207
1208
1209 %************************************************************************
1210 %*                                                                      *
1211 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1212 %*                                                                      *
1213 %************************************************************************
1214
1215 GHC randomly injects these into the code.
1216
1217 @patError@ is just a version of @error@ for pattern-matching
1218 failures.  It knows various ``codes'' which expand to longer
1219 strings---this saves space!
1220
1221 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
1222 well shouldn't be yanked on, but if one is, then you will get a
1223 friendly message from @absentErr@ (rather than a totally random
1224 crash).
1225
1226 @parError@ is a special version of @error@ which the compiler does
1227 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
1228 templates, but we don't ever expect to generate code for it.
1229
1230 \begin{code}
1231 mkRuntimeErrorApp 
1232         :: Id           -- Should be of type (forall a. Addr# -> a)
1233                         --      where Addr# points to a UTF8 encoded string
1234         -> Type         -- The type to instantiate 'a'
1235         -> String       -- The string to print
1236         -> CoreExpr
1237
1238 mkRuntimeErrorApp err_id res_ty err_msg 
1239   = mkApps (Var err_id) [Type res_ty, err_string]
1240   where
1241     err_string = Lit (mkStringLit err_msg)
1242
1243 rEC_SEL_ERROR_ID                = mkRuntimeErrorId recSelErrorName
1244 rUNTIME_ERROR_ID                = mkRuntimeErrorId runtimeErrorName
1245 iRREFUT_PAT_ERROR_ID            = mkRuntimeErrorId irrefutPatErrorName
1246 rEC_CON_ERROR_ID                = mkRuntimeErrorId recConErrorName
1247 pAT_ERROR_ID                    = mkRuntimeErrorId patErrorName
1248 nO_METHOD_BINDING_ERROR_ID      = mkRuntimeErrorId noMethodBindingErrorName
1249 nON_EXHAUSTIVE_GUARDS_ERROR_ID  = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1250
1251 -- The runtime error Ids take a UTF8-encoded string as argument
1252 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1253 runtimeErrorTy        = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1254 \end{code}
1255
1256 \begin{code}
1257 eRROR_ID = pc_bottoming_Id errorName errorTy
1258
1259 errorTy  :: Type
1260 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1261     -- Notice the openAlphaTyVar.  It says that "error" can be applied
1262     -- to unboxed as well as boxed types.  This is OK because it never
1263     -- returns, so the return type is irrelevant.
1264 \end{code}
1265
1266
1267 %************************************************************************
1268 %*                                                                      *
1269 \subsection{Utilities}
1270 %*                                                                      *
1271 %************************************************************************
1272
1273 \begin{code}
1274 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1275 pcMiscPrelId name ty info
1276   = mkVanillaGlobal name ty info
1277     -- We lie and say the thing is imported; otherwise, we get into
1278     -- a mess with dependency analysis; e.g., core2stg may heave in
1279     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
1280     -- being compiled, then it's just a matter of luck if the definition
1281     -- will be in "the right place" to be in scope.
1282
1283 pc_bottoming_Id name ty
1284  = pcMiscPrelId name ty bottoming_info
1285  where
1286     bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1287         -- Do *not* mark them as NoCafRefs, because they can indeed have
1288         -- CAF refs.  For example, pAT_ERROR_ID calls GHC.Err.untangle,
1289         -- which has some CAFs
1290         -- In due course we may arrange that these error-y things are
1291         -- regarded by the GC as permanently live, in which case we
1292         -- can give them NoCaf info.  As it is, any function that calls
1293         -- any pc_bottoming_Id will itself have CafRefs, which bloats
1294         -- SRTs.
1295
1296     strict_sig     = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1297         -- These "bottom" out, no matter what their arguments
1298 \end{code}
1299