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