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