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