[project @ 2001-10-17 11:26:04 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         mkDictFunId, mkDefaultMethodId,
17         mkDictSelId,
18
19         mkDataConId, mkDataConWrapId,
20         mkRecordSelId, rebuildConArgs,
21         mkPrimOpId, mkFCallId,
22
23         -- And some particular Ids; see below for why they are wired in
24         wiredInIds,
25         unsafeCoerceId, realWorldPrimId, nullAddrId,
26         eRROR_ID, eRROR_CSTRING_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 BasicTypes       ( Arity, StrictnessMark(..), isMarkedUnboxed, isMarkedStrict )
35 import TysPrim          ( openAlphaTyVars, alphaTyVar, alphaTy, betaTyVar, betaTy,
36                           intPrimTy, realWorldStatePrimTy, addrPrimTy
37                         )
38 import TysWiredIn       ( charTy, mkListTy )
39 import PrelRules        ( primOpRules )
40 import Rules            ( addRule )
41 import TcType           ( Type, ThetaType, mkDictTy, mkPredTys, mkTyConApp,
42                           mkTyVarTys, mkClassPred, tcEqPred,
43                           mkFunTys, mkFunTy, mkSigmaTy, tcSplitSigmaTy, 
44                           isUnLiftedType, mkForAllTys, mkTyVarTy, tyVarsOfType,
45                           tcSplitFunTys, tcSplitForAllTys, mkPredTy
46                         )
47 import Module           ( Module )
48 import CoreUtils        ( mkInlineMe )
49 import CoreUnfold       ( mkTopUnfolding, mkCompulsoryUnfolding, mkOtherCon )
50 import Literal          ( Literal(..), nullAddrLit )
51 import TyCon            ( TyCon, isNewTyCon, tyConTyVars, tyConDataCons,
52                           tyConTheta, isProductTyCon, isDataTyCon, isRecursiveTyCon )
53 import Class            ( Class, classTyCon, classTyVars, classSelIds )
54 import Var              ( Id, TyVar )
55 import VarSet           ( isEmptyVarSet )
56 import Name             ( mkWiredInName, mkFCallName, Name )
57 import OccName          ( mkVarOcc )
58 import PrimOp           ( PrimOp(DataToTagOp), primOpSig, mkPrimOpIdName )
59 import ForeignCall      ( ForeignCall )
60 import DataCon          ( DataCon, 
61                           dataConFieldLabels, dataConRepArity, dataConTyCon,
62                           dataConArgTys, dataConRepType, 
63                           dataConInstOrigArgTys,
64                           dataConName, dataConTheta,
65                           dataConSig, dataConStrictMarks, dataConId,
66                           splitProductType
67                         )
68 import Id               ( idType, mkGlobalId, mkVanillaGlobal, mkSysLocal,
69                           mkTemplateLocals, mkTemplateLocalsNum,
70                           mkTemplateLocal, idNewStrictness, idName
71                         )
72 import IdInfo           ( IdInfo, noCafNoTyGenIdInfo,
73                           setUnfoldingInfo, 
74                           setArityInfo, setSpecInfo,  setCgInfo,
75                           mkNewStrictnessInfo, setNewStrictnessInfo,
76                           GlobalIdDetails(..), CafInfo(..), CprInfo(..), 
77                           CgInfo(..), setCgArity
78                         )
79 import NewDemand        ( mkStrictSig, strictSigResInfo, DmdResult(..),
80                           mkTopDmdType, topDmd, evalDmd, Demand(..), Keepity(..) )
81 import FieldLabel       ( mkFieldLabel, fieldLabelName, 
82                           firstFieldLabelTag, allFieldLabelTags, fieldLabelType
83                         )
84 import DmdAnal          ( dmdAnalTopRhs )
85 import CoreSyn
86 import Unique           ( mkBuiltinUnique )
87 import Maybes
88 import PrelNames
89 import Maybe            ( isJust )
90 import Outputable
91 import ListSetOps       ( assoc, assocMaybe )
92 import UnicodeUtil      ( stringToUtf8 )
93 import Char             ( ord )
94 \end{code}              
95
96 %************************************************************************
97 %*                                                                      *
98 \subsection{Wired in Ids}
99 %*                                                                      *
100 %************************************************************************
101
102 \begin{code}
103 wiredInIds
104   = [   -- These error-y things are wired in because we don't yet have
105         -- a way to express in an interface file that the result type variable
106         -- is 'open'; that is can be unified with an unboxed type
107         -- 
108         -- [The interface file format now carry such information, but there's
109         -- no way yet of expressing at the definition site for these 
110         -- error-reporting
111         -- functions that they have an 'open' result type. -- sof 1/99]
112
113       aBSENT_ERROR_ID
114     , eRROR_ID
115     , eRROR_CSTRING_ID
116     , iRREFUT_PAT_ERROR_ID
117     , nON_EXHAUSTIVE_GUARDS_ERROR_ID
118     , nO_METHOD_BINDING_ERROR_ID
119     , pAR_ERROR_ID
120     , pAT_ERROR_ID
121     , rEC_CON_ERROR_ID
122     , rEC_UPD_ERROR_ID
123
124         -- These can't be defined in Haskell, but they have
125         -- perfectly reasonable unfoldings in Core
126     , realWorldPrimId
127     , unsafeCoerceId
128     , nullAddrId
129     , getTagId
130     , seqId
131     ]
132 \end{code}
133
134 %************************************************************************
135 %*                                                                      *
136 \subsection{Data constructors}
137 %*                                                                      *
138 %************************************************************************
139
140 \begin{code}
141 mkDataConId :: Name -> DataCon -> Id
142         -- Makes the *worker* for the data constructor; that is, the function
143         -- that takes the reprsentation arguments and builds the constructor.
144 mkDataConId work_name data_con
145   = mkGlobalId (DataConId data_con) work_name (dataConRepType data_con) info
146   where
147     info = noCafNoTyGenIdInfo
148            `setCgArity`                 arity
149            `setArityInfo`               arity
150            `setNewStrictnessInfo`       Just strict_sig
151
152     arity      = dataConRepArity data_con
153
154     strict_sig = mkStrictSig (mkTopDmdType (replicate arity topDmd) cpr_info)
155         -- Notice that we do *not* say the worker is strict
156         -- even if the data constructor is declared strict
157         --      e.g.    data T = MkT !(Int,Int)
158         -- Why?  Because the *wrapper* is strict (and its unfolding has case
159         -- expresssions that do the evals) but the *worker* itself is not.
160         -- If we pretend it is strict then when we see
161         --      case x of y -> $wMkT y
162         -- the simplifier thinks that y is "sure to be evaluated" (because
163         -- $wMkT is strict) and drops the case.  No, $wMkT is not strict.
164         --
165         -- When the simplifer sees a pattern 
166         --      case e of MkT x -> ...
167         -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
168         -- but that's fine... dataConRepStrictness comes from the data con
169         -- not from the worker Id.
170
171     tycon = dataConTyCon data_con
172     cpr_info | isProductTyCon tycon && 
173                isDataTyCon tycon    &&
174                arity > 0            &&
175                arity <= mAX_CPR_SIZE    = RetCPR
176              | otherwise                = TopRes
177         -- RetCPR is only true for products that are real data types;
178         -- that is, not unboxed tuples or [non-recursive] newtypes
179
180 mAX_CPR_SIZE :: Arity
181 mAX_CPR_SIZE = 10
182 -- We do not treat very big tuples as CPR-ish:
183 --      a) for a start we get into trouble because there aren't 
184 --         "enough" unboxed tuple types (a tiresome restriction, 
185 --         but hard to fix), 
186 --      b) more importantly, big unboxed tuples get returned mainly
187 --         on the stack, and are often then allocated in the heap
188 --         by the caller.  So doing CPR for them may in fact make
189 --         things worse.
190 \end{code}
191
192 The wrapper for a constructor is an ordinary top-level binding that evaluates
193 any strict args, unboxes any args that are going to be flattened, and calls
194 the worker.
195
196 We're going to build a constructor that looks like:
197
198         data (Data a, C b) =>  T a b = T1 !a !Int b
199
200         T1 = /\ a b -> 
201              \d1::Data a, d2::C b ->
202              \p q r -> case p of { p ->
203                        case q of { q ->
204                        Con T1 [a,b] [p,q,r]}}
205
206 Notice that
207
208 * d2 is thrown away --- a context in a data decl is used to make sure
209   one *could* construct dictionaries at the site the constructor
210   is used, but the dictionary isn't actually used.
211
212 * We have to check that we can construct Data dictionaries for
213   the types a and Int.  Once we've done that we can throw d1 away too.
214
215 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
216   all that matters is that the arguments are evaluated.  "seq" is 
217   very careful to preserve evaluation order, which we don't need
218   to be here.
219
220   You might think that we could simply give constructors some strictness
221   info, like PrimOps, and let CoreToStg do the let-to-case transformation.
222   But we don't do that because in the case of primops and functions strictness
223   is a *property* not a *requirement*.  In the case of constructors we need to
224   do something active to evaluate the argument.
225
226   Making an explicit case expression allows the simplifier to eliminate
227   it in the (common) case where the constructor arg is already evaluated.
228
229 \begin{code}
230 mkDataConWrapId data_con
231   = mkGlobalId (DataConWrapId data_con) (dataConName data_con) wrap_ty info
232   where
233     work_id = dataConId data_con
234
235     info = noCafNoTyGenIdInfo
236            `setUnfoldingInfo`   mkTopUnfolding (mkInlineMe wrap_rhs)
237            `setCgArity`         arity
238                 -- The NoCaf-ness is set by noCafNoTyGenIdInfo
239            `setArityInfo`       arity
240                 -- It's important to specify the arity, so that partial
241                 -- applications are treated as values
242            `setNewStrictnessInfo`       Just wrap_sig
243
244     wrap_ty = mkForAllTys all_tyvars (mkFunTys all_arg_tys result_ty)
245
246     res_info = strictSigResInfo (idNewStrictness work_id)
247     wrap_sig = mkStrictSig (mkTopDmdType (replicate arity topDmd) res_info)
248         -- The Cpr info can be important inside INLINE rhss, where the
249         -- wrapper constructor isn't inlined
250         -- But we are sloppy about the argument demands, because we expect 
251         -- to inline the constructor very vigorously.
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 context
256                 -- e.g.         newtype Eq a => T a = MkT (...)
257                 mkLams tyvars $ mkLams dict_args $ Lam id_arg1 $ 
258                 mkNewTypeBody tycon result_ty id_arg1
259
260              | null dict_args && not (any isMarkedStrict strict_marks)
261              = Var work_id      -- The common case.  Not only is this efficient,
262                                 -- but it also ensures that the wrapper is replaced
263                                 -- by the worker even when there are no args.
264                                 --              f (:) x
265                                 -- becomes 
266                                 --              f $w: x
267                                 -- This is really important in rule matching,
268                                 -- (We could match on the wrappers,
269                                 -- but that makes it less likely that rules will match
270                                 -- when we bring bits of unfoldings together.)
271                 --
272                 -- NB:  because of this special case, (map (:) ys) turns into
273                 --      (map $w: ys), and thence into (map (\x xs. $w: x xs) ys)
274                 --      in core-to-stg.  The top-level defn for (:) is never used.
275                 --      This is somewhat of a bore, but I'm currently leaving it 
276                 --      as is, so that there still is a top level curried (:) for
277                 --      the interpreter to call.
278
279              | otherwise
280              = mkLams all_tyvars $ mkLams dict_args $ 
281                mkLams ex_dict_args $ mkLams id_args $
282                foldr mk_case con_app 
283                      (zip (ex_dict_args++id_args) strict_marks) i3 []
284
285     con_app i rep_ids = mkApps (Var work_id)
286                                (map varToCoreExpr (all_tyvars ++ reverse rep_ids))
287
288     (tyvars, theta, ex_tyvars, ex_theta, orig_arg_tys, tycon) = dataConSig data_con
289     all_tyvars   = tyvars ++ ex_tyvars
290
291     dict_tys     = mkPredTys theta
292     ex_dict_tys  = mkPredTys ex_theta
293     all_arg_tys  = dict_tys ++ ex_dict_tys ++ orig_arg_tys
294     result_ty    = mkTyConApp tycon (mkTyVarTys tyvars)
295
296     mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
297                    where
298                      n = length tys
299
300     (dict_args, i1)    = mkLocals 1  dict_tys
301     (ex_dict_args,i2)  = mkLocals i1 ex_dict_tys
302     (id_args,i3)       = mkLocals i2 orig_arg_tys
303     arity              = i3-1
304     (id_arg1:_)   = id_args             -- Used for newtype only
305
306     strict_marks  = dataConStrictMarks data_con
307
308     mk_case 
309            :: (Id, StrictnessMark)      -- Arg, strictness
310            -> (Int -> [Id] -> CoreExpr) -- Body
311            -> Int                       -- Next rep arg id
312            -> [Id]                      -- Rep args so far, reversed
313            -> CoreExpr
314     mk_case (arg,strict) body i rep_args
315           = case strict of
316                 NotMarkedStrict -> body i (arg:rep_args)
317                 MarkedStrict 
318                    | isUnLiftedType (idType arg) -> body i (arg:rep_args)
319                    | otherwise ->
320                         Case (Var arg) arg [(DEFAULT,[], body i (arg:rep_args))]
321
322                 MarkedUnboxed
323                    -> case splitProductType "do_unbox" (idType arg) of
324                            (tycon, tycon_args, con, tys) ->
325                                    Case (Var arg) arg [(DataAlt con, con_args,
326                                         body i' (reverse con_args ++ rep_args))]
327                               where 
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 unpackUtf8_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     = mkGlobalId (RecordSelId field_label) (fieldLabelName field_label) selector_ty info
385     field_ty   = fieldLabelType field_label
386     data_cons  = tyConDataCons tycon
387     tyvars     = tyConTyVars tycon      -- These scope over the types in 
388                                         -- the FieldLabels of constructors of this type
389     data_ty   = mkTyConApp tycon tyvar_tys
390     tyvar_tys = mkTyVarTys tyvars
391
392     tycon_theta = tyConTheta tycon      -- The context on the data decl
393                                         --   eg data (Eq a, Ord b) => T a b = ...
394     dict_tys  = [mkPredTy pred | pred <- tycon_theta, 
395                                  needed_dict pred]
396     needed_dict pred = or [ tcEqPred pred p
397                           | (DataAlt dc, _, _) <- the_alts, p <- dataConTheta dc]
398     n_dict_tys = length dict_tys
399
400     (field_tyvars,field_theta,field_tau) = tcSplitSigmaTy field_ty
401     field_dict_tys                       = map mkPredTy field_theta
402     n_field_dict_tys                     = length field_dict_tys
403         -- If the field has a universally quantified type we have to 
404         -- be a bit careful.  Suppose we have
405         --      data R = R { op :: forall a. Foo a => a -> a }
406         -- Then we can't give op the type
407         --      op :: R -> forall a. Foo a => a -> a
408         -- because the typechecker doesn't understand foralls to the
409         -- right of an arrow.  The "right" type to give it is
410         --      op :: forall a. Foo a => R -> a -> a
411         -- But then we must generate the right unfolding too:
412         --      op = /\a -> \dfoo -> \ r ->
413         --           case r of
414         --              R op -> op a dfoo
415         -- Note that this is exactly the type we'd infer from a user defn
416         --      op (R op) = op
417
418         -- Very tiresomely, the selectors are (unnecessarily!) overloaded over
419         -- just the dictionaries in the types of the constructors that contain
420         -- the relevant field.  Urgh.  
421         -- NB: this code relies on the fact that DataCons are quantified over
422         -- the identical type variables as their parent TyCon
423
424     selector_ty :: Type
425     selector_ty  = mkForAllTys tyvars $ mkForAllTys field_tyvars $
426                    mkFunTys dict_tys  $  mkFunTys field_dict_tys $
427                    mkFunTy data_ty field_tau
428       
429     arity = 1 + n_dict_tys + n_field_dict_tys
430
431     (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
432         -- Use the demand analyser to work out strictness.
433         -- With all this unpackery it's not easy!
434
435     info = noCafNoTyGenIdInfo
436            `setCgInfo`            CgInfo arity caf_info
437            `setArityInfo`         arity
438            `setUnfoldingInfo`     mkTopUnfolding rhs_w_str
439            `setNewStrictnessInfo` Just strict_sig
440
441         -- Allocate Ids.  We do it a funny way round because field_dict_tys is
442         -- almost always empty.  Also note that we use length_tycon_theta
443         -- rather than n_dict_tys, because the latter gives an infinite loop:
444         -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
445         -- on arity, which depends on n_dict tys.  Sigh!  Mega sigh!
446     field_dict_base    = length tycon_theta + 1
447     dict_id_base       = field_dict_base + n_field_dict_tys
448     field_base         = dict_id_base + 1
449     dict_ids           = mkTemplateLocalsNum  1               dict_tys
450     field_dict_ids     = mkTemplateLocalsNum  field_dict_base field_dict_tys
451     data_id            = mkTemplateLocal      dict_id_base    data_ty
452
453     alts      = map mk_maybe_alt data_cons
454     the_alts  = catMaybes alts
455
456     no_default = all isJust alts        -- No default needed
457     default_alt | no_default = []
458                 | otherwise  = [(DEFAULT, [], error_expr)]
459
460         -- the default branch may have CAF refs, because it calls recSelError etc.
461     caf_info    | no_default = NoCafRefs
462                 | otherwise  = MayHaveCafRefs
463
464     sel_rhs = mkLams tyvars   $ mkLams field_tyvars $ 
465               mkLams dict_ids $ mkLams field_dict_ids $
466               Lam data_id     $ sel_body
467
468     sel_body | isNewTyCon tycon = mkNewTypeBody tycon field_tau data_id
469              | otherwise        = Case (Var data_id) data_id (default_alt ++ the_alts)
470
471     mk_maybe_alt data_con 
472           = case maybe_the_arg_id of
473                 Nothing         -> Nothing
474                 Just the_arg_id -> Just (DataAlt data_con, real_args, mkLets binds body)
475                   where
476                     body               = mkVarApps (mkVarApps (Var the_arg_id) field_tyvars) field_dict_ids
477                     strict_marks       = dataConStrictMarks data_con
478                     (binds, real_args) = rebuildConArgs arg_ids strict_marks
479                                                         (map mkBuiltinUnique [unpack_base..])
480         where
481             arg_ids = mkTemplateLocalsNum field_base (dataConInstOrigArgTys data_con tyvar_tys)
482
483             unpack_base = field_base + length arg_ids
484
485                                 -- arity+1 avoids all shadowing
486             maybe_the_arg_id  = assocMaybe (field_lbls `zip` arg_ids) field_label
487             field_lbls        = dataConFieldLabels data_con
488
489     error_expr = mkApps (Var rEC_SEL_ERROR_ID) [Type field_tau, err_string]
490     err_string
491         | all safeChar full_msg
492             = App (Var unpack_id) (Lit (MachStr (_PK_ full_msg)))
493         | otherwise
494             = App (Var unpackUtf8_id) (Lit (MachStr (_PK_ (stringToUtf8 (map ord full_msg)))))
495         where
496         safeChar c = c >= '\1' && c <= '\xFF'
497         -- TODO: Putting this Unicode stuff here is ugly. Find a better
498         -- generic place to make string literals. This logic is repeated
499         -- in DsUtils.
500     full_msg   = showSDoc (sep [text "No match in record selector", ppr sel_id]) 
501
502
503 -- This rather ugly function converts the unpacked data con 
504 -- arguments back into their packed form.
505
506 rebuildConArgs
507   :: [Id]                       -- Source-level args
508   -> [StrictnessMark]           -- Strictness annotations (per-arg)
509   -> [Unique]                   -- Uniques for the new Ids
510   -> ([CoreBind], [Id])         -- A binding for each source-level arg, plus
511                                 -- a list of the representation-level arguments 
512 -- e.g.   data T = MkT Int !Int
513 --
514 -- rebuild [x::Int, y::Int] [Not, Unbox]
515 --  = ([ y = I# t ], [x,t])
516
517 rebuildConArgs []         stricts us = ([], [])
518
519 -- Type variable case
520 rebuildConArgs (arg:args) stricts us 
521   | isTyVar arg
522   = let (binds, args') = rebuildConArgs args stricts us
523     in  (binds, arg:args')
524
525 -- Term variable case
526 rebuildConArgs (arg:args) (str:stricts) us
527   | isMarkedUnboxed str
528   = let
529         arg_ty  = idType arg
530
531         (_, tycon_args, pack_con, con_arg_tys)
532                  = splitProductType "rebuildConArgs" arg_ty
533
534         unpacked_args  = zipWith (mkSysLocal SLIT("rb")) us con_arg_tys
535         (binds, args') = rebuildConArgs args stricts (drop (length con_arg_tys) us)
536         con_app        = mkConApp pack_con (map Type tycon_args ++ map Var unpacked_args)
537     in
538     (NonRec arg con_app : binds, unpacked_args ++ args')
539
540   | otherwise
541   = let (binds, args') = rebuildConArgs args stricts us
542     in  (binds, arg:args')
543 \end{code}
544
545
546 %************************************************************************
547 %*                                                                      *
548 \subsection{Dictionary selectors}
549 %*                                                                      *
550 %************************************************************************
551
552 Selecting a field for a dictionary.  If there is just one field, then
553 there's nothing to do.  
554
555 ToDo: unify with mkRecordSelId.
556
557 \begin{code}
558 mkDictSelId :: Name -> Class -> Id
559 mkDictSelId name clas
560   = mkGlobalId (RecordSelId field_lbl) name sel_ty info
561   where
562     sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
563         -- We can't just say (exprType rhs), because that would give a type
564         --      C a -> C a
565         -- for a single-op class (after all, the selector is the identity)
566         -- But it's type must expose the representation of the dictionary
567         -- to gat (say)         C a -> (a -> a)
568
569     field_lbl = mkFieldLabel name tycon sel_ty tag
570     tag       = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` allFieldLabelTags) name
571
572     info      = noCafNoTyGenIdInfo
573                 `setCgArity`            1
574                 `setArityInfo`          1
575                 `setUnfoldingInfo`      mkTopUnfolding rhs
576                 `setNewStrictnessInfo`  Just strict_sig
577
578         -- We no longer use 'must-inline' on record selectors.  They'll
579         -- inline like crazy if they scrutinise a constructor
580
581         -- The strictness signature is of the form U(AAAVAAAA) -> T
582         -- where the V depends on which item we are selecting
583         -- It's worth giving one, so that absence info etc is generated
584         -- even if the selector isn't inlined
585     strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
586     arg_dmd | isNewTyCon tycon = Eval
587             | otherwise        = Seq Drop [ if the_arg_id == id then Eval else Abs
588                                           | id <- arg_ids ]
589
590     tyvars  = classTyVars clas
591
592     tycon      = classTyCon clas
593     [data_con] = tyConDataCons tycon
594     tyvar_tys  = mkTyVarTys tyvars
595     arg_tys    = dataConArgTys data_con tyvar_tys
596     the_arg_id = arg_ids !! (tag - firstFieldLabelTag)
597
598     pred              = mkClassPred clas tyvar_tys
599     (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
600
601     rhs | isNewTyCon tycon = mkLams tyvars $ Lam dict_id $ 
602                              mkNewTypeBody tycon (head arg_tys) dict_id
603         | otherwise        = mkLams tyvars $ Lam dict_id $
604                              Case (Var dict_id) dict_id
605                                   [(DataAlt data_con, arg_ids, Var the_arg_id)]
606
607 mkNewTypeBody tycon result_ty result_id
608   | isRecursiveTyCon tycon      -- Recursive case; use a coerce
609   = Note (Coerce result_ty (idType result_id)) (Var result_id)
610   | otherwise                   -- Normal case
611   = Var result_id
612 \end{code}
613
614
615 %************************************************************************
616 %*                                                                      *
617 \subsection{Primitive operations
618 %*                                                                      *
619 %************************************************************************
620
621 \begin{code}
622 mkPrimOpId :: PrimOp -> Id
623 mkPrimOpId prim_op 
624   = id
625   where
626     (tyvars,arg_tys,res_ty, arity, strict_info) = primOpSig prim_op
627     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
628     name = mkPrimOpIdName prim_op
629     id   = mkGlobalId (PrimOpId prim_op) name ty info
630                 
631     info = noCafNoTyGenIdInfo
632            `setSpecInfo`        rules
633            `setCgArity`         arity
634            `setArityInfo`       arity
635            `setNewStrictnessInfo`       Just (mkNewStrictnessInfo id arity strict_info NoCPRInfo)
636         -- Until we modify the primop generation code
637
638     rules = foldl (addRule id) emptyCoreRules (primOpRules prim_op)
639
640
641 -- For each ccall we manufacture a separate CCallOpId, giving it
642 -- a fresh unique, a type that is correct for this particular ccall,
643 -- and a CCall structure that gives the correct details about calling
644 -- convention etc.  
645 --
646 -- The *name* of this Id is a local name whose OccName gives the full
647 -- details of the ccall, type and all.  This means that the interface 
648 -- file reader can reconstruct a suitable Id
649
650 mkFCallId :: Unique -> ForeignCall -> Type -> Id
651 mkFCallId uniq fcall ty
652   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
653         -- A CCallOpId should have no free type variables; 
654         -- when doing substitutions won't substitute over it
655     mkGlobalId (FCallId fcall) name ty info
656   where
657     occ_str = showSDocIface (braces (ppr fcall <+> ppr ty))
658         -- The "occurrence name" of a ccall is the full info about the
659         -- ccall; it is encoded, but may have embedded spaces etc!
660
661     name = mkFCallName uniq occ_str
662
663     info = noCafNoTyGenIdInfo
664            `setCgArity`                 arity
665            `setArityInfo`               arity
666            `setNewStrictnessInfo`       Just strict_sig
667
668     (_, tau)     = tcSplitForAllTys ty
669     (arg_tys, _) = tcSplitFunTys tau
670     arity        = length arg_tys
671     strict_sig   = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
672 \end{code}
673
674
675 %************************************************************************
676 %*                                                                      *
677 \subsection{DictFuns and default methods}
678 %*                                                                      *
679 %************************************************************************
680
681 Important notes about dict funs and default methods
682 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
683 Dict funs and default methods are *not* ImplicitIds.  Their definition
684 involves user-written code, so we can't figure out their strictness etc
685 based on fixed info, as we can for constructors and record selectors (say).
686
687 We build them as GlobalIds, but when in the module where they are
688 bound, we turn the Id at the *binding site* into an exported LocalId.
689 This ensures that they are taken to account by free-variable finding
690 and dependency analysis (e.g. CoreFVs.exprFreeVars).   The simplifier
691 will propagate the LocalId to all occurrence sites. 
692
693 Why shouldn't they be bound as GlobalIds?  Because, in particular, if
694 they are globals, the specialiser floats dict uses above their defns,
695 which prevents good simplifications happening.  Also the strictness
696 analyser treats a occurrence of a GlobalId as imported and assumes it
697 contains strictness in its IdInfo, which isn't true if the thing is
698 bound in the same module as the occurrence.
699
700 It's OK for dfuns to be LocalIds, because we form the instance-env to
701 pass on to the next module (md_insts) in CoreTidy, afer tidying
702 and globalising the top-level Ids.
703
704 BUT make sure they are *exported* LocalIds (setIdLocalExported) so 
705 that they aren't discarded by the occurrence analyser.
706
707 \begin{code}
708 mkDefaultMethodId dm_name ty = mkVanillaGlobal dm_name ty noCafNoTyGenIdInfo
709
710 mkDictFunId :: Name             -- Name to use for the dict fun;
711             -> Class 
712             -> [TyVar]
713             -> [Type]
714             -> ThetaType
715             -> Id
716
717 mkDictFunId dfun_name clas inst_tyvars inst_tys dfun_theta
718   = mkVanillaGlobal dfun_name dfun_ty noCafNoTyGenIdInfo
719   where
720     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
721
722 {-  1 dec 99: disable the Mark Jones optimisation for the sake
723     of compatibility with Hugs.
724     See `types/InstEnv' for a discussion related to this.
725
726     (class_tyvars, sc_theta, _, _) = classBigSig clas
727     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
728     sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys) sc_theta
729     dfun_theta = case inst_decl_theta of
730                    []    -> []  -- If inst_decl_theta is empty, then we don't
731                                 -- want to have any dict arguments, so that we can
732                                 -- expose the constant methods.
733
734                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
735                                 -- Otherwise we pass the superclass dictionaries to
736                                 -- the dictionary function; the Mark Jones optimisation.
737                                 --
738                                 -- NOTE the "nub".  I got caught by this one:
739                                 --   class Monad m => MonadT t m where ...
740                                 --   instance Monad m => MonadT (EnvT env) m where ...
741                                 -- Here, the inst_decl_theta has (Monad m); but so
742                                 -- does the sc_theta'!
743                                 --
744                                 -- NOTE the "not_const".  I got caught by this one too:
745                                 --   class Foo a => Baz a b where ...
746                                 --   instance Wob b => Baz T b where..
747                                 -- Now sc_theta' has Foo T
748 -}
749 \end{code}
750
751
752 %************************************************************************
753 %*                                                                      *
754 \subsection{Un-definable}
755 %*                                                                      *
756 %************************************************************************
757
758 These Ids can't be defined in Haskell.  They could be defined in 
759 unfoldings in PrelGHC.hi-boot, but we'd have to ensure that they
760 were definitely, definitely inlined, because there is no curried
761 identifier for them.  That's what mkCompulsoryUnfolding does.
762 If we had a way to get a compulsory unfolding from an interface file,
763 we could do that, but we don't right now.
764
765 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
766 just gets expanded into a type coercion wherever it occurs.  Hence we
767 add it as a built-in Id with an unfolding here.
768
769 The type variables we use here are "open" type variables: this means
770 they can unify with both unlifted and lifted types.  Hence we provide
771 another gun with which to shoot yourself in the foot.
772
773 \begin{code}
774 -- unsafeCoerce# :: forall a b. a -> b
775 unsafeCoerceId
776   = pcMiscPrelId unsafeCoerceIdKey pREL_GHC SLIT("unsafeCoerce#") ty info
777   where
778     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
779            
780
781     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
782                       (mkFunTy openAlphaTy openBetaTy)
783     [x] = mkTemplateLocals [openAlphaTy]
784     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
785           Note (Coerce openBetaTy openAlphaTy) (Var x)
786
787 -- nullAddr# :: Addr#
788 -- The reason is is here is because we don't provide 
789 -- a way to write this literal in Haskell.
790 nullAddrId 
791   = pcMiscPrelId nullAddrIdKey pREL_GHC SLIT("nullAddr#") addrPrimTy info
792   where
793     info = noCafNoTyGenIdInfo `setUnfoldingInfo` 
794            mkCompulsoryUnfolding (Lit nullAddrLit)
795
796 seqId
797   = pcMiscPrelId seqIdKey pREL_GHC SLIT("seq") ty info
798   where
799     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
800            
801
802     ty  = mkForAllTys [alphaTyVar,betaTyVar]
803                       (mkFunTy alphaTy (mkFunTy betaTy betaTy))
804     [x,y] = mkTemplateLocals [alphaTy, betaTy]
805     rhs = mkLams [alphaTyVar,betaTyVar,x,y] (Case (Var x) x [(DEFAULT, [], Var y)])
806 \end{code}
807
808 @getTag#@ is another function which can't be defined in Haskell.  It needs to
809 evaluate its argument and call the dataToTag# primitive.
810
811 \begin{code}
812 getTagId
813   = pcMiscPrelId getTagIdKey pREL_GHC SLIT("getTag#") ty info
814   where
815     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
816         -- We don't provide a defn for this; you must inline it
817
818     ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy intPrimTy)
819     [x,y] = mkTemplateLocals [alphaTy,alphaTy]
820     rhs = mkLams [alphaTyVar,x] $
821           Case (Var x) y [ (DEFAULT, [], mkApps (Var dataToTagId) [Type alphaTy, Var y]) ]
822
823 dataToTagId = mkPrimOpId DataToTagOp
824 \end{code}
825
826 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
827 nasty as-is, change it back to a literal (@Literal@).
828
829 \begin{code}
830 realWorldPrimId -- :: State# RealWorld
831   = pcMiscPrelId realWorldPrimIdKey pREL_GHC SLIT("realWorld#")
832                  realWorldStatePrimTy
833                  (noCafNoTyGenIdInfo `setUnfoldingInfo` mkOtherCon [])
834         -- The mkOtherCon makes it look that realWorld# is evaluated
835         -- which in turn makes Simplify.interestingArg return True,
836         -- which in turn makes INLINE things applied to realWorld# likely
837         -- to be inlined
838 \end{code}
839
840
841 %************************************************************************
842 %*                                                                      *
843 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
844 %*                                                                      *
845 %************************************************************************
846
847 GHC randomly injects these into the code.
848
849 @patError@ is just a version of @error@ for pattern-matching
850 failures.  It knows various ``codes'' which expand to longer
851 strings---this saves space!
852
853 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
854 well shouldn't be yanked on, but if one is, then you will get a
855 friendly message from @absentErr@ (rather than a totally random
856 crash).
857
858 @parError@ is a special version of @error@ which the compiler does
859 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
860 templates, but we don't ever expect to generate code for it.
861
862 \begin{code}
863 eRROR_ID
864   = pc_bottoming_Id errorIdKey pREL_ERR SLIT("error") errorTy
865 eRROR_CSTRING_ID
866   = pc_bottoming_Id errorCStringIdKey pREL_ERR SLIT("errorCString") 
867                     (mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy))
868 pAT_ERROR_ID
869   = generic_ERROR_ID patErrorIdKey SLIT("patError")
870 rEC_SEL_ERROR_ID
871   = generic_ERROR_ID recSelErrIdKey SLIT("recSelError")
872 rEC_CON_ERROR_ID
873   = generic_ERROR_ID recConErrorIdKey SLIT("recConError")
874 rEC_UPD_ERROR_ID
875   = generic_ERROR_ID recUpdErrorIdKey SLIT("recUpdError")
876 iRREFUT_PAT_ERROR_ID
877   = generic_ERROR_ID irrefutPatErrorIdKey SLIT("irrefutPatError")
878 nON_EXHAUSTIVE_GUARDS_ERROR_ID
879   = generic_ERROR_ID nonExhaustiveGuardsErrorIdKey SLIT("nonExhaustiveGuardsError")
880 nO_METHOD_BINDING_ERROR_ID
881   = generic_ERROR_ID noMethodBindingErrorIdKey SLIT("noMethodBindingError")
882
883 aBSENT_ERROR_ID
884   = pc_bottoming_Id absentErrorIdKey pREL_ERR SLIT("absentErr")
885         (mkSigmaTy [openAlphaTyVar] [] openAlphaTy)
886
887 pAR_ERROR_ID
888   = pcMiscPrelId parErrorIdKey pREL_ERR SLIT("parError")
889     (mkSigmaTy [openAlphaTyVar] [] openAlphaTy) noCafNoTyGenIdInfo
890 \end{code}
891
892
893 %************************************************************************
894 %*                                                                      *
895 \subsection{Utilities}
896 %*                                                                      *
897 %************************************************************************
898
899 \begin{code}
900 pcMiscPrelId :: Unique{-IdKey-} -> Module -> FAST_STRING -> Type -> IdInfo -> Id
901 pcMiscPrelId key mod str ty info
902   = let
903         name = mkWiredInName mod (mkVarOcc str) key
904         imp  = mkVanillaGlobal name ty info -- the usual case...
905     in
906     imp
907     -- We lie and say the thing is imported; otherwise, we get into
908     -- a mess with dependency analysis; e.g., core2stg may heave in
909     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
910     -- being compiled, then it's just a matter of luck if the definition
911     -- will be in "the right place" to be in scope.
912
913 pc_bottoming_Id key mod name ty
914  = pcMiscPrelId key mod name ty bottoming_info
915  where
916     strict_sig     = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
917     bottoming_info = noCafNoTyGenIdInfo `setNewStrictnessInfo` Just strict_sig
918         -- these "bottom" out, no matter what their arguments
919
920 generic_ERROR_ID u n = pc_bottoming_Id u pREL_ERR n errorTy
921
922 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
923 openAlphaTy  = mkTyVarTy openAlphaTyVar
924 openBetaTy   = mkTyVarTy openBetaTyVar
925
926 errorTy  :: Type
927 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] 
928                                                    openAlphaTy)
929     -- Notice the openAlphaTyVar.  It says that "error" can be applied
930     -- to unboxed as well as boxed types.  This is OK because it never
931     -- returns, so the return type is irrelevant.
932 \end{code}
933