[project @ 2001-05-22 13:43:14 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 Type             ( Type, ThetaType, mkDictTy, mkPredTys, mkTyConApp,
43                           mkTyVarTys, repType, isNewType,
44                           mkFunTys, mkFunTy, mkSigmaTy, splitSigmaTy, 
45                           isUnLiftedType, mkForAllTys, mkTyVarTy, tyVarsOfType,
46                           splitFunTys, splitForAllTys, 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 )
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
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 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
240                mkLams tyvars $ mkLams dict_args $ Lam id_arg1 $
241                Note (Coerce result_ty (head orig_arg_tys)) (Var 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                    | isNewType arg_ty ->
307                         Let (NonRec coerced_arg 
308                                 (Note (Coerce rep_ty arg_ty) (Var arg)))
309                               (do_unbox coerced_arg rep_ty i')
310                    | otherwise ->
311                         do_unbox arg arg_ty i
312                   where
313                     ([coerced_arg],i') = mkLocals i [rep_ty]
314                     arg_ty = idType arg
315                     rep_ty = repType arg_ty
316
317                     do_unbox arg ty i = 
318                         case splitProductType "do_unbox" ty of
319                            (tycon, tycon_args, con, tys) ->
320                                    Case (Var arg) arg [(DataAlt con, con_args,
321                                         body i' (reverse con_args ++ rep_args))]
322                               where 
323                                 (con_args, i')   = mkLocals i tys
324 \end{code}
325
326
327 %************************************************************************
328 %*                                                                      *
329 \subsection{Record selectors}
330 %*                                                                      *
331 %************************************************************************
332
333 We're going to build a record selector unfolding that looks like this:
334
335         data T a b c = T1 { ..., op :: a, ...}
336                      | T2 { ..., op :: a, ...}
337                      | T3
338
339         sel = /\ a b c -> \ d -> case d of
340                                     T1 ... x ... -> x
341                                     T2 ... x ... -> x
342                                     other        -> error "..."
343
344 Similarly for newtypes
345
346         newtype N a = MkN { unN :: a->a }
347
348         unN :: N a -> a -> a
349         unN n = coerce (a->a) n
350         
351 We need to take a little care if the field has a polymorphic type:
352
353         data R = R { f :: forall a. a->a }
354
355 Then we want
356
357         f :: forall a. R -> a -> a
358         f = /\ a \ r = case r of
359                           R f -> f a
360
361 (not f :: R -> forall a. a->a, which gives the type inference mechanism 
362 problems at call sites)
363
364 Similarly for newtypes
365
366         newtype N = MkN { unN :: forall a. a->a }
367
368         unN :: forall a. N -> a -> a
369         unN = /\a -> \n:N -> coerce (a->a) n
370
371 \begin{code}
372 mkRecordSelId tycon field_label unpack_id unpackUtf8_id
373         -- Assumes that all fields with the same field label have the same type
374         --
375         -- Annoyingly, we have to pass in the unpackCString# Id, because
376         -- we can't conjure it up out of thin air
377   = sel_id
378   where
379     sel_id     = mkGlobalId (RecordSelId field_label) (fieldLabelName field_label) selector_ty info
380     field_ty   = fieldLabelType field_label
381     data_cons  = tyConDataCons tycon
382     tyvars     = tyConTyVars tycon      -- These scope over the types in 
383                                         -- the FieldLabels of constructors of this type
384     data_ty   = mkTyConApp tycon tyvar_tys
385     tyvar_tys = mkTyVarTys tyvars
386
387     tycon_theta = tyConTheta tycon      -- The context on the data decl
388                                         --   eg data (Eq a, Ord b) => T a b = ...
389     dict_tys  = [mkPredTy pred | pred <- tycon_theta, 
390                                  needed_dict pred]
391     needed_dict pred = or [ pred `elem` (dataConTheta dc) 
392                           | (DataAlt dc, _, _) <- the_alts]
393     n_dict_tys = length dict_tys
394
395     (field_tyvars,field_theta,field_tau) = splitSigmaTy field_ty
396     field_dict_tys                       = map mkPredTy field_theta
397     n_field_dict_tys                     = length field_dict_tys
398         -- If the field has a universally quantified type we have to 
399         -- be a bit careful.  Suppose we have
400         --      data R = R { op :: forall a. Foo a => a -> a }
401         -- Then we can't give op the type
402         --      op :: R -> forall a. Foo a => a -> a
403         -- because the typechecker doesn't understand foralls to the
404         -- right of an arrow.  The "right" type to give it is
405         --      op :: forall a. Foo a => R -> a -> a
406         -- But then we must generate the right unfolding too:
407         --      op = /\a -> \dfoo -> \ r ->
408         --           case r of
409         --              R op -> op a dfoo
410         -- Note that this is exactly the type we'd infer from a user defn
411         --      op (R op) = op
412
413         -- Very tiresomely, the selectors are (unnecessarily!) overloaded over
414         -- just the dictionaries in the types of the constructors that contain
415         -- the relevant field.  Urgh.  
416         -- NB: this code relies on the fact that DataCons are quantified over
417         -- the identical type variables as their parent TyCon
418
419     selector_ty :: Type
420     selector_ty  = mkForAllTys tyvars $ mkForAllTys field_tyvars $
421                    mkFunTys dict_tys  $  mkFunTys field_dict_tys $
422                    mkFunTy data_ty field_tau
423       
424     arity = 1 + n_dict_tys + n_field_dict_tys
425     info = noCafNoTyGenIdInfo
426            `setCgInfo`          (CgInfo arity caf_info)
427            `setArityInfo`       exactArity arity
428            `setUnfoldingInfo`   unfolding       
429         -- ToDo: consider adding further IdInfo
430
431     unfolding = mkTopUnfolding sel_rhs
432
433         -- Allocate Ids.  We do it a funny way round because field_dict_tys is
434         -- almost always empty.  Also note that we use length_tycon_theta
435         -- rather than n_dict_tys, because the latter gives an infinite loop:
436         -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
437         -- on arity, which depends on n_dict tys.  Sigh!  Mega sigh!
438     field_dict_base    = length tycon_theta + 1
439     dict_id_base       = field_dict_base + n_field_dict_tys
440     field_base         = dict_id_base + 1
441     dict_ids           = mkTemplateLocalsNum  1               dict_tys
442     field_dict_ids     = mkTemplateLocalsNum  field_dict_base field_dict_tys
443     data_id            = mkTemplateLocal      dict_id_base    data_ty
444
445     alts      = map mk_maybe_alt data_cons
446     the_alts  = catMaybes alts
447
448     no_default = all isJust alts        -- No default needed
449     default_alt | no_default = []
450                 | otherwise  = [(DEFAULT, [], error_expr)]
451
452         -- the default branch may have CAF refs, because it calls recSelError etc.
453     caf_info    | no_default = NoCafRefs
454                 | otherwise  = MayHaveCafRefs
455
456     sel_rhs = mkLams tyvars   $ mkLams field_tyvars $ 
457               mkLams dict_ids $ mkLams field_dict_ids $
458               Lam data_id     $ sel_body
459
460     sel_body | isNewTyCon tycon = Note (Coerce field_tau data_ty) (Var data_id)
461              | otherwise        = Case (Var data_id) data_id (the_alts ++ default_alt)
462
463     mk_maybe_alt data_con 
464           = case maybe_the_arg_id of
465                 Nothing         -> Nothing
466                 Just the_arg_id -> Just (DataAlt data_con, real_args, mkLets binds body)
467                   where
468                     body               = mkVarApps (mkVarApps (Var the_arg_id) field_tyvars) field_dict_ids
469                     strict_marks       = dataConStrictMarks data_con
470                     (binds, real_args) = rebuildConArgs arg_ids strict_marks
471                                                         (map mkBuiltinUnique [unpack_base..])
472         where
473             arg_ids = mkTemplateLocalsNum field_base (dataConInstOrigArgTys data_con tyvar_tys)
474
475             unpack_base = field_base + length arg_ids
476
477                                 -- arity+1 avoids all shadowing
478             maybe_the_arg_id  = assocMaybe (field_lbls `zip` arg_ids) field_label
479             field_lbls        = dataConFieldLabels data_con
480
481     error_expr = mkApps (Var rEC_SEL_ERROR_ID) [Type field_tau, err_string]
482     err_string
483         | all safeChar full_msg
484             = App (Var unpack_id) (Lit (MachStr (_PK_ full_msg)))
485         | otherwise
486             = App (Var unpackUtf8_id) (Lit (MachStr (_PK_ (stringToUtf8 (map ord full_msg)))))
487         where
488         safeChar c = c >= '\1' && c <= '\xFF'
489         -- TODO: Putting this Unicode stuff here is ugly. Find a better
490         -- generic place to make string literals. This logic is repeated
491         -- in DsUtils.
492     full_msg   = showSDoc (sep [text "No match in record selector", ppr sel_id]) 
493
494
495 -- This rather ugly function converts the unpacked data con 
496 -- arguments back into their packed form.
497
498 rebuildConArgs
499   :: [Id]                       -- Source-level args
500   -> [StrictnessMark]           -- Strictness annotations (per-arg)
501   -> [Unique]                   -- Uniques for the new Ids
502   -> ([CoreBind], [Id])         -- A binding for each source-level arg, plus
503                                 -- a list of the representation-level arguments 
504 -- e.g.   data T = MkT Int !Int
505 --
506 -- rebuild [x::Int, y::Int] [Not, Unbox]
507 --  = ([ y = I# t ], [x,t])
508
509 rebuildConArgs []         stricts us = ([], [])
510
511 -- Type variable case
512 rebuildConArgs (arg:args) stricts us 
513   | isTyVar arg
514   = let (binds, args') = rebuildConArgs args stricts us
515     in  (binds, arg:args')
516
517 -- Term variable case
518 rebuildConArgs (arg:args) (str:stricts) us
519   | isMarkedUnboxed str
520   = let
521         arg_ty  = idType arg
522         prod_ty | isNewType arg_ty = repType arg_ty
523                 | otherwise        = arg_ty
524
525         (_, tycon_args, pack_con, con_arg_tys)
526                  = splitProductType "rebuildConArgs" prod_ty
527
528         unpacked_args  = zipWith (mkSysLocal SLIT("rb")) us con_arg_tys
529
530         (binds, args') = rebuildConArgs args stricts 
531                                 (drop (length con_arg_tys) us)
532
533         coerce | isNewType arg_ty = Note (Coerce arg_ty prod_ty) con_app
534                | otherwise        = con_app
535
536         con_app        = mkConApp pack_con (map Type tycon_args ++ 
537                                             map Var  unpacked_args)
538     in
539     (NonRec arg coerce : binds, unpacked_args ++ args')
540
541   | otherwise
542   = let (binds, args') = rebuildConArgs args stricts us
543     in  (binds, arg:args')
544 \end{code}
545
546
547 %************************************************************************
548 %*                                                                      *
549 \subsection{Dictionary selectors}
550 %*                                                                      *
551 %************************************************************************
552
553 Selecting a field for a dictionary.  If there is just one field, then
554 there's nothing to do.  
555
556 ToDo: unify with mkRecordSelId.
557
558 \begin{code}
559 mkDictSelId :: Name -> Class -> Id
560 mkDictSelId name clas
561   = sel_id
562   where
563     ty        = exprType rhs
564     sel_id    = mkGlobalId (RecordSelId field_lbl) name ty info
565     field_lbl = mkFieldLabel name tycon ty tag
566     tag       = assoc "MkId.mkDictSelId" (classSelIds clas `zip` allFieldLabelTags) sel_id
567
568     info      = noCafNoTyGenIdInfo
569                 `setCgArity`        1
570                 `setArityInfo`      exactArity 1
571                 `setUnfoldingInfo`  unfolding
572                 
573         -- We no longer use 'must-inline' on record selectors.  They'll
574         -- inline like crazy if they scrutinise a constructor
575
576     unfolding = mkTopUnfolding rhs
577
578     tyvars  = classTyVars clas
579
580     tycon      = classTyCon clas
581     [data_con] = tyConDataCons tycon
582     tyvar_tys  = mkTyVarTys tyvars
583     arg_tys    = dataConArgTys data_con tyvar_tys
584     the_arg_id = arg_ids !! (tag - firstFieldLabelTag)
585
586     dict_ty    = mkDictTy clas tyvar_tys
587     (dict_id:arg_ids) = mkTemplateLocals (dict_ty : arg_tys)
588
589     rhs | isNewTyCon tycon = mkLams tyvars $ Lam dict_id $
590                              Note (Coerce (head arg_tys) dict_ty) (Var dict_id)
591         | otherwise        = mkLams tyvars $ Lam dict_id $
592                              Case (Var dict_id) dict_id
593                                   [(DataAlt data_con, arg_ids, Var the_arg_id)]
594 \end{code}
595
596
597 %************************************************************************
598 %*                                                                      *
599 \subsection{Primitive operations
600 %*                                                                      *
601 %************************************************************************
602
603 \begin{code}
604 mkPrimOpId :: PrimOp -> Id
605 mkPrimOpId prim_op 
606   = id
607   where
608     (tyvars,arg_tys,res_ty, arity, strict_info) = primOpSig prim_op
609     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
610     name = mkPrimOpIdName prim_op
611     id   = mkGlobalId (PrimOpId prim_op) name ty info
612                 
613     info = noCafNoTyGenIdInfo
614            `setSpecInfo`        rules
615            `setCgArity`         arity
616            `setArityInfo`       exactArity arity
617            `setStrictnessInfo`  strict_info
618
619     rules = maybe emptyCoreRules (addRule emptyCoreRules id)
620                 (primOpRule prim_op)
621
622
623 -- For each ccall we manufacture a separate CCallOpId, giving it
624 -- a fresh unique, a type that is correct for this particular ccall,
625 -- and a CCall structure that gives the correct details about calling
626 -- convention etc.  
627 --
628 -- The *name* of this Id is a local name whose OccName gives the full
629 -- details of the ccall, type and all.  This means that the interface 
630 -- file reader can reconstruct a suitable Id
631
632 mkFCallId :: Unique -> ForeignCall -> Type -> Id
633 mkFCallId uniq fcall ty
634   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
635         -- A CCallOpId should have no free type variables; 
636         -- when doing substitutions won't substitute over it
637     mkGlobalId (FCallId fcall) name ty info
638   where
639     occ_str = showSDocIface (braces (ppr fcall <+> ppr ty))
640         -- The "occurrence name" of a ccall is the full info about the
641         -- ccall; it is encoded, but may have embedded spaces etc!
642
643     name = mkFCallName uniq occ_str
644
645     info = noCafNoTyGenIdInfo
646            `setCgArity`         arity
647            `setArityInfo`       exactArity arity
648            `setStrictnessInfo`  strict_info
649
650     (_, tau)     = splitForAllTys ty
651     (arg_tys, _) = splitFunTys tau
652     arity        = length arg_tys
653     strict_info  = mkStrictnessInfo (take arity (repeat wwPrim), False)
654 \end{code}
655
656
657 %************************************************************************
658 %*                                                                      *
659 \subsection{DictFuns and default methods}
660 %*                                                                      *
661 %************************************************************************
662
663 \begin{code}
664 mkDefaultMethodId dm_name ty
665   = mkVanillaGlobal dm_name ty noCafNoTyGenIdInfo
666
667 mkDictFunId :: Name             -- Name to use for the dict fun;
668             -> Class 
669             -> [TyVar]
670             -> [Type]
671             -> ThetaType
672             -> Id
673
674 mkDictFunId dfun_name clas inst_tyvars inst_tys dfun_theta
675   = mkVanillaGlobal dfun_name dfun_ty noCafNoTyGenIdInfo
676   where
677     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
678
679 {-  1 dec 99: disable the Mark Jones optimisation for the sake
680     of compatibility with Hugs.
681     See `types/InstEnv' for a discussion related to this.
682
683     (class_tyvars, sc_theta, _, _) = classBigSig clas
684     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
685     sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys) sc_theta
686     dfun_theta = case inst_decl_theta of
687                    []    -> []  -- If inst_decl_theta is empty, then we don't
688                                 -- want to have any dict arguments, so that we can
689                                 -- expose the constant methods.
690
691                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
692                                 -- Otherwise we pass the superclass dictionaries to
693                                 -- the dictionary function; the Mark Jones optimisation.
694                                 --
695                                 -- NOTE the "nub".  I got caught by this one:
696                                 --   class Monad m => MonadT t m where ...
697                                 --   instance Monad m => MonadT (EnvT env) m where ...
698                                 -- Here, the inst_decl_theta has (Monad m); but so
699                                 -- does the sc_theta'!
700                                 --
701                                 -- NOTE the "not_const".  I got caught by this one too:
702                                 --   class Foo a => Baz a b where ...
703                                 --   instance Wob b => Baz T b where..
704                                 -- Now sc_theta' has Foo T
705 -}
706 \end{code}
707
708
709 %************************************************************************
710 %*                                                                      *
711 \subsection{Un-definable}
712 %*                                                                      *
713 %************************************************************************
714
715 These two can't be defined in Haskell.
716
717 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
718 just gets expanded into a type coercion wherever it occurs.  Hence we
719 add it as a built-in Id with an unfolding here.
720
721 The type variables we use here are "open" type variables: this means
722 they can unify with both unlifted and lifted types.  Hence we provide
723 another gun with which to shoot yourself in the foot.
724
725 \begin{code}
726 unsafeCoerceId
727   = pcMiscPrelId unsafeCoerceIdKey pREL_GHC SLIT("unsafeCoerce#") ty info
728   where
729     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
730            
731
732     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
733                       (mkFunTy openAlphaTy openBetaTy)
734     [x] = mkTemplateLocals [openAlphaTy]
735     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
736           Note (Coerce openBetaTy openAlphaTy) (Var x)
737 \end{code}
738
739
740 @getTag#@ is another function which can't be defined in Haskell.  It needs to
741 evaluate its argument and call the dataToTag# primitive.
742
743 \begin{code}
744 getTagId
745   = pcMiscPrelId getTagIdKey pREL_GHC SLIT("getTag#") ty info
746   where
747     info = noCafNoTyGenIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
748         -- We don't provide a defn for this; you must inline it
749
750     ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy intPrimTy)
751     [x,y] = mkTemplateLocals [alphaTy,alphaTy]
752     rhs = mkLams [alphaTyVar,x] $
753           Case (Var x) y [ (DEFAULT, [], mkApps (Var dataToTagId) [Type alphaTy, Var y]) ]
754
755 dataToTagId = mkPrimOpId DataToTagOp
756 \end{code}
757
758 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
759 nasty as-is, change it back to a literal (@Literal@).
760
761 \begin{code}
762 realWorldPrimId -- :: State# RealWorld
763   = pcMiscPrelId realWorldPrimIdKey pREL_GHC SLIT("realWorld#")
764                  realWorldStatePrimTy
765                  (noCafNoTyGenIdInfo `setUnfoldingInfo` mkOtherCon [])
766         -- The mkOtherCon makes it look that realWorld# is evaluated
767         -- which in turn makes Simplify.interestingArg return True,
768         -- which in turn makes INLINE things applied to realWorld# likely
769         -- to be inlined
770 \end{code}
771
772
773 %************************************************************************
774 %*                                                                      *
775 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
776 %*                                                                      *
777 %************************************************************************
778
779 GHC randomly injects these into the code.
780
781 @patError@ is just a version of @error@ for pattern-matching
782 failures.  It knows various ``codes'' which expand to longer
783 strings---this saves space!
784
785 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
786 well shouldn't be yanked on, but if one is, then you will get a
787 friendly message from @absentErr@ (rather than a totally random
788 crash).
789
790 @parError@ is a special version of @error@ which the compiler does
791 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
792 templates, but we don't ever expect to generate code for it.
793
794 \begin{code}
795 eRROR_ID
796   = pc_bottoming_Id errorIdKey pREL_ERR SLIT("error") errorTy
797 pAT_ERROR_ID
798   = generic_ERROR_ID patErrorIdKey SLIT("patError")
799 rEC_SEL_ERROR_ID
800   = generic_ERROR_ID recSelErrIdKey SLIT("recSelError")
801 rEC_CON_ERROR_ID
802   = generic_ERROR_ID recConErrorIdKey SLIT("recConError")
803 rEC_UPD_ERROR_ID
804   = generic_ERROR_ID recUpdErrorIdKey SLIT("recUpdError")
805 iRREFUT_PAT_ERROR_ID
806   = generic_ERROR_ID irrefutPatErrorIdKey SLIT("irrefutPatError")
807 nON_EXHAUSTIVE_GUARDS_ERROR_ID
808   = generic_ERROR_ID nonExhaustiveGuardsErrorIdKey SLIT("nonExhaustiveGuardsError")
809 nO_METHOD_BINDING_ERROR_ID
810   = generic_ERROR_ID noMethodBindingErrorIdKey SLIT("noMethodBindingError")
811
812 aBSENT_ERROR_ID
813   = pc_bottoming_Id absentErrorIdKey pREL_ERR SLIT("absentErr")
814         (mkSigmaTy [openAlphaTyVar] [] openAlphaTy)
815
816 pAR_ERROR_ID
817   = pcMiscPrelId parErrorIdKey pREL_ERR SLIT("parError")
818     (mkSigmaTy [openAlphaTyVar] [] openAlphaTy) noCafNoTyGenIdInfo
819 \end{code}
820
821
822 %************************************************************************
823 %*                                                                      *
824 \subsection{Utilities}
825 %*                                                                      *
826 %************************************************************************
827
828 \begin{code}
829 pcMiscPrelId :: Unique{-IdKey-} -> Module -> FAST_STRING -> Type -> IdInfo -> Id
830 pcMiscPrelId key mod str ty info
831   = let
832         name = mkWiredInName mod (mkVarOcc str) key
833         imp  = mkVanillaGlobal name ty info -- the usual case...
834     in
835     imp
836     -- We lie and say the thing is imported; otherwise, we get into
837     -- a mess with dependency analysis; e.g., core2stg may heave in
838     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
839     -- being compiled, then it's just a matter of luck if the definition
840     -- will be in "the right place" to be in scope.
841
842 pc_bottoming_Id key mod name ty
843  = pcMiscPrelId key mod name ty bottoming_info
844  where
845     bottoming_info = noCafNoTyGenIdInfo 
846                      `setStrictnessInfo` mkStrictnessInfo ([wwStrict], True)
847
848         -- these "bottom" out, no matter what their arguments
849
850 generic_ERROR_ID u n = pc_bottoming_Id u pREL_ERR n errorTy
851
852 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
853 openAlphaTy  = mkTyVarTy openAlphaTyVar
854 openBetaTy   = mkTyVarTy openBetaTyVar
855
856 errorTy  :: Type
857 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] 
858                                                    openAlphaTy)
859     -- Notice the openAlphaTyVar.  It says that "error" can be applied
860     -- to unboxed as well as boxed types.  This is OK because it never
861     -- returns, so the return type is irrelevant.
862 \end{code}
863