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