[project @ 2000-05-25 12:41:14 by simonpj]
[ghc-hetmet.git] / ghc / compiler / basicTypes / MkId.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4 \section[StdIdInfo]{Standard unfoldings}
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         mkSpecPragmaId, mkWorkerId,
17
18         mkDictFunId, mkDefaultMethodId,
19         mkDictSelId,
20
21         mkDataConId, mkDataConWrapId,
22         mkRecordSelId,
23         mkPrimOpId, mkCCallOpId,
24
25         -- And some particular Ids; see below for why they are wired in
26         wiredInIds,
27         unsafeCoerceId, realWorldPrimId,
28         eRROR_ID, rEC_SEL_ERROR_ID, pAT_ERROR_ID, rEC_CON_ERROR_ID,
29         rEC_UPD_ERROR_ID, iRREFUT_PAT_ERROR_ID, nON_EXHAUSTIVE_GUARDS_ERROR_ID,
30         nO_METHOD_BINDING_ERROR_ID, aBSENT_ERROR_ID, pAR_ERROR_ID
31     ) where
32
33 #include "HsVersions.h"
34
35
36 import TysPrim          ( openAlphaTyVars, alphaTyVar, alphaTy, 
37                           intPrimTy, realWorldStatePrimTy
38                         )
39 import TysWiredIn       ( boolTy, charTy, mkListTy )
40 import PrelNames        ( pREL_ERR, pREL_GHC )
41 import PrelRules        ( primOpRule )
42 import Rules            ( addRule )
43 import Type             ( Type, ClassContext, mkDictTy, mkDictTys, mkTyConApp, mkTyVarTys,
44                           mkFunTys, mkFunTy, mkSigmaTy, classesToPreds,
45                           isUnLiftedType, mkForAllTys, mkTyVarTy, tyVarsOfType, tyVarsOfTypes,
46                           splitSigmaTy, splitFunTy_maybe, 
47                           splitFunTys, splitForAllTys, unUsgTy,
48                           mkUsgTy, UsageAnn(..)
49                         )
50 import PprType          ( pprParendType )
51 import Module           ( Module )
52 import CoreUtils        ( exprType, mkInlineMe )
53 import CoreUnfold       ( mkTopUnfolding, mkCompulsoryUnfolding, mkOtherCon )
54 import Literal          ( Literal(..) )
55 import Subst            ( mkTopTyVarSubst, substClasses )
56 import TyCon            ( TyCon, isNewTyCon, tyConTyVars, tyConDataCons, isDataTyCon, 
57                           tyConTheta, isProductTyCon, isUnboxedTupleTyCon )
58 import Class            ( Class, classBigSig, classTyCon, classTyVars, classSelIds )
59 import Var              ( Id, TyVar )
60 import VarSet           ( isEmptyVarSet )
61 import Name             ( mkDerivedName, mkWiredInIdName, mkLocalName, 
62                           mkWorkerOcc, mkSuperDictSelOcc, mkCCallName,
63                           Name, NamedThing(..),
64                         )
65 import OccName          ( mkSrcVarOcc )
66 import PrimOp           ( PrimOp(DataToTagOp, CCallOp), 
67                           primOpSig, mkPrimOpIdName,
68                           CCall, pprCCallOp
69                         )
70 import Demand           ( wwStrict, wwPrim, mkStrictnessInfo )
71 import DataCon          ( DataCon, StrictnessMark(..), 
72                           dataConFieldLabels, dataConRepArity, dataConTyCon,
73                           dataConArgTys, dataConRepType, dataConRepStrictness, 
74                           dataConName, dataConTheta,
75                           dataConSig, dataConStrictMarks, dataConId
76                         )
77 import Id               ( idType, mkId,
78                           mkVanillaId, mkTemplateLocals,
79                           mkTemplateLocal, setInlinePragma, idCprInfo
80                         )
81 import IdInfo           ( IdInfo, vanillaIdInfo, mkIdInfo,
82                           exactArity, setUnfoldingInfo, setCafInfo, setCprInfo,
83                           setArityInfo, setInlinePragInfo, setSpecInfo,
84                           mkStrictnessInfo, setStrictnessInfo,
85                           IdFlavour(..), InlinePragInfo(..), CafInfo(..), StrictnessInfo(..), CprInfo(..)
86                         )
87 import FieldLabel       ( FieldLabel, FieldLabelTag, mkFieldLabel, fieldLabelName, 
88                           firstFieldLabelTag, allFieldLabelTags, fieldLabelType
89                         )
90 import CoreSyn
91 import Maybes
92 import BasicTypes       ( Arity )
93 import Unique
94 import Maybe            ( isJust )
95 import Outputable
96 import Util             ( assoc )
97 import List             ( nub )
98 \end{code}              
99
100
101 %************************************************************************
102 %*                                                                      *
103 \subsection{Wired in Ids}
104 %*                                                                      *
105 %************************************************************************
106
107 \begin{code}
108 wiredInIds
109   = [   -- These error-y things are wired in because we don't yet have
110         -- a way to express in an interface file that the result type variable
111         -- is 'open'; that is can be unified with an unboxed type
112         -- 
113         -- [The interface file format now carry such information, but there's
114         --  no way yet of expressing at the definition site for these error-reporting
115         --  functions that they have an 'open' result type. -- sof 1/99]
116
117       aBSENT_ERROR_ID
118     , eRROR_ID
119     , iRREFUT_PAT_ERROR_ID
120     , nON_EXHAUSTIVE_GUARDS_ERROR_ID
121     , nO_METHOD_BINDING_ERROR_ID
122     , pAR_ERROR_ID
123     , pAT_ERROR_ID
124     , rEC_CON_ERROR_ID
125     , rEC_UPD_ERROR_ID
126
127         -- These two can't be defined in Haskell
128     , realWorldPrimId
129     , unsafeCoerceId
130     , getTagId
131     ]
132 \end{code}
133
134 %************************************************************************
135 %*                                                                      *
136 \subsection{Easy ones}
137 %*                                                                      *
138 %************************************************************************
139
140 \begin{code}
141 mkSpecPragmaId occ uniq ty loc
142   = mkId (mkLocalName uniq occ loc) ty (mkIdInfo SpecPragmaId)
143         -- Maybe a SysLocal?  But then we'd lose the location
144
145 mkDefaultMethodId dm_name rec_c ty
146   = mkVanillaId dm_name ty
147
148 mkWorkerId uniq unwrkr ty
149   = mkVanillaId (mkDerivedName mkWorkerOcc (getName unwrkr) uniq) ty
150 \end{code}
151
152 %************************************************************************
153 %*                                                                      *
154 \subsection{Data constructors}
155 %*                                                                      *
156 %************************************************************************
157
158 \begin{code}
159 mkDataConId :: Name -> DataCon -> Id
160         -- Makes the *worker* for the data constructor; that is, the function
161         -- that takes the reprsentation arguments and builds the constructor.
162 mkDataConId work_name data_con
163   = mkId work_name (dataConRepType data_con) info
164   where
165     info = mkIdInfo (DataConId data_con)
166            `setArityInfo`       exactArity arity
167            `setStrictnessInfo`  strict_info
168            `setCprInfo`         cpr_info
169
170     arity = dataConRepArity data_con
171
172     strict_info = mkStrictnessInfo (dataConRepStrictness data_con, False)
173
174     cpr_info | isProductTyCon tycon && 
175                not (isUnboxedTupleTyCon tycon) && 
176                arity > 0                        = ReturnsCPR
177              | otherwise                        = NoCPRInfo
178              where
179                 tycon = dataConTyCon data_con
180                 -- Newtypes don't have a worker at all
181                 -- 
182                 -- If we are a product with 0 args we must be void(like)
183                 -- We can't create an unboxed tuple with 0 args for this
184                 -- and since Void has only one, constant value it should 
185                 -- just mean returning a pointer to a pre-existing cell. 
186                 -- So we won't really gain from doing anything fancy
187                 -- and we treat this case as Top.
188 \end{code}
189
190 The wrapper for a constructor is an ordinary top-level binding that evaluates
191 any strict args, unboxes any args that are going to be flattened, and calls
192 the worker.
193
194 We're going to build a constructor that looks like:
195
196         data (Data a, C b) =>  T a b = T1 !a !Int b
197
198         T1 = /\ a b -> 
199              \d1::Data a, d2::C b ->
200              \p q r -> case p of { p ->
201                        case q of { q ->
202                        Con T1 [a,b] [p,q,r]}}
203
204 Notice that
205
206 * d2 is thrown away --- a context in a data decl is used to make sure
207   one *could* construct dictionaries at the site the constructor
208   is used, but the dictionary isn't actually used.
209
210 * We have to check that we can construct Data dictionaries for
211   the types a and Int.  Once we've done that we can throw d1 away too.
212
213 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
214   all that matters is that the arguments are evaluated.  "seq" is 
215   very careful to preserve evaluation order, which we don't need
216   to be here.
217
218   You might think that we could simply give constructors some strictness
219   info, like PrimOps, and let CoreToStg do the let-to-case transformation.
220   But we don't do that because in the case of primops and functions strictness
221   is a *property* not a *requirement*.  In the case of constructors we need to
222   do something active to evaluate the argument.
223
224   Making an explicit case expression allows the simplifier to eliminate
225   it in the (common) case where the constructor arg is already evaluated.
226
227 \begin{code}
228 mkDataConWrapId data_con
229   = wrap_id
230   where
231     wrap_id = mkId (dataConName data_con) wrap_ty info
232     work_id = dataConId data_con
233
234     info = mkIdInfo (DataConWrapId data_con)
235            `setUnfoldingInfo`   mkTopUnfolding (mkInlineMe wrap_rhs)
236            `setCprInfo`         cpr_info
237                 -- The Cpr info can be important inside INLINE rhss, where the
238                 -- wrapper constructor isn't inlined
239            `setArityInfo`       exactArity arity
240                 -- It's important to specify the arity, so that partial
241                 -- applications are treated as values
242            `setCafInfo`       NoCafRefs
243                 -- The wrapper Id ends up in STG code as an argument,
244                 -- sometimes before its definition, so we want to
245                 -- signal that it has no CAFs
246
247     wrap_ty = mkForAllTys all_tyvars $
248               mkFunTys all_arg_tys
249               result_ty
250
251     cpr_info = idCprInfo work_id
252
253     wrap_rhs | isNewTyCon tycon
254              = ASSERT( null ex_tyvars && null ex_dict_args && length orig_arg_tys == 1 )
255                 -- No existentials on a newtype, but it can have a contex
256                 -- e.g.         newtype Eq a => T a = MkT (...)
257
258                mkLams tyvars $ mkLams dict_args $ Lam id_arg1 $
259                Note (Coerce result_ty (head orig_arg_tys)) (Var id_arg1)
260
261 {-      I nuked this because map (:) xs would create a
262         new local lambda for the (:) in core-to-stg.  
263         There isn't a defn for the worker!
264
265              | null dict_args && all not_marked_strict strict_marks
266              = Var work_id      -- The common case.  Not only is this efficient,
267                                 -- but it also ensures that the wrapper is replaced
268                                 -- by the worker even when there are no args.
269                                 --              f (:) x
270                                 -- becomes 
271                                 --              f $w: x
272                                 -- This is really important in rule matching,
273                                 -- which is a bit sad.  (We could match on the wrappers,
274                                 -- but that makes it less likely that rules will match
275                                 -- when we bring bits of unfoldings together
276 -}
277
278              | otherwise
279              = mkLams all_tyvars $ mkLams dict_args $ 
280                mkLams ex_dict_args $ mkLams id_args $
281                foldr mk_case con_app 
282                      (zip (ex_dict_args++id_args) strict_marks) i3 []
283
284     con_app i rep_ids = mkApps (Var work_id)
285                                (map varToCoreExpr (all_tyvars ++ reverse rep_ids))
286
287     (tyvars, theta, ex_tyvars, ex_theta, orig_arg_tys, tycon) = dataConSig data_con
288     all_tyvars   = tyvars ++ ex_tyvars
289
290     dict_tys     = mkDictTys theta
291     ex_dict_tys  = mkDictTys ex_theta
292     all_arg_tys  = dict_tys ++ ex_dict_tys ++ orig_arg_tys
293     result_ty    = mkTyConApp tycon (mkTyVarTys tyvars)
294
295     mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
296                    where
297                      n = length tys
298
299     (dict_args, i1)    = mkLocals 1  dict_tys
300     (ex_dict_args,i2)  = mkLocals i1 ex_dict_tys
301     (id_args,i3)       = mkLocals i2 orig_arg_tys
302     arity              = i3-1
303     (id_arg1:_)   = id_args             -- Used for newtype only
304
305     strict_marks  = dataConStrictMarks data_con
306     not_marked_strict NotMarkedStrict = True
307     not_marked_strict other           = False
308
309
310     mk_case 
311            :: (Id, StrictnessMark)      -- arg, strictness
312            -> (Int -> [Id] -> CoreExpr) -- body
313            -> Int                       -- next rep arg id
314            -> [Id]                      -- rep args so far
315            -> CoreExpr
316     mk_case (arg,strict) body i rep_args
317           = case strict of
318                 NotMarkedStrict -> body i (arg:rep_args)
319                 MarkedStrict 
320                    | isUnLiftedType (idType arg) -> body i (arg:rep_args)
321                    | otherwise ->
322                         Case (Var arg) arg [(DEFAULT,[], body i (arg:rep_args))]
323
324                 MarkedUnboxed con tys ->
325                    Case (Var arg) arg [(DataAlt con, con_args,
326                                         body i' (reverse con_args++rep_args))]
327                    where n_tys = length tys
328                          (con_args,i') = mkLocals i tys
329 \end{code}
330
331
332 %************************************************************************
333 %*                                                                      *
334 \subsection{Record selectors}
335 %*                                                                      *
336 %************************************************************************
337
338 We're going to build a record selector unfolding that looks like this:
339
340         data T a b c = T1 { ..., op :: a, ...}
341                      | T2 { ..., op :: a, ...}
342                      | T3
343
344         sel = /\ a b c -> \ d -> case d of
345                                     T1 ... x ... -> x
346                                     T2 ... x ... -> x
347                                     other        -> error "..."
348
349 Similarly for newtypes
350
351         newtype N a = MkN { unN :: a->a }
352
353         unN :: N a -> a -> a
354         unN n = coerce (a->a) n
355         
356 We need to take a little care if the field has a polymorphic type:
357
358         data R = R { f :: forall a. a->a }
359
360 Then we want
361
362         f :: forall a. R -> a -> a
363         f = /\ a \ r = case r of
364                           R f -> f a
365
366 (not f :: R -> forall a. a->a, which gives the type inference mechanism 
367 problems at call sites)
368
369 Similarly for newtypes
370
371         newtype N = MkN { unN :: forall a. a->a }
372
373         unN :: forall a. N -> a -> a
374         unN = /\a -> \n:N -> coerce (a->a) n
375
376 \begin{code}
377 mkRecordSelId tycon field_label unpack_id
378         -- Assumes that all fields with the same field label have the same type
379         --
380         -- Annoyingly, we have to pass in the unpackCString# Id, because
381         -- we can't conjure it up out of thin air
382   = sel_id
383   where
384     sel_id     = mkId (fieldLabelName field_label) selector_ty info
385
386     field_ty   = fieldLabelType field_label
387     field_name = fieldLabelName field_label
388     data_cons  = tyConDataCons tycon
389     tyvars     = tyConTyVars tycon      -- These scope over the types in 
390                                         -- the FieldLabels of constructors of this type
391     tycon_theta = tyConTheta tycon      -- The context on the data decl
392                                         --   eg data (Eq a, Ord b) => T a b = ...
393     (field_tyvars,field_tau) = splitForAllTys field_ty
394
395     data_ty   = mkTyConApp tycon tyvar_tys
396     tyvar_tys = mkTyVarTys tyvars
397
398         -- Very tiresomely, the selectors are (unnecessarily!) overloaded over
399         -- just the dictionaries in the types of the constructors that contain
400         -- the relevant field.  Urgh.  
401         -- NB: this code relies on the fact that DataCons are quantified over
402         -- the identical type variables as their parent TyCon
403     dict_tys  = [mkDictTy cls tys | (cls, tys) <- tycon_theta, needed_dict (cls, tys)]
404     needed_dict pred = or [ pred `elem` (dataConTheta dc) 
405                           | (DataAlt dc, _, _) <- the_alts]
406
407     selector_ty :: Type
408     selector_ty  = mkForAllTys tyvars $ mkForAllTys field_tyvars $
409                    mkFunTys dict_tys $  mkFunTy data_ty field_tau
410       
411     info = mkIdInfo (RecordSelId field_label)
412            `setArityInfo`       exactArity 1
413            `setUnfoldingInfo`   unfolding       
414            `setCafInfo`         NoCafRefs
415         -- ToDo: consider adding further IdInfo
416
417     unfolding = mkTopUnfolding sel_rhs
418
419         
420     (data_id:dict_ids) = mkTemplateLocals (data_ty:dict_tys)
421     alts      = map mk_maybe_alt data_cons
422     the_alts  = catMaybes alts
423     default_alt | all isJust alts = []  -- No default needed
424                 | otherwise       = [(DEFAULT, [], error_expr)]
425
426     sel_rhs | isNewTyCon tycon = new_sel_rhs
427             | otherwise        = data_sel_rhs
428
429     data_sel_rhs = mkLams tyvars $ mkLams field_tyvars $ 
430                    mkLams dict_ids $ Lam data_id $
431                    Case (Var data_id) data_id (the_alts ++ default_alt)
432
433     new_sel_rhs  = mkLams tyvars $ mkLams field_tyvars $ Lam data_id $
434                     Note (Coerce (unUsgTy field_tau) (unUsgTy data_ty)) (Var data_id)
435
436     mk_maybe_alt data_con 
437           = case maybe_the_arg_id of
438                 Nothing         -> Nothing
439                 Just the_arg_id -> Just (DataAlt data_con, arg_ids, 
440                                          mkVarApps (Var the_arg_id) field_tyvars)
441           where
442             arg_ids          = mkTemplateLocals (dataConArgTys data_con tyvar_tys)
443                                     -- The first one will shadow data_id, but who cares
444             field_lbls       = dataConFieldLabels data_con
445             maybe_the_arg_id = assocMaybe (field_lbls `zip` arg_ids) field_label
446
447     error_expr = mkApps (Var rEC_SEL_ERROR_ID) [Type (unUsgTy field_tau), err_string]
448        -- preserves invariant that type args are *not* usage-annotated on top.  KSW 1999-04.
449     err_string = App (Var unpack_id) (Lit (MachStr (_PK_ full_msg)))
450     full_msg   = showSDoc (sep [text "No match in record selector", ppr sel_id]) 
451 \end{code}
452
453
454 %************************************************************************
455 %*                                                                      *
456 \subsection{Dictionary selectors}
457 %*                                                                      *
458 %************************************************************************
459
460 Selecting a field for a dictionary.  If there is just one field, then
461 there's nothing to do.  
462
463 ToDo: unify with mkRecordSelId.
464
465 \begin{code}
466 mkDictSelId :: Name -> Class -> Id
467 mkDictSelId name clas
468   = sel_id
469   where
470     ty        = exprType rhs
471     sel_id    = mkId name ty info
472     field_lbl = mkFieldLabel name tycon ty tag
473     tag       = assoc "MkId.mkDictSelId" (classSelIds clas `zip` allFieldLabelTags) sel_id
474
475     info      = mkIdInfo (RecordSelId field_lbl)
476                 `setArityInfo`      exactArity 1
477                 `setUnfoldingInfo`  unfolding
478                 `setCafInfo`        NoCafRefs
479                 
480         -- We no longer use 'must-inline' on record selectors.  They'll
481         -- inline like crazy if they scrutinise a constructor
482
483     unfolding = mkTopUnfolding rhs
484
485     tyvars  = classTyVars clas
486
487     tycon      = classTyCon clas
488     [data_con] = tyConDataCons tycon
489     tyvar_tys  = mkTyVarTys tyvars
490     arg_tys    = dataConArgTys data_con tyvar_tys
491     the_arg_id = arg_ids !! (tag - firstFieldLabelTag)
492
493     dict_ty    = mkDictTy clas tyvar_tys
494     (dict_id:arg_ids) = mkTemplateLocals (dict_ty : arg_tys)
495
496     rhs | isNewTyCon tycon = mkLams tyvars $ Lam dict_id $
497                              Note (Coerce (head arg_tys) dict_ty) (Var dict_id)
498         | otherwise        = mkLams tyvars $ Lam dict_id $
499                              Case (Var dict_id) dict_id
500                                   [(DataAlt data_con, arg_ids, Var the_arg_id)]
501 \end{code}
502
503
504 %************************************************************************
505 %*                                                                      *
506 \subsection{Primitive operations
507 %*                                                                      *
508 %************************************************************************
509
510 \begin{code}
511 mkPrimOpId :: PrimOp -> Id
512 mkPrimOpId prim_op 
513   = id
514   where
515     (tyvars,arg_tys,res_ty, arity, strict_info) = primOpSig prim_op
516     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
517     name = mkPrimOpIdName prim_op id
518     id   = mkId name ty info
519                 
520     info = mkIdInfo (PrimOpId prim_op)
521            `setSpecInfo`        rules
522            `setArityInfo`       exactArity arity
523            `setStrictnessInfo`  strict_info
524
525     rules = addRule id emptyCoreRules (primOpRule prim_op)
526
527
528 -- For each ccall we manufacture a separate CCallOpId, giving it
529 -- a fresh unique, a type that is correct for this particular ccall,
530 -- and a CCall structure that gives the correct details about calling
531 -- convention etc.  
532 --
533 -- The *name* of this Id is a local name whose OccName gives the full
534 -- details of the ccall, type and all.  This means that the interface 
535 -- file reader can reconstruct a suitable Id
536
537 mkCCallOpId :: Unique -> CCall -> Type -> Id
538 mkCCallOpId uniq ccall ty
539   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
540         -- A CCallOpId should have no free type variables; 
541         -- when doing substitutions won't substitute over it
542     mkId name ty info
543   where
544     occ_str = showSDocIface (braces (pprCCallOp ccall <+> ppr ty))
545         -- The "occurrence name" of a ccall is the full info about the
546         -- ccall; it is encoded, but may have embedded spaces etc!
547
548     name    = mkCCallName uniq occ_str
549     prim_op = CCallOp ccall
550
551     info = mkIdInfo (PrimOpId prim_op)
552            `setArityInfo`       exactArity arity
553            `setStrictnessInfo`  strict_info
554
555     (_, tau)     = splitForAllTys ty
556     (arg_tys, _) = splitFunTys tau
557     arity        = length arg_tys
558     strict_info  = mkStrictnessInfo (take arity (repeat wwPrim), False)
559 \end{code}
560
561
562 %************************************************************************
563 %*                                                                      *
564 \subsection{DictFuns}
565 %*                                                                      *
566 %************************************************************************
567
568 \begin{code}
569 mkDictFunId :: Name             -- Name to use for the dict fun;
570             -> Class 
571             -> [TyVar]
572             -> [Type]
573             -> ClassContext
574             -> Id
575
576 mkDictFunId dfun_name clas inst_tyvars inst_tys inst_decl_theta
577   = mkVanillaId dfun_name dfun_ty
578   where
579     (class_tyvars, sc_theta, _, _) = classBigSig clas
580     sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys) sc_theta
581
582     dfun_theta = classesToPreds inst_decl_theta
583
584 {-  1 dec 99: disable the Mark Jones optimisation for the sake
585     of compatibility with Hugs.
586     See `types/InstEnv' for a discussion related to this.
587
588     dfun_theta = case inst_decl_theta of
589                    []    -> []  -- If inst_decl_theta is empty, then we don't
590                                 -- want to have any dict arguments, so that we can
591                                 -- expose the constant methods.
592
593                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
594                                 -- Otherwise we pass the superclass dictionaries to
595                                 -- the dictionary function; the Mark Jones optimisation.
596                                 --
597                                 -- NOTE the "nub".  I got caught by this one:
598                                 --   class Monad m => MonadT t m where ...
599                                 --   instance Monad m => MonadT (EnvT env) m where ...
600                                 -- Here, the inst_decl_theta has (Monad m); but so
601                                 -- does the sc_theta'!
602                                 --
603                                 -- NOTE the "not_const".  I got caught by this one too:
604                                 --   class Foo a => Baz a b where ...
605                                 --   instance Wob b => Baz T b where..
606                                 -- Now sc_theta' has Foo T
607 -}
608     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
609
610     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
611 \end{code}
612
613
614 %************************************************************************
615 %*                                                                      *
616 \subsection{Un-definable}
617 %*                                                                      *
618 %************************************************************************
619
620 These two can't be defined in Haskell.
621
622 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
623 just gets expanded into a type coercion wherever it occurs.  Hence we
624 add it as a built-in Id with an unfolding here.
625
626 The type variables we use here are "open" type variables: this means
627 they can unify with both unlifted and lifted types.  Hence we provide
628 another gun with which to shoot yourself in the foot.
629
630 \begin{code}
631 unsafeCoerceId
632   = pcMiscPrelId unsafeCoerceIdKey pREL_GHC SLIT("unsafeCoerce#") ty info
633   where
634     info = vanillaIdInfo
635            `setUnfoldingInfo` mkCompulsoryUnfolding rhs
636            
637
638     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
639                       (mkFunTy openAlphaTy openBetaTy)
640     [x] = mkTemplateLocals [openAlphaTy]
641     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
642           Note (Coerce openBetaTy openAlphaTy) (Var x)
643 \end{code}
644
645
646 @getTag#@ is another function which can't be defined in Haskell.  It needs to
647 evaluate its argument and call the dataToTag# primitive.
648
649 \begin{code}
650 getTagId
651   = pcMiscPrelId getTagIdKey pREL_GHC SLIT("getTag#") ty info
652   where
653     info = vanillaIdInfo
654            `setUnfoldingInfo`   mkCompulsoryUnfolding rhs
655         -- We don't provide a defn for this; you must inline it
656
657     ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy intPrimTy)
658     [x,y] = mkTemplateLocals [alphaTy,alphaTy]
659     rhs = mkLams [alphaTyVar,x] $
660           Case (Var x) y [ (DEFAULT, [], mkApps (Var dataToTagId) [Type alphaTy, Var y]) ]
661
662 dataToTagId = mkPrimOpId DataToTagOp
663 \end{code}
664
665 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
666 nasty as-is, change it back to a literal (@Literal@).
667
668 \begin{code}
669 realWorldPrimId -- :: State# RealWorld
670   = pcMiscPrelId realWorldPrimIdKey pREL_GHC SLIT("realWorld#")
671                  realWorldStatePrimTy
672                  (noCafIdInfo `setUnfoldingInfo` mkOtherCon [])
673         -- The mkOtherCon makes it look that realWorld# is evaluated
674         -- which in turn makes Simplify.interestingArg return True,
675         -- which in turn makes INLINE things applied to realWorld# likely
676         -- to be inlined
677 \end{code}
678
679
680 %************************************************************************
681 %*                                                                      *
682 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
683 %*                                                                      *
684 %************************************************************************
685
686 GHC randomly injects these into the code.
687
688 @patError@ is just a version of @error@ for pattern-matching
689 failures.  It knows various ``codes'' which expand to longer
690 strings---this saves space!
691
692 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
693 well shouldn't be yanked on, but if one is, then you will get a
694 friendly message from @absentErr@ (rather than a totally random
695 crash).
696
697 @parError@ is a special version of @error@ which the compiler does
698 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
699 templates, but we don't ever expect to generate code for it.
700
701 \begin{code}
702 eRROR_ID
703   = pc_bottoming_Id errorIdKey pREL_ERR SLIT("error") errorTy
704 rEC_SEL_ERROR_ID
705   = generic_ERROR_ID recSelErrIdKey SLIT("patError")
706 pAT_ERROR_ID
707   = generic_ERROR_ID patErrorIdKey SLIT("patError")
708 rEC_CON_ERROR_ID
709   = generic_ERROR_ID recConErrorIdKey SLIT("recConError")
710 rEC_UPD_ERROR_ID
711   = generic_ERROR_ID recUpdErrorIdKey SLIT("recUpdError")
712 iRREFUT_PAT_ERROR_ID
713   = generic_ERROR_ID irrefutPatErrorIdKey SLIT("irrefutPatError")
714 nON_EXHAUSTIVE_GUARDS_ERROR_ID
715   = generic_ERROR_ID nonExhaustiveGuardsErrorIdKey SLIT("nonExhaustiveGuardsError")
716 nO_METHOD_BINDING_ERROR_ID
717   = generic_ERROR_ID noMethodBindingErrorIdKey SLIT("noMethodBindingError")
718
719 aBSENT_ERROR_ID
720   = pc_bottoming_Id absentErrorIdKey pREL_ERR SLIT("absentErr")
721         (mkSigmaTy [openAlphaTyVar] [] openAlphaTy)
722
723 pAR_ERROR_ID
724   = pcMiscPrelId parErrorIdKey pREL_ERR SLIT("parError")
725     (mkSigmaTy [openAlphaTyVar] [] openAlphaTy) noCafIdInfo
726
727 \end{code}
728
729
730 %************************************************************************
731 %*                                                                      *
732 \subsection{Utilities}
733 %*                                                                      *
734 %************************************************************************
735
736 \begin{code}
737 pcMiscPrelId :: Unique{-IdKey-} -> Module -> FAST_STRING -> Type -> IdInfo -> Id
738 pcMiscPrelId key mod str ty info
739   = let
740         name = mkWiredInIdName key mod (mkSrcVarOcc str) imp
741         imp  = mkId name ty info -- the usual case...
742     in
743     imp
744     -- We lie and say the thing is imported; otherwise, we get into
745     -- a mess with dependency analysis; e.g., core2stg may heave in
746     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
747     -- being compiled, then it's just a matter of luck if the definition
748     -- will be in "the right place" to be in scope.
749
750 pc_bottoming_Id key mod name ty
751  = pcMiscPrelId key mod name ty bottoming_info
752  where
753     bottoming_info = noCafIdInfo 
754                      `setStrictnessInfo` mkStrictnessInfo ([wwStrict], True)
755                      
756         -- these "bottom" out, no matter what their arguments
757
758 generic_ERROR_ID u n = pc_bottoming_Id u pREL_ERR n errorTy
759
760 -- Very useful...
761 noCafIdInfo = vanillaIdInfo `setCafInfo` NoCafRefs
762
763 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
764 openAlphaTy  = mkTyVarTy openAlphaTyVar
765 openBetaTy   = mkTyVarTy openBetaTyVar
766
767 errorTy  :: Type
768 errorTy  = mkUsgTy UsMany $
769            mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkUsgTy UsOnce (mkListTy charTy)] 
770                                                    (mkUsgTy UsMany openAlphaTy))
771     -- Notice the openAlphaTyVar.  It says that "error" can be applied
772     -- to unboxed as well as boxed types.  This is OK because it never
773     -- returns, so the return type is irrelevant.
774 \end{code}
775