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