Allow RULES for seq, and exploit them
[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         mkPrimOpId, mkFCallId, mkTickBoxOpId, mkBreakPointOpId,
28
29         mkReboxingAlt, wrapNewTypeBody, unwrapNewTypeBody,
30         wrapFamInstBody, unwrapFamInstScrut,
31         mkUnpackCase, mkProductBox,
32
33         -- And some particular Ids; see below for why they are wired in
34         wiredInIds, ghcPrimIds,
35         unsafeCoerceId, realWorldPrimId, voidArgId, nullAddrId, seqId,
36         lazyId, lazyIdKey,
37
38         mkRuntimeErrorApp, mkImpossibleExpr,
39         rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
40         nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
41         pAT_ERROR_ID, eRROR_ID, rEC_SEL_ERROR_ID,
42
43         unsafeCoerceName
44     ) where
45
46 #include "HsVersions.h"
47
48 import Rules
49 import TysPrim
50 import TysWiredIn
51 import PrelRules
52 import Type
53 import TypeRep
54 import Coercion
55 import TcType
56 import CoreUtils        ( exprType, mkCoerce )
57 import CoreUnfold
58 import Literal
59 import TyCon
60 import Class
61 import VarSet
62 import Name
63 import OccName
64 import PrimOp
65 import ForeignCall
66 import DataCon
67 import Id
68 import Var              ( Var, TyVar, mkCoVar, mkExportedLocalVar )
69 import IdInfo
70 import NewDemand
71 import CoreSyn
72 import Unique
73 import Maybes
74 import PrelNames
75 import BasicTypes       hiding ( SuccessFlag(..) )
76 import Util
77 import Outputable
78 import FastString
79 import ListSetOps
80 import Module
81 \end{code}
82
83 %************************************************************************
84 %*                                                                      *
85 \subsection{Wired in Ids}
86 %*                                                                      *
87 %************************************************************************
88
89 Note [Wired-in Ids]
90 ~~~~~~~~~~~~~~~~~~~
91 There are several reasons why an Id might appear in the wiredInIds:
92
93 (1) The ghcPrimIds are wired in because they can't be defined in
94     Haskell at all, although the can be defined in Core.  They have
95     compulsory unfoldings, so they are always inlined and they  have
96     no definition site.  Their home module is GHC.Prim, so they
97     also have a description in primops.txt.pp, where they are called
98     'pseudoops'.
99
100 (2) The 'error' function, eRROR_ID, is wired in because we don't yet have
101     a way to express in an interface file that the result type variable
102     is 'open'; that is can be unified with an unboxed type
103
104     [The interface file format now carry such information, but there's
105     no way yet of expressing at the definition site for these 
106     error-reporting functions that they have an 'open' 
107     result type. -- sof 1/99]
108
109 (3) Other error functions (rUNTIME_ERROR_ID) are wired in (a) because
110     the desugarer generates code that mentiones them directly, and
111     (b) for the same reason as eRROR_ID
112
113 (4) lazyId is wired in because the wired-in version overrides the
114     strictness of the version defined in GHC.Base
115
116 In cases (2-4), the function has a definition in a library module, and
117 can be called; but the wired-in version means that the details are 
118 never read from that module's interface file; instead, the full definition
119 is right here.
120
121 \begin{code}
122 wiredInIds :: [Id]
123 wiredInIds
124   = [   
125
126     eRROR_ID,   -- This one isn't used anywhere else in the compiler
127                 -- But we still need it in wiredInIds so that when GHC
128                 -- compiles a program that mentions 'error' we don't
129                 -- import its type from the interface file; we just get
130                 -- the Id defined here.  Which has an 'open-tyvar' type.
131
132     rUNTIME_ERROR_ID,
133     iRREFUT_PAT_ERROR_ID,
134     nON_EXHAUSTIVE_GUARDS_ERROR_ID,
135     nO_METHOD_BINDING_ERROR_ID,
136     pAT_ERROR_ID,
137     rEC_CON_ERROR_ID,
138     rEC_SEL_ERROR_ID,
139
140     lazyId
141     ] ++ ghcPrimIds
142
143 -- These Ids are exported from GHC.Prim
144 ghcPrimIds :: [Id]
145 ghcPrimIds
146   = [   -- These can't be defined in Haskell, but they have
147         -- perfectly reasonable unfoldings in Core
148     realWorldPrimId,
149     unsafeCoerceId,
150     nullAddrId,
151     seqId
152     ]
153 \end{code}
154
155 %************************************************************************
156 %*                                                                      *
157 \subsection{Data constructors}
158 %*                                                                      *
159 %************************************************************************
160
161 The wrapper for a constructor is an ordinary top-level binding that evaluates
162 any strict args, unboxes any args that are going to be flattened, and calls
163 the worker.
164
165 We're going to build a constructor that looks like:
166
167         data (Data a, C b) =>  T a b = T1 !a !Int b
168
169         T1 = /\ a b -> 
170              \d1::Data a, d2::C b ->
171              \p q r -> case p of { p ->
172                        case q of { q ->
173                        Con T1 [a,b] [p,q,r]}}
174
175 Notice that
176
177 * d2 is thrown away --- a context in a data decl is used to make sure
178   one *could* construct dictionaries at the site the constructor
179   is used, but the dictionary isn't actually used.
180
181 * We have to check that we can construct Data dictionaries for
182   the types a and Int.  Once we've done that we can throw d1 away too.
183
184 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
185   all that matters is that the arguments are evaluated.  "seq" is 
186   very careful to preserve evaluation order, which we don't need
187   to be here.
188
189   You might think that we could simply give constructors some strictness
190   info, like PrimOps, and let CoreToStg do the let-to-case transformation.
191   But we don't do that because in the case of primops and functions strictness
192   is a *property* not a *requirement*.  In the case of constructors we need to
193   do something active to evaluate the argument.
194
195   Making an explicit case expression allows the simplifier to eliminate
196   it in the (common) case where the constructor arg is already evaluated.
197
198 Note [Wrappers for data instance tycons]
199 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
200 In the case of data instances, the wrapper also applies the coercion turning
201 the representation type into the family instance type to cast the result of
202 the wrapper.  For example, consider the declarations
203
204   data family Map k :: * -> *
205   data instance Map (a, b) v = MapPair (Map a (Pair b v))
206
207 The tycon to which the datacon MapPair belongs gets a unique internal
208 name of the form :R123Map, and we call it the representation tycon.
209 In contrast, Map is the family tycon (accessible via
210 tyConFamInst_maybe). A coercion allows you to move between
211 representation and family type.  It is accessible from :R123Map via
212 tyConFamilyCoercion_maybe and has kind
213
214   Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
215
216 The wrapper and worker of MapPair get the types
217
218         -- Wrapper
219   $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
220   $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v)
221
222         -- Worker
223   MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
224
225 This coercion is conditionally applied by wrapFamInstBody.
226
227 It's a bit more complicated if the data instance is a GADT as well!
228
229    data instance T [a] where
230         T1 :: forall b. b -> T [Maybe b]
231 Hence
232    Co7T a :: T [a] ~ :R7T a
233
234 Now we want
235
236         -- Wrapper
237   $WT1 :: forall b. b -> T [Maybe b]
238   $WT1 b v = T1 (Maybe b) b (Maybe b) v
239                         `cast` sym (Co7T (Maybe b))
240
241         -- Worker
242   T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
243
244 \begin{code}
245 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
246 mkDataConIds wrap_name wkr_name data_con
247   | isNewTyCon tycon                    -- Newtype, only has a worker
248   = DCIds Nothing nt_work_id                 
249
250   | any isMarkedStrict all_strict_marks      -- Algebraic, needs wrapper
251     || not (null eq_spec)                    -- NB: LoadIface.ifaceDeclSubBndrs
252     || isFamInstTyCon tycon                  --     depends on this test
253   = DCIds (Just alg_wrap_id) wrk_id
254
255   | otherwise                                -- Algebraic, no wrapper
256   = DCIds Nothing wrk_id
257   where
258     (univ_tvs, ex_tvs, eq_spec, 
259      eq_theta, dict_theta, orig_arg_tys, res_ty) = dataConFullSig data_con
260     tycon = dataConTyCon data_con       -- The representation TyCon (not family)
261
262         ----------- Worker (algebraic data types only) --------------
263         -- The *worker* for the data constructor is the function that
264         -- takes the representation arguments and builds the constructor.
265     wrk_id = mkGlobalId (DataConWorkId data_con) wkr_name
266                         (dataConRepType data_con) wkr_info
267
268     wkr_arity = dataConRepArity data_con
269     wkr_info  = noCafIdInfo
270                 `setArityInfo`          wkr_arity
271                 `setAllStrictnessInfo`  Just wkr_sig
272                 `setUnfoldingInfo`      evaldUnfolding  -- Record that it's evaluated,
273                                                         -- even if arity = 0
274
275     wkr_sig = mkStrictSig (mkTopDmdType (replicate wkr_arity topDmd) cpr_info)
276         --      Note [Data-con worker strictness]
277         -- Notice that we do *not* say the worker is strict
278         -- even if the data constructor is declared strict
279         --      e.g.    data T = MkT !(Int,Int)
280         -- Why?  Because the *wrapper* is strict (and its unfolding has case
281         -- expresssions that do the evals) but the *worker* itself is not.
282         -- If we pretend it is strict then when we see
283         --      case x of y -> $wMkT y
284         -- the simplifier thinks that y is "sure to be evaluated" (because
285         --  $wMkT is strict) and drops the case.  No, $wMkT is not strict.
286         --
287         -- When the simplifer sees a pattern 
288         --      case e of MkT x -> ...
289         -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
290         -- but that's fine... dataConRepStrictness comes from the data con
291         -- not from the worker Id.
292
293     cpr_info | isProductTyCon tycon && 
294                isDataTyCon tycon    &&
295                wkr_arity > 0        &&
296                wkr_arity <= mAX_CPR_SIZE        = retCPR
297              | otherwise                        = TopRes
298         -- RetCPR is only true for products that are real data types;
299         -- that is, not unboxed tuples or [non-recursive] newtypes
300
301         ----------- Workers for newtypes --------------
302     nt_work_id   = mkGlobalId (DataConWrapId data_con) wkr_name wrap_ty nt_work_info
303     nt_work_info = noCafIdInfo          -- The NoCaf-ness is set by noCafIdInfo
304                   `setArityInfo` 1      -- Arity 1
305                   `setUnfoldingInfo`     newtype_unf
306     id_arg1      = mkTemplateLocal 1 (head orig_arg_tys)
307     newtype_unf  = ASSERT2( isVanillaDataCon data_con &&
308                             isSingleton orig_arg_tys, ppr data_con  )
309                               -- Note [Newtype datacons]
310                    mkCompulsoryUnfolding $ 
311                    mkLams wrap_tvs $ Lam id_arg1 $ 
312                    wrapNewTypeBody tycon res_ty_args (Var id_arg1)
313
314
315         ----------- Wrapper --------------
316         -- We used to include the stupid theta in the wrapper's args
317         -- but now we don't.  Instead the type checker just injects these
318         -- extra constraints where necessary.
319     wrap_tvs    = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
320     res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
321     eq_tys   = mkPredTys eq_theta
322     dict_tys = mkPredTys dict_theta
323     wrap_ty  = mkForAllTys wrap_tvs $ mkFunTys eq_tys $ mkFunTys dict_tys $
324                mkFunTys orig_arg_tys $ res_ty
325         -- NB: watch out here if you allow user-written equality 
326         --     constraints in data constructor signatures
327
328         ----------- Wrappers for algebraic data types -------------- 
329     alg_wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty alg_wrap_info
330     alg_wrap_info = noCafIdInfo         -- The NoCaf-ness is set by noCafIdInfo
331                     `setArityInfo`         wrap_arity
332                         -- It's important to specify the arity, so that partial
333                         -- applications are treated as values
334                     `setUnfoldingInfo`     wrap_unf
335                     `setAllStrictnessInfo` Just wrap_sig
336
337     all_strict_marks = dataConExStricts data_con ++ dataConStrictMarks data_con
338     wrap_sig = mkStrictSig (mkTopDmdType arg_dmds cpr_info)
339     arg_dmds = map mk_dmd all_strict_marks
340     mk_dmd str | isMarkedStrict str = evalDmd
341                | otherwise          = lazyDmd
342         -- The Cpr info can be important inside INLINE rhss, where the
343         -- wrapper constructor isn't inlined.
344         -- And the argument strictness can be important too; we
345         -- may not inline a contructor when it is partially applied.
346         -- For example:
347         --      data W = C !Int !Int !Int
348         --      ...(let w = C x in ...(w p q)...)...
349         -- we want to see that w is strict in its two arguments
350
351     wrap_unf = mkImplicitUnfolding $ Note InlineMe $
352                mkLams wrap_tvs $ 
353                mkLams eq_args $
354                mkLams dict_args $ mkLams id_args $
355                foldr mk_case con_app 
356                      (zip (dict_args ++ id_args) all_strict_marks)
357                      i3 []
358
359     con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
360                           Var wrk_id `mkTyApps`  res_ty_args
361                                      `mkVarApps` ex_tvs                 
362                                      -- Equality evidence:
363                                      `mkTyApps`  map snd eq_spec
364                                      `mkVarApps` eq_args
365                                      `mkVarApps` reverse rep_ids
366
367     (dict_args,i2) = mkLocals 1  dict_tys
368     (id_args,i3)   = mkLocals i2 orig_arg_tys
369     wrap_arity     = i3-1
370     (eq_args,_)    = mkCoVarLocals i3 eq_tys
371
372     mkCoVarLocals i []     = ([],i)
373     mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
374                                  y      = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
375                              in (y:ys,j)
376
377     mk_case 
378            :: (Id, StrictnessMark)      -- Arg, strictness
379            -> (Int -> [Id] -> CoreExpr) -- Body
380            -> Int                       -- Next rep arg id
381            -> [Id]                      -- Rep args so far, reversed
382            -> CoreExpr
383     mk_case (arg,strict) body i rep_args
384           = case strict of
385                 NotMarkedStrict -> body i (arg:rep_args)
386                 MarkedStrict 
387                    | isUnLiftedType (idType arg) -> body i (arg:rep_args)
388                    | otherwise ->
389                         Case (Var arg) arg res_ty [(DEFAULT,[], body i (arg:rep_args))]
390
391                 MarkedUnboxed
392                    -> unboxProduct i (Var arg) (idType arg) the_body 
393                       where
394                         the_body i con_args = body i (reverse con_args ++ rep_args)
395
396 mAX_CPR_SIZE :: Arity
397 mAX_CPR_SIZE = 10
398 -- We do not treat very big tuples as CPR-ish:
399 --      a) for a start we get into trouble because there aren't 
400 --         "enough" unboxed tuple types (a tiresome restriction, 
401 --         but hard to fix), 
402 --      b) more importantly, big unboxed tuples get returned mainly
403 --         on the stack, and are often then allocated in the heap
404 --         by the caller.  So doing CPR for them may in fact make
405 --         things worse.
406
407 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
408                where
409                  n = length tys
410 \end{code}
411
412 Note [Newtype datacons]
413 ~~~~~~~~~~~~~~~~~~~~~~~
414 The "data constructor" for a newtype should always be vanilla.  At one
415 point this wasn't true, because the newtype arising from
416      class C a => D a
417 looked like
418        newtype T:D a = D:D (C a)
419 so the data constructor for T:C had a single argument, namely the
420 predicate (C a).  But now we treat that as an ordinary argument, not
421 part of the theta-type, so all is well.
422
423
424 %************************************************************************
425 %*                                                                      *
426 \subsection{Dictionary selectors}
427 %*                                                                      *
428 %************************************************************************
429
430 Selecting a field for a dictionary.  If there is just one field, then
431 there's nothing to do.  
432
433 Dictionary selectors may get nested forall-types.  Thus:
434
435         class Foo a where
436           op :: forall b. Ord b => a -> b -> b
437
438 Then the top-level type for op is
439
440         op :: forall a. Foo a => 
441               forall b. Ord b => 
442               a -> b -> b
443
444 This is unlike ordinary record selectors, which have all the for-alls
445 at the outside.  When dealing with classes it's very convenient to
446 recover the original type signature from the class op selector.
447
448 \begin{code}
449 mkDictSelId :: Bool     -- True <=> don't include the unfolding
450                         -- Little point on imports without -O, because the
451                         -- dictionary itself won't be visible
452             -> Name -> Class -> Id
453 mkDictSelId no_unf name clas
454   = mkGlobalId (ClassOpId clas) name sel_ty info
455   where
456     sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
457         -- We can't just say (exprType rhs), because that would give a type
458         --      C a -> C a
459         -- for a single-op class (after all, the selector is the identity)
460         -- But it's type must expose the representation of the dictionary
461         -- to get (say)         C a -> (a -> a)
462
463     info = noCafIdInfo
464                 `setArityInfo`          1
465                 `setAllStrictnessInfo`  Just strict_sig
466                 `setUnfoldingInfo`      (if no_unf then noUnfolding
467                                                    else mkImplicitUnfolding rhs)
468
469         -- We no longer use 'must-inline' on record selectors.  They'll
470         -- inline like crazy if they scrutinise a constructor
471
472         -- The strictness signature is of the form U(AAAVAAAA) -> T
473         -- where the V depends on which item we are selecting
474         -- It's worth giving one, so that absence info etc is generated
475         -- even if the selector isn't inlined
476     strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
477     arg_dmd | isNewTyCon tycon = evalDmd
478             | otherwise        = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
479                                             | id <- arg_ids ])
480
481     tycon      = classTyCon clas
482     [data_con] = tyConDataCons tycon
483     tyvars     = dataConUnivTyVars data_con
484     arg_tys    = {- ASSERT( isVanillaDataCon data_con ) -} dataConRepArgTys data_con
485     eq_theta   = dataConEqTheta data_con
486     the_arg_id = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` arg_ids) name
487
488     pred       = mkClassPred clas (mkTyVarTys tyvars)
489     dict_id    = mkTemplateLocal     1 $ mkPredTy pred
490     (eq_ids,n) = mkCoVarLocals 2 $ mkPredTys eq_theta
491     arg_ids    = mkTemplateLocalsNum n arg_tys
492
493     mkCoVarLocals i []     = ([],i)
494     mkCoVarLocals i (x:xs) = let (ys,j) = mkCoVarLocals (i+1) xs
495                                  y      = mkCoVar (mkSysTvName (mkBuiltinUnique i) (fsLit "dc_co")) x
496                              in (y:ys,j)
497
498     rhs = mkLams tyvars  (Lam dict_id   rhs_body)
499     rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
500              | otherwise        = Case (Var dict_id) dict_id (idType the_arg_id)
501                                        [(DataAlt data_con, eq_ids ++ arg_ids, Var the_arg_id)]
502 \end{code}
503
504
505 %************************************************************************
506 %*                                                                      *
507         Boxing and unboxing
508 %*                                                                      *
509 %************************************************************************
510
511 \begin{code}
512 -- unbox a product type...
513 -- we will recurse into newtypes, casting along the way, and unbox at the
514 -- first product data constructor we find. e.g.
515 --  
516 --   data PairInt = PairInt Int Int
517 --   newtype S = MkS PairInt
518 --   newtype T = MkT S
519 --
520 -- If we have e = MkT (MkS (PairInt 0 1)) and some body expecting a list of
521 -- ids, we get (modulo int passing)
522 --
523 --   case (e `cast` CoT) `cast` CoS of
524 --     PairInt a b -> body [a,b]
525 --
526 -- The Ints passed around are just for creating fresh locals
527 unboxProduct :: Int -> CoreExpr -> Type -> (Int -> [Id] -> CoreExpr) -> CoreExpr
528 unboxProduct i arg arg_ty body
529   = result
530   where 
531     result = mkUnpackCase the_id arg con_args boxing_con rhs
532     (_tycon, _tycon_args, boxing_con, tys) = deepSplitProductType "unboxProduct" arg_ty
533     ([the_id], i') = mkLocals i [arg_ty]
534     (con_args, i'') = mkLocals i' tys
535     rhs = body i'' con_args
536
537 mkUnpackCase ::  Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
538 -- (mkUnpackCase x e args Con body)
539 --      returns
540 -- case (e `cast` ...) of bndr { Con args -> body }
541 -- 
542 -- the type of the bndr passed in is irrelevent
543 mkUnpackCase bndr arg unpk_args boxing_con body
544   = Case cast_arg (setIdType bndr bndr_ty) (exprType body) [(DataAlt boxing_con, unpk_args, body)]
545   where
546   (cast_arg, bndr_ty) = go (idType bndr) arg
547   go ty arg 
548     | (tycon, tycon_args, _, _)  <- splitProductType "mkUnpackCase" ty
549     , isNewTyCon tycon && not (isRecursiveTyCon tycon)
550     = go (newTyConInstRhs tycon tycon_args) 
551          (unwrapNewTypeBody tycon tycon_args arg)
552     | otherwise = (arg, ty)
553
554 -- ...and the dual
555 reboxProduct :: [Unique]     -- uniques to create new local binders
556              -> Type         -- type of product to box
557              -> ([Unique],   -- remaining uniques
558                  CoreExpr,   -- boxed product
559                  [Id])       -- Ids being boxed into product
560 reboxProduct us ty
561   = let 
562         (_tycon, _tycon_args, _pack_con, con_arg_tys) = deepSplitProductType "reboxProduct" ty
563  
564         us' = dropList con_arg_tys us
565
566         arg_ids  = zipWith (mkSysLocal (fsLit "rb")) us con_arg_tys
567
568         bind_rhs = mkProductBox arg_ids ty
569
570     in
571       (us', bind_rhs, arg_ids)
572
573 mkProductBox :: [Id] -> Type -> CoreExpr
574 mkProductBox arg_ids ty 
575   = result_expr
576   where 
577     (tycon, tycon_args, pack_con, _con_arg_tys) = splitProductType "mkProductBox" ty
578
579     result_expr
580       | isNewTyCon tycon && not (isRecursiveTyCon tycon) 
581       = wrap (mkProductBox arg_ids (newTyConInstRhs tycon tycon_args))
582       | otherwise = mkConApp pack_con (map Type tycon_args ++ map Var arg_ids)
583
584     wrap expr = wrapNewTypeBody tycon tycon_args expr
585
586
587 -- (mkReboxingAlt us con xs rhs) basically constructs the case
588 -- alternative (con, xs, rhs)
589 -- but it does the reboxing necessary to construct the *source* 
590 -- arguments, xs, from the representation arguments ys.
591 -- For example:
592 --      data T = MkT !(Int,Int) Bool
593 --
594 -- mkReboxingAlt MkT [x,b] r 
595 --      = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
596 --
597 -- mkDataAlt should really be in DataCon, but it can't because
598 -- it manipulates CoreSyn.
599
600 mkReboxingAlt
601   :: [Unique] -- Uniques for the new Ids
602   -> DataCon
603   -> [Var]    -- Source-level args, including existential dicts
604   -> CoreExpr -- RHS
605   -> CoreAlt
606
607 mkReboxingAlt us con args rhs
608   | not (any isMarkedUnboxed stricts)
609   = (DataAlt con, args, rhs)
610
611   | otherwise
612   = let
613         (binds, args') = go args stricts us
614     in
615     (DataAlt con, args', mkLets binds rhs)
616
617   where
618     stricts = dataConExStricts con ++ dataConStrictMarks con
619
620     go [] _stricts _us = ([], [])
621
622     -- Type variable case
623     go (arg:args) stricts us 
624       | isTyVar arg
625       = let (binds, args') = go args stricts us
626         in  (binds, arg:args')
627
628         -- Term variable case
629     go (arg:args) (str:stricts) us
630       | isMarkedUnboxed str
631       = 
632         let (binds, unpacked_args')        = go args stricts us'
633             (us', bind_rhs, unpacked_args) = reboxProduct us (idType arg)
634         in
635             (NonRec arg bind_rhs : binds, unpacked_args ++ unpacked_args')
636       | otherwise
637       = let (binds, args') = go args stricts us
638         in  (binds, arg:args')
639     go (_ : _) [] _ = panic "mkReboxingAlt"
640 \end{code}
641
642
643 %************************************************************************
644 %*                                                                      *
645         Wrapping and unwrapping newtypes and type families
646 %*                                                                      *
647 %************************************************************************
648
649 \begin{code}
650 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
651 -- The wrapper for the data constructor for a newtype looks like this:
652 --      newtype T a = MkT (a,Int)
653 --      MkT :: forall a. (a,Int) -> T a
654 --      MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
655 -- where CoT is the coercion TyCon assoicated with the newtype
656 --
657 -- The call (wrapNewTypeBody T [a] e) returns the
658 -- body of the wrapper, namely
659 --      e `cast` (CoT [a])
660 --
661 -- If a coercion constructor is provided in the newtype, then we use
662 -- it, otherwise the wrap/unwrap are both no-ops 
663 --
664 -- If the we are dealing with a newtype *instance*, we have a second coercion
665 -- identifying the family instance with the constructor of the newtype
666 -- instance.  This coercion is applied in any case (ie, composed with the
667 -- coercion constructor of the newtype or applied by itself).
668
669 wrapNewTypeBody tycon args result_expr
670   = wrapFamInstBody tycon args inner
671   where
672     inner
673       | Just co_con <- newTyConCo_maybe tycon
674       = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
675       | otherwise
676       = result_expr
677
678 -- When unwrapping, we do *not* apply any family coercion, because this will
679 -- be done via a CoPat by the type checker.  We have to do it this way as
680 -- computing the right type arguments for the coercion requires more than just
681 -- a spliting operation (cf, TcPat.tcConPat).
682
683 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
684 unwrapNewTypeBody tycon args result_expr
685   | Just co_con <- newTyConCo_maybe tycon
686   = mkCoerce (mkTyConApp co_con args) result_expr
687   | otherwise
688   = result_expr
689
690 -- If the type constructor is a representation type of a data instance, wrap
691 -- the expression into a cast adjusting the expression type, which is an
692 -- instance of the representation type, to the corresponding instance of the
693 -- family instance type.
694 -- See Note [Wrappers for data instance tycons]
695 wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
696 wrapFamInstBody tycon args body
697   | Just co_con <- tyConFamilyCoercion_maybe tycon
698   = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
699   | otherwise
700   = body
701
702 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
703 unwrapFamInstScrut tycon args scrut
704   | Just co_con <- tyConFamilyCoercion_maybe tycon
705   = mkCoerce (mkTyConApp co_con args) scrut
706   | otherwise
707   = scrut
708 \end{code}
709
710
711 %************************************************************************
712 %*                                                                      *
713 \subsection{Primitive operations}
714 %*                                                                      *
715 %************************************************************************
716
717 \begin{code}
718 mkPrimOpId :: PrimOp -> Id
719 mkPrimOpId prim_op 
720   = id
721   where
722     (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
723     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
724     name = mkWiredInName gHC_PRIM (primOpOcc prim_op) 
725                          (mkPrimOpIdUnique (primOpTag prim_op))
726                          (AnId id) UserSyntax
727     id   = mkGlobalId (PrimOpId prim_op) name ty info
728                 
729     info = noCafIdInfo
730            `setSpecInfo`          mkSpecInfo (primOpRules prim_op name)
731            `setArityInfo`         arity
732            `setAllStrictnessInfo` Just strict_sig
733
734 -- For each ccall we manufacture a separate CCallOpId, giving it
735 -- a fresh unique, a type that is correct for this particular ccall,
736 -- and a CCall structure that gives the correct details about calling
737 -- convention etc.  
738 --
739 -- The *name* of this Id is a local name whose OccName gives the full
740 -- details of the ccall, type and all.  This means that the interface 
741 -- file reader can reconstruct a suitable Id
742
743 mkFCallId :: Unique -> ForeignCall -> Type -> Id
744 mkFCallId uniq fcall ty
745   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
746     -- A CCallOpId should have no free type variables; 
747     -- when doing substitutions won't substitute over it
748     mkGlobalId (FCallId fcall) name ty info
749   where
750     occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
751     -- The "occurrence name" of a ccall is the full info about the
752     -- ccall; it is encoded, but may have embedded spaces etc!
753
754     name = mkFCallName uniq occ_str
755
756     info = noCafIdInfo
757            `setArityInfo`         arity
758            `setAllStrictnessInfo` Just strict_sig
759
760     (_, tau)     = tcSplitForAllTys ty
761     (arg_tys, _) = tcSplitFunTys tau
762     arity        = length arg_tys
763     strict_sig   = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
764
765 -- Tick boxes and breakpoints are both represented as TickBoxOpIds,
766 -- except for the type:
767 --
768 --    a plain HPC tick box has type (State# RealWorld)
769 --    a breakpoint Id has type forall a.a
770 --
771 -- The breakpoint Id will be applied to a list of arbitrary free variables,
772 -- which is why it needs a polymorphic type.
773
774 mkTickBoxOpId :: Unique -> Module -> TickBoxId -> Id
775 mkTickBoxOpId uniq mod ix = mkTickBox' uniq mod ix realWorldStatePrimTy
776
777 mkBreakPointOpId :: Unique -> Module -> TickBoxId -> Id
778 mkBreakPointOpId uniq mod ix = mkTickBox' uniq mod ix ty
779  where ty = mkSigmaTy [openAlphaTyVar] [] openAlphaTy
780
781 mkTickBox' uniq mod ix ty = mkGlobalId (TickBoxOpId tickbox) name ty info    
782   where
783     tickbox = TickBox mod ix
784     occ_str = showSDoc (braces (ppr tickbox))
785     name    = mkTickBoxOpName uniq occ_str
786     info    = noCafIdInfo
787 \end{code}
788
789
790 %************************************************************************
791 %*                                                                      *
792 \subsection{DictFuns and default methods}
793 %*                                                                      *
794 %************************************************************************
795
796 Important notes about dict funs and default methods
797 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
798 Dict funs and default methods are *not* ImplicitIds.  Their definition
799 involves user-written code, so we can't figure out their strictness etc
800 based on fixed info, as we can for constructors and record selectors (say).
801
802 We build them as LocalIds, but with External Names.  This ensures that
803 they are taken to account by free-variable finding and dependency
804 analysis (e.g. CoreFVs.exprFreeVars).
805
806 Why shouldn't they be bound as GlobalIds?  Because, in particular, if
807 they are globals, the specialiser floats dict uses above their defns,
808 which prevents good simplifications happening.  Also the strictness
809 analyser treats a occurrence of a GlobalId as imported and assumes it
810 contains strictness in its IdInfo, which isn't true if the thing is
811 bound in the same module as the occurrence.
812
813 It's OK for dfuns to be LocalIds, because we form the instance-env to
814 pass on to the next module (md_insts) in CoreTidy, afer tidying
815 and globalising the top-level Ids.
816
817 BUT make sure they are *exported* LocalIds (mkExportedLocalId) so 
818 that they aren't discarded by the occurrence analyser.
819
820 \begin{code}
821 mkDefaultMethodId dm_name ty = mkExportedLocalId dm_name ty
822
823 mkDictFunId :: Name      -- Name to use for the dict fun;
824             -> [TyVar]
825             -> ThetaType
826             -> Class 
827             -> [Type]
828             -> Id
829
830 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
831   = mkExportedLocalVar DFunId dfun_name dfun_ty vanillaIdInfo
832   where
833     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
834 \end{code}
835
836
837 %************************************************************************
838 %*                                                                      *
839 \subsection{Un-definable}
840 %*                                                                      *
841 %************************************************************************
842
843 These Ids can't be defined in Haskell.  They could be defined in
844 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
845 ensure that they were definitely, definitely inlined, because there is
846 no curried identifier for them.  That's what mkCompulsoryUnfolding
847 does.  If we had a way to get a compulsory unfolding from an interface
848 file, we could do that, but we don't right now.
849
850 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
851 just gets expanded into a type coercion wherever it occurs.  Hence we
852 add it as a built-in Id with an unfolding here.
853
854 The type variables we use here are "open" type variables: this means
855 they can unify with both unlifted and lifted types.  Hence we provide
856 another gun with which to shoot yourself in the foot.
857
858 \begin{code}
859 mkWiredInIdName mod fs uniq id
860  = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
861
862 unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey  unsafeCoerceId
863 nullAddrName     = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#")     nullAddrIdKey      nullAddrId
864 seqName          = mkWiredInIdName gHC_PRIM (fsLit "seq")           seqIdKey           seqId
865 realWorldName    = mkWiredInIdName gHC_PRIM (fsLit "realWorld#")    realWorldPrimIdKey realWorldPrimId
866 lazyIdName       = mkWiredInIdName gHC_BASE (fsLit "lazy")         lazyIdKey           lazyId
867
868 errorName                = mkWiredInIdName gHC_ERR (fsLit "error")            errorIdKey eRROR_ID
869 recSelErrorName          = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recSelError")     recSelErrorIdKey rEC_SEL_ERROR_ID
870 runtimeErrorName         = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "runtimeError")    runtimeErrorIdKey rUNTIME_ERROR_ID
871 irrefutPatErrorName      = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "irrefutPatError") irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
872 recConErrorName          = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "recConError")     recConErrorIdKey rEC_CON_ERROR_ID
873 patErrorName             = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "patError")         patErrorIdKey pAT_ERROR_ID
874 noMethodBindingErrorName = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "noMethodBindingError")
875                                            noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
876 nonExhaustiveGuardsErrorName 
877   = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit "nonExhaustiveGuardsError") 
878                     nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
879 \end{code}
880
881 \begin{code}
882 ------------------------------------------------
883 -- unsafeCoerce# :: forall a b. a -> b
884 unsafeCoerceId
885   = pcMiscPrelId unsafeCoerceName ty info
886   where
887     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
888            
889
890     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
891                       (mkFunTy openAlphaTy openBetaTy)
892     [x] = mkTemplateLocals [openAlphaTy]
893     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
894           Cast (Var x) (mkUnsafeCoercion openAlphaTy openBetaTy)
895
896 ------------------------------------------------
897 nullAddrId :: Id
898 -- nullAddr# :: Addr#
899 -- The reason is is here is because we don't provide 
900 -- a way to write this literal in Haskell.
901 nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info
902   where
903     info = noCafIdInfo `setUnfoldingInfo` 
904            mkCompulsoryUnfolding (Lit nullAddrLit)
905
906 ------------------------------------------------
907 seqId :: Id     -- See Note [seqId magic]
908 seqId = pcMiscPrelId seqName ty info
909   where
910     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
911            
912
913     ty  = mkForAllTys [alphaTyVar,openBetaTyVar]
914                       (mkFunTy alphaTy (mkFunTy openBetaTy openBetaTy))
915     [x,y] = mkTemplateLocals [alphaTy, openBetaTy]
916     rhs = mkLams [alphaTyVar,openBetaTyVar,x,y] (Case (Var x) x openBetaTy [(DEFAULT, [], Var y)])
917
918 ------------------------------------------------
919 lazyId :: Id    -- See Note [lazyId magic]
920 lazyId = pcMiscPrelId lazyIdName ty info
921   where
922     info = noCafIdInfo
923     ty  = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
924 \end{code}
925
926 Note [seqId magic]
927 ~~~~~~~~~~~~~~~~~~
928 'seq' is special in several ways.  
929
930 a) Its second arg can have an unboxed type
931       x `seq` (v +# w)
932
933 b) Its fixity is set in LoadIface.ghcPrimIface
934
935 c) It has quite a bit of desugaring magic. 
936    See DsUtils.lhs Note [Desugaring seq (1)] and (2) and (3)
937
938 d) There is some special rule handing: Note [RULES for seq]
939
940 Note [Rules for seq]
941 ~~~~~~~~~~~~~~~~~~~~
942 Roman found situations where he had
943       case (f n) of _ -> e
944 where he knew that f (which was strict in n) would terminate if n did.
945 Notice that the result of (f n) is discarded. So it makes sense to
946 transform to
947       case n of _ -> e
948
949 Rather than attempt some general analysis to support this, I've added
950 enough support that you can do this using a rewrite rule:
951
952   RULE "f/seq" forall n.  seq (f n) e = seq n e
953
954 You write that rule.  When GHC sees a case expression that discards
955 its result, it mentally transforms it to a call to 'seq' and looks for
956 a RULE.  (This is done in Simplify.rebuildCase.)  As usual, the
957 correctness of the rule is up to you.
958
959 To make this work, we need to be careful that the magical desugaring
960 done in Note [seqId magic] item (c) is *not* done on the LHS of a rule.
961 Or rather, we arrange to un-do it, in DsBinds.decomposeRuleLhs.
962
963
964 Note [lazyId magic]
965 ~~~~~~~~~~~~~~~~~~~
966     lazy :: forall a?. a? -> a?   (i.e. works for unboxed types too)
967
968 Used to lazify pseq:   pseq a b = a `seq` lazy b
969
970 Also, no strictness: by being a built-in Id, all the info about lazyId comes from here,
971 not from GHC.Base.hi.   This is important, because the strictness
972 analyser will spot it as strict!
973
974 Also no unfolding in lazyId: it gets "inlined" by a HACK in CorePrep.
975 It's very important to do this inlining *after* unfoldings are exposed 
976 in the interface file.  Otherwise, the unfolding for (say) pseq in the
977 interface file will not mention 'lazy', so if we inline 'pseq' we'll totally
978 miss the very thing that 'lazy' was there for in the first place.
979 See Trac #3259 for a real world example.
980
981 lazyId is defined in GHC.Base, so we don't *have* to inline it.  If it
982 appears un-applied, we'll end up just calling it.
983
984 -------------------------------------------------------------
985 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
986 nasty as-is, change it back to a literal (@Literal@).
987
988 voidArgId is a Local Id used simply as an argument in functions
989 where we just want an arg to avoid having a thunk of unlifted type.
990 E.g.
991         x = \ void :: State# RealWorld -> (# p, q #)
992
993 This comes up in strictness analysis
994
995 \begin{code}
996 realWorldPrimId -- :: State# RealWorld
997   = pcMiscPrelId realWorldName realWorldStatePrimTy
998                  (noCafIdInfo `setUnfoldingInfo` evaldUnfolding)
999         -- The evaldUnfolding makes it look that realWorld# is evaluated
1000         -- which in turn makes Simplify.interestingArg return True,
1001         -- which in turn makes INLINE things applied to realWorld# likely
1002         -- to be inlined
1003
1004 voidArgId :: Id
1005 voidArgId       -- :: State# RealWorld
1006   = mkSysLocal (fsLit "void") voidArgIdKey realWorldStatePrimTy
1007 \end{code}
1008
1009
1010 %************************************************************************
1011 %*                                                                      *
1012 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
1013 %*                                                                      *
1014 %************************************************************************
1015
1016 GHC randomly injects these into the code.
1017
1018 @patError@ is just a version of @error@ for pattern-matching
1019 failures.  It knows various ``codes'' which expand to longer
1020 strings---this saves space!
1021
1022 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
1023 well shouldn't be yanked on, but if one is, then you will get a
1024 friendly message from @absentErr@ (rather than a totally random
1025 crash).
1026
1027 @parError@ is a special version of @error@ which the compiler does
1028 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
1029 templates, but we don't ever expect to generate code for it.
1030
1031 \begin{code}
1032 mkRuntimeErrorApp 
1033         :: Id           -- Should be of type (forall a. Addr# -> a)
1034                         --      where Addr# points to a UTF8 encoded string
1035         -> Type         -- The type to instantiate 'a'
1036         -> String       -- The string to print
1037         -> CoreExpr
1038
1039 mkRuntimeErrorApp err_id res_ty err_msg 
1040   = mkApps (Var err_id) [Type res_ty, err_string]
1041   where
1042     err_string = Lit (mkMachString err_msg)
1043
1044 mkImpossibleExpr :: Type -> CoreExpr
1045 mkImpossibleExpr res_ty
1046   = mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty "Impossible case alternative"
1047
1048 rEC_SEL_ERROR_ID                = mkRuntimeErrorId recSelErrorName
1049 rUNTIME_ERROR_ID                = mkRuntimeErrorId runtimeErrorName
1050 iRREFUT_PAT_ERROR_ID            = mkRuntimeErrorId irrefutPatErrorName
1051 rEC_CON_ERROR_ID                = mkRuntimeErrorId recConErrorName
1052 pAT_ERROR_ID                    = mkRuntimeErrorId patErrorName
1053 nO_METHOD_BINDING_ERROR_ID      = mkRuntimeErrorId noMethodBindingErrorName
1054 nON_EXHAUSTIVE_GUARDS_ERROR_ID  = mkRuntimeErrorId nonExhaustiveGuardsErrorName
1055
1056 -- The runtime error Ids take a UTF8-encoded string as argument
1057
1058 mkRuntimeErrorId :: Name -> Id
1059 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
1060
1061 runtimeErrorTy :: Type
1062 runtimeErrorTy = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
1063 \end{code}
1064
1065 \begin{code}
1066 eRROR_ID = pc_bottoming_Id errorName errorTy
1067
1068 errorTy  :: Type
1069 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
1070     -- Notice the openAlphaTyVar.  It says that "error" can be applied
1071     -- to unboxed as well as boxed types.  This is OK because it never
1072     -- returns, so the return type is irrelevant.
1073 \end{code}
1074
1075
1076 %************************************************************************
1077 %*                                                                      *
1078 \subsection{Utilities}
1079 %*                                                                      *
1080 %************************************************************************
1081
1082 \begin{code}
1083 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
1084 pcMiscPrelId name ty info
1085   = mkVanillaGlobalWithInfo name ty info
1086     -- We lie and say the thing is imported; otherwise, we get into
1087     -- a mess with dependency analysis; e.g., core2stg may heave in
1088     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
1089     -- being compiled, then it's just a matter of luck if the definition
1090     -- will be in "the right place" to be in scope.
1091
1092 pc_bottoming_Id :: Name -> Type -> Id
1093 -- Function of arity 1, which diverges after being given one argument
1094 pc_bottoming_Id name ty
1095  = pcMiscPrelId name ty bottoming_info
1096  where
1097     bottoming_info = vanillaIdInfo `setAllStrictnessInfo` Just strict_sig
1098                                    `setArityInfo`         1
1099                         -- Make arity and strictness agree
1100
1101         -- Do *not* mark them as NoCafRefs, because they can indeed have
1102         -- CAF refs.  For example, pAT_ERROR_ID calls GHC.Err.untangle,
1103         -- which has some CAFs
1104         -- In due course we may arrange that these error-y things are
1105         -- regarded by the GC as permanently live, in which case we
1106         -- can give them NoCaf info.  As it is, any function that calls
1107         -- any pc_bottoming_Id will itself have CafRefs, which bloats
1108         -- SRTs.
1109
1110     strict_sig = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1111         -- These "bottom" out, no matter what their arguments
1112 \end{code}
1113