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