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