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