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