[project @ 2003-01-13 17:01:22 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, 
21         mkPrimOpId, mkFCallId,
22
23         mkReboxingAlt, mkNewTypeBody,
24
25         -- And some particular Ids; see below for why they are wired in
26         wiredInIds, ghcPrimIds,
27         unsafeCoerceId, realWorldPrimId, voidArgId, nullAddrId, seqId,
28         lazyId, lazyIdUnfolding, lazyIdKey,
29
30         mkRuntimeErrorApp,
31         rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
32         nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
33         pAT_ERROR_ID
34     ) where
35
36 #include "HsVersions.h"
37
38
39 import BasicTypes       ( Arity, StrictnessMark(..), isMarkedUnboxed, isMarkedStrict )
40 import TysPrim          ( openAlphaTyVars, alphaTyVar, alphaTy, betaTyVar, betaTy,
41                           intPrimTy, realWorldStatePrimTy, addrPrimTy
42                         )
43 import TysWiredIn       ( charTy, mkListTy )
44 import PrelRules        ( primOpRules )
45 import Rules            ( addRule )
46 import TcType           ( Type, ThetaType, mkDictTy, mkPredTys, mkTyConApp,
47                           mkTyVarTys, mkClassPred, tcEqPred,
48                           mkFunTys, mkFunTy, mkSigmaTy, tcSplitSigmaTy, 
49                           isUnLiftedType, mkForAllTys, mkTyVarTy, tyVarsOfType,
50                           tcSplitFunTys, tcSplitForAllTys, mkPredTy
51                         )
52 import CoreUtils        ( exprType )
53 import CoreUnfold       ( mkTopUnfolding, mkCompulsoryUnfolding, mkOtherCon )
54 import Literal          ( Literal(..), nullAddrLit )
55 import TyCon            ( TyCon, isNewTyCon, tyConTyVars, tyConDataCons,
56                           tyConTheta, isProductTyCon, isDataTyCon, isRecursiveTyCon )
57 import Class            ( Class, classTyCon, classTyVars, classSelIds )
58 import Var              ( Id, TyVar, Var )
59 import VarSet           ( isEmptyVarSet )
60 import Name             ( mkFCallName, Name )
61 import PrimOp           ( PrimOp(DataToTagOp), primOpSig, mkPrimOpIdName )
62 import ForeignCall      ( ForeignCall )
63 import DataCon          ( DataCon, 
64                           dataConFieldLabels, dataConRepArity, dataConTyCon,
65                           dataConArgTys, dataConRepType, 
66                           dataConOrigArgTys,
67                           dataConName, dataConTheta,
68                           dataConSig, dataConStrictMarks, dataConWorkId,
69                           splitProductType
70                         )
71 import Id               ( idType, mkGlobalId, mkVanillaGlobal, mkSysLocal, mkLocalId,
72                           mkTemplateLocals, mkTemplateLocalsNum, setIdLocalExported,
73                           mkTemplateLocal, idNewStrictness, idName
74                         )
75 import IdInfo           ( IdInfo, noCafIdInfo, hasCafIdInfo,
76                           setUnfoldingInfo, 
77                           setArityInfo, setSpecInfo, setCafInfo,
78                           setAllStrictnessInfo,
79                           GlobalIdDetails(..), CafInfo(..)
80                         )
81 import NewDemand        ( mkStrictSig, strictSigResInfo, DmdResult(..),
82                           mkTopDmdType, topDmd, evalDmd, lazyDmd, retCPR,
83                           Demand(..), Demands(..) )
84 import FieldLabel       ( mkFieldLabel, fieldLabelName, 
85                           firstFieldLabelTag, allFieldLabelTags, fieldLabelType
86                         )
87 import DmdAnal          ( dmdAnalTopRhs )
88 import CoreSyn
89 import Unique           ( mkBuiltinUnique )
90 import Maybes
91 import PrelNames
92 import Maybe            ( isJust )
93 import Util             ( dropList, isSingleton )
94 import Outputable
95 import FastString
96 import ListSetOps       ( assoc, assocMaybe )
97 import UnicodeUtil      ( stringToUtf8 )
98 import List             ( nubBy )
99 \end{code}              
100
101 %************************************************************************
102 %*                                                                      *
103 \subsection{Wired in Ids}
104 %*                                                                      *
105 %************************************************************************
106
107 \begin{code}
108 wiredInIds
109   = [   -- These error-y things are wired in because we don't yet have
110         -- a way to express in an interface file that the result type variable
111         -- is 'open'; that is can be unified with an unboxed type
112         -- 
113         -- [The interface file format now carry such information, but there's
114         -- no way yet of expressing at the definition site for these 
115         -- error-reporting functions that they have an 'open' 
116         -- result type. -- sof 1/99]
117
118     eRROR_ID,   -- This one isn't used anywhere else in the compiler
119                 -- But we still need it in wiredInIds so that when GHC
120                 -- compiles a program that mentions 'error' we don't
121                 -- import its type from the interface file; we just get
122                 -- the Id defined here.  Which has an 'open-tyvar' type.
123
124     rUNTIME_ERROR_ID,
125     iRREFUT_PAT_ERROR_ID,
126     nON_EXHAUSTIVE_GUARDS_ERROR_ID,
127     nO_METHOD_BINDING_ERROR_ID,
128     pAT_ERROR_ID,
129     rEC_CON_ERROR_ID,
130
131     lazyId
132     ] ++ ghcPrimIds
133
134 -- These Ids are exported from GHC.Prim
135 ghcPrimIds
136   = [   -- These can't be defined in Haskell, but they have
137         -- perfectly reasonable unfoldings in Core
138     realWorldPrimId,
139     unsafeCoerceId,
140     nullAddrId,
141     getTagId,
142     seqId
143     ]
144 \end{code}
145
146 %************************************************************************
147 %*                                                                      *
148 \subsection{Data constructors}
149 %*                                                                      *
150 %************************************************************************
151
152 \begin{code}
153 mkDataConId :: Name -> DataCon -> Id
154         -- Makes the *worker* for the data constructor; that is, the function
155         -- that takes the reprsentation arguments and builds the constructor.
156 mkDataConId work_name data_con
157   = mkGlobalId (DataConId data_con) work_name (dataConRepType data_con) info
158   where
159     info = noCafIdInfo
160            `setArityInfo`               arity
161            `setAllStrictnessInfo`       Just strict_sig
162
163     arity      = dataConRepArity data_con
164
165     strict_sig = mkStrictSig (mkTopDmdType (replicate arity topDmd) cpr_info)
166         -- Notice that we do *not* say the worker is strict
167         -- even if the data constructor is declared strict
168         --      e.g.    data T = MkT !(Int,Int)
169         -- Why?  Because the *wrapper* is strict (and its unfolding has case
170         -- expresssions that do the evals) but the *worker* itself is not.
171         -- If we pretend it is strict then when we see
172         --      case x of y -> $wMkT y
173         -- the simplifier thinks that y is "sure to be evaluated" (because
174         -- $wMkT is strict) and drops the case.  No, $wMkT is not strict.
175         --
176         -- When the simplifer sees a pattern 
177         --      case e of MkT x -> ...
178         -- it uses the dataConRepStrictness of MkT to mark x as evaluated;
179         -- but that's fine... dataConRepStrictness comes from the data con
180         -- not from the worker Id.
181
182     tycon = dataConTyCon data_con
183     cpr_info | isProductTyCon tycon && 
184                isDataTyCon tycon    &&
185                arity > 0            &&
186                arity <= mAX_CPR_SIZE    = retCPR
187              | otherwise                = TopRes
188         -- RetCPR is only true for products that are real data types;
189         -- that is, not unboxed tuples or [non-recursive] newtypes
190
191 mAX_CPR_SIZE :: Arity
192 mAX_CPR_SIZE = 10
193 -- We do not treat very big tuples as CPR-ish:
194 --      a) for a start we get into trouble because there aren't 
195 --         "enough" unboxed tuple types (a tiresome restriction, 
196 --         but hard to fix), 
197 --      b) more importantly, big unboxed tuples get returned mainly
198 --         on the stack, and are often then allocated in the heap
199 --         by the caller.  So doing CPR for them may in fact make
200 --         things worse.
201 \end{code}
202
203 The wrapper for a constructor is an ordinary top-level binding that evaluates
204 any strict args, unboxes any args that are going to be flattened, and calls
205 the worker.
206
207 We're going to build a constructor that looks like:
208
209         data (Data a, C b) =>  T a b = T1 !a !Int b
210
211         T1 = /\ a b -> 
212              \d1::Data a, d2::C b ->
213              \p q r -> case p of { p ->
214                        case q of { q ->
215                        Con T1 [a,b] [p,q,r]}}
216
217 Notice that
218
219 * d2 is thrown away --- a context in a data decl is used to make sure
220   one *could* construct dictionaries at the site the constructor
221   is used, but the dictionary isn't actually used.
222
223 * We have to check that we can construct Data dictionaries for
224   the types a and Int.  Once we've done that we can throw d1 away too.
225
226 * We use (case p of q -> ...) to evaluate p, rather than "seq" because
227   all that matters is that the arguments are evaluated.  "seq" is 
228   very careful to preserve evaluation order, which we don't need
229   to be here.
230
231   You might think that we could simply give constructors some strictness
232   info, like PrimOps, and let CoreToStg do the let-to-case transformation.
233   But we don't do that because in the case of primops and functions strictness
234   is a *property* not a *requirement*.  In the case of constructors we need to
235   do something active to evaluate the argument.
236
237   Making an explicit case expression allows the simplifier to eliminate
238   it in the (common) case where the constructor arg is already evaluated.
239
240 \begin{code}
241 mkDataConWrapId data_con
242   = mkGlobalId (DataConWrapId data_con) (dataConName data_con) wrap_ty info
243   where
244     work_id = dataConWorkId data_con
245
246     info = noCafIdInfo
247            `setUnfoldingInfo`   wrap_unf
248                 -- The NoCaf-ness is set by noCafIdInfo
249            `setArityInfo`       arity
250                 -- It's important to specify the arity, so that partial
251                 -- applications are treated as values
252            `setAllStrictnessInfo`       Just wrap_sig
253
254     wrap_sig = mkStrictSig (mkTopDmdType arg_dmds res_info)
255     res_info = strictSigResInfo (idNewStrictness work_id)
256     arg_dmds = map mk_dmd strict_marks
257     mk_dmd str | isMarkedStrict str = evalDmd
258                | otherwise          = lazyDmd
259         -- The Cpr info can be important inside INLINE rhss, where the
260         -- wrapper constructor isn't inlined.
261         -- And the argument strictness can be important too; we
262         -- may not inline a contructor when it is partially applied.
263         -- For example:
264         --      data W = C !Int !Int !Int
265         --      ...(let w = C x in ...(w p q)...)...
266         -- we want to see that w is strict in its two arguments
267
268     wrap_unf | isNewTyCon tycon
269              = ASSERT( null ex_tyvars && null ex_dict_args && isSingleton orig_arg_tys )
270                 -- No existentials on a newtype, but it can have a context
271                 -- e.g.         newtype Eq a => T a = MkT (...)
272                 mkTopUnfolding $ Note InlineMe $
273                 mkLams tyvars $ Lam id_arg1 $ 
274                 mkNewTypeBody tycon result_ty (Var id_arg1)
275
276              | not (any isMarkedStrict strict_marks)
277              = mkCompulsoryUnfolding (Var work_id)
278                         -- The common case.  Not only is this efficient,
279                         -- but it also ensures that the wrapper is replaced
280                         -- by the worker even when there are no args.
281                         --              f (:) x
282                         -- becomes 
283                         --              f $w: x
284                         -- This is really important in rule matching,
285                         -- (We could match on the wrappers,
286                         -- but that makes it less likely that rules will match
287                         -- when we bring bits of unfoldings together.)
288                 --
289                 -- NB:  because of this special case, (map (:) ys) turns into
290                 --      (map $w: ys).  The top-level defn for (:) is never used.
291                 --      This is somewhat of a bore, but I'm currently leaving it 
292                 --      as is, so that there still is a top level curried (:) for
293                 --      the interpreter to call.
294
295              | otherwise
296              = mkTopUnfolding $ Note InlineMe $
297                mkLams all_tyvars $ 
298                mkLams ex_dict_args $ mkLams id_args $
299                foldr mk_case con_app 
300                      (zip (ex_dict_args++id_args) strict_marks) i3 []
301
302     con_app i rep_ids = mkApps (Var work_id)
303                                (map varToCoreExpr (all_tyvars ++ reverse rep_ids))
304
305     (tyvars, _, ex_tyvars, ex_theta, orig_arg_tys, tycon) = dataConSig data_con
306     all_tyvars   = tyvars ++ ex_tyvars
307
308     ex_dict_tys  = mkPredTys ex_theta
309     all_arg_tys  = ex_dict_tys ++ orig_arg_tys
310     result_ty    = mkTyConApp tycon (mkTyVarTys tyvars)
311
312     wrap_ty = mkForAllTys all_tyvars (mkFunTys all_arg_tys result_ty)
313         -- We used to include the stupid theta in the wrapper's args
314         -- but now we don't.  Instead the type checker just injects these
315         -- extra constraints where necessary.
316
317     mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
318                    where
319                      n = length tys
320
321     (ex_dict_args,i2)  = mkLocals 1  ex_dict_tys
322     (id_args,i3)       = mkLocals i2 orig_arg_tys
323     arity              = i3-1
324     (id_arg1:_)   = id_args             -- Used for newtype only
325
326     strict_marks  = dataConStrictMarks data_con
327
328     mk_case 
329            :: (Id, StrictnessMark)      -- Arg, strictness
330            -> (Int -> [Id] -> CoreExpr) -- Body
331            -> Int                       -- Next rep arg id
332            -> [Id]                      -- Rep args so far, reversed
333            -> CoreExpr
334     mk_case (arg,strict) body i rep_args
335           = case strict of
336                 NotMarkedStrict -> body i (arg:rep_args)
337                 MarkedStrict 
338                    | isUnLiftedType (idType arg) -> body i (arg:rep_args)
339                    | otherwise ->
340                         Case (Var arg) arg [(DEFAULT,[], body i (arg:rep_args))]
341
342                 MarkedUnboxed
343                    -> case splitProductType "do_unbox" (idType arg) of
344                            (tycon, tycon_args, con, tys) ->
345                                    Case (Var arg) arg [(DataAlt con, con_args,
346                                         body i' (reverse con_args ++ rep_args))]
347                               where 
348                                 (con_args, i') = mkLocals i tys
349 \end{code}
350
351
352 %************************************************************************
353 %*                                                                      *
354 \subsection{Record selectors}
355 %*                                                                      *
356 %************************************************************************
357
358 We're going to build a record selector unfolding that looks like this:
359
360         data T a b c = T1 { ..., op :: a, ...}
361                      | T2 { ..., op :: a, ...}
362                      | T3
363
364         sel = /\ a b c -> \ d -> case d of
365                                     T1 ... x ... -> x
366                                     T2 ... x ... -> x
367                                     other        -> error "..."
368
369 Similarly for newtypes
370
371         newtype N a = MkN { unN :: a->a }
372
373         unN :: N a -> a -> a
374         unN n = coerce (a->a) n
375         
376 We need to take a little care if the field has a polymorphic type:
377
378         data R = R { f :: forall a. a->a }
379
380 Then we want
381
382         f :: forall a. R -> a -> a
383         f = /\ a \ r = case r of
384                           R f -> f a
385
386 (not f :: R -> forall a. a->a, which gives the type inference mechanism 
387 problems at call sites)
388
389 Similarly for (recursive) newtypes
390
391         newtype N = MkN { unN :: forall a. a->a }
392
393         unN :: forall b. N -> b -> b
394         unN = /\b -> \n:N -> (coerce (forall a. a->a) n)
395
396 \begin{code}
397 mkRecordSelId tycon field_label
398         -- Assumes that all fields with the same field label have the same type
399         --
400         -- Annoyingly, we have to pass in the unpackCString# Id, because
401         -- we can't conjure it up out of thin air
402   = sel_id
403   where
404     sel_id     = mkGlobalId (RecordSelId field_label) (fieldLabelName field_label) selector_ty info
405     field_ty   = fieldLabelType field_label
406     data_cons  = tyConDataCons tycon
407     tyvars     = tyConTyVars tycon      -- These scope over the types in 
408                                         -- the FieldLabels of constructors of this type
409     data_ty   = mkTyConApp tycon tyvar_tys
410     tyvar_tys = mkTyVarTys tyvars
411
412         -- Very tiresomely, the selectors are (unnecessarily!) overloaded over
413         -- just the dictionaries in the types of the constructors that contain
414         -- the relevant field.  [The Report says that pattern matching on a
415         -- constructor gives the same constraints as applying it.]  Urgh.  
416         --
417         -- However, not all data cons have all constraints (because of
418         -- TcTyDecls.thinContext).  So we need to find all the data cons 
419         -- involved in the pattern match and take the union of their constraints.
420         --
421         -- NB: this code relies on the fact that DataCons are quantified over
422         -- the identical type variables as their parent TyCon
423     tycon_theta  = tyConTheta tycon     -- The context on the data decl
424                                         --   eg data (Eq a, Ord b) => T a b = ...
425     needed_preds = [pred | (DataAlt dc, _, _) <- the_alts, pred <- dataConTheta dc]
426     dict_tys     = map mkPredTy (nubBy tcEqPred needed_preds)
427     n_dict_tys   = length dict_tys
428
429     (field_tyvars,field_theta,field_tau) = tcSplitSigmaTy field_ty
430     field_dict_tys                       = map mkPredTy field_theta
431     n_field_dict_tys                     = length field_dict_tys
432         -- If the field has a universally quantified type we have to 
433         -- be a bit careful.  Suppose we have
434         --      data R = R { op :: forall a. Foo a => a -> a }
435         -- Then we can't give op the type
436         --      op :: R -> forall a. Foo a => a -> a
437         -- because the typechecker doesn't understand foralls to the
438         -- right of an arrow.  The "right" type to give it is
439         --      op :: forall a. Foo a => R -> a -> a
440         -- But then we must generate the right unfolding too:
441         --      op = /\a -> \dfoo -> \ r ->
442         --           case r of
443         --              R op -> op a dfoo
444         -- Note that this is exactly the type we'd infer from a user defn
445         --      op (R op) = op
446
447     selector_ty :: Type
448     selector_ty  = mkForAllTys tyvars $ mkForAllTys field_tyvars $
449                    mkFunTys dict_tys  $  mkFunTys field_dict_tys $
450                    mkFunTy data_ty field_tau
451       
452     arity = 1 + n_dict_tys + n_field_dict_tys
453
454     (strict_sig, rhs_w_str) = dmdAnalTopRhs sel_rhs
455         -- Use the demand analyser to work out strictness.
456         -- With all this unpackery it's not easy!
457
458     info = noCafIdInfo
459            `setCafInfo`           caf_info
460            `setArityInfo`         arity
461            `setUnfoldingInfo`     mkTopUnfolding rhs_w_str
462            `setAllStrictnessInfo` Just strict_sig
463
464         -- Allocate Ids.  We do it a funny way round because field_dict_tys is
465         -- almost always empty.  Also note that we use length_tycon_theta
466         -- rather than n_dict_tys, because the latter gives an infinite loop:
467         -- n_dict tys depends on the_alts, which depens on arg_ids, which depends
468         -- on arity, which depends on n_dict tys.  Sigh!  Mega sigh!
469     field_dict_base    = length tycon_theta + 1
470     dict_id_base       = field_dict_base + n_field_dict_tys
471     field_base         = dict_id_base + 1
472     dict_ids           = mkTemplateLocalsNum  1               dict_tys
473     field_dict_ids     = mkTemplateLocalsNum  field_dict_base field_dict_tys
474     data_id            = mkTemplateLocal      dict_id_base    data_ty
475
476     alts      = map mk_maybe_alt data_cons
477     the_alts  = catMaybes alts
478
479     no_default = all isJust alts        -- No default needed
480     default_alt | no_default = []
481                 | otherwise  = [(DEFAULT, [], error_expr)]
482
483         -- The default branch may have CAF refs, because it calls recSelError etc.
484     caf_info    | no_default = NoCafRefs
485                 | otherwise  = MayHaveCafRefs
486
487     sel_rhs = mkLams tyvars   $ mkLams field_tyvars $ 
488               mkLams dict_ids $ mkLams field_dict_ids $
489               Lam data_id     $ sel_body
490
491     sel_body | isNewTyCon tycon = mk_result (mkNewTypeBody tycon field_ty (Var data_id))
492              | otherwise        = Case (Var data_id) data_id (default_alt ++ the_alts)
493
494     mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
495         -- We pull the field lambdas to the top, so we need to 
496         -- apply them in the body.  For example:
497         --      data T = MkT { foo :: forall a. a->a }
498         --
499         --      foo :: forall a. T -> a -> a
500         --      foo = /\a. \t:T. case t of { MkT f -> f a }
501
502     mk_maybe_alt data_con 
503         = case maybe_the_arg_id of
504                 Nothing         -> Nothing
505                 Just the_arg_id -> Just (mkReboxingAlt uniqs data_con arg_ids body)
506                                 where
507                                    body = mk_result (Var the_arg_id)
508         where
509             arg_ids = mkTemplateLocalsNum field_base (dataConOrigArgTys data_con)
510                         -- No need to instantiate; same tyvars in datacon as tycon
511
512             unpack_base = field_base + length arg_ids
513             uniqs = map mkBuiltinUnique [unpack_base..]
514
515                                 -- arity+1 avoids all shadowing
516             maybe_the_arg_id  = assocMaybe (field_lbls `zip` arg_ids) field_label
517             field_lbls        = dataConFieldLabels data_con
518
519     error_expr = mkRuntimeErrorApp rEC_SEL_ERROR_ID field_tau full_msg
520     full_msg   = showSDoc (sep [text "No match in record selector", ppr sel_id]) 
521
522
523 -- (mkReboxingAlt us con xs rhs) basically constructs the case
524 -- alternative  (con, xs, rhs)
525 -- but it does the reboxing necessary to construct the *source* 
526 -- arguments, xs, from the representation arguments ys.
527 -- For example:
528 --      data T = MkT !(Int,Int) Bool
529 --
530 -- mkReboxingAlt MkT [x,b] r 
531 --      = (DataAlt MkT, [y::Int,z::Int,b], let x = (y,z) in r)
532 --
533 -- mkDataAlt should really be in DataCon, but it can't because
534 -- it manipulates CoreSyn.
535
536 mkReboxingAlt
537   :: [Unique]                   -- Uniques for the new Ids
538   -> DataCon
539   -> [Var]                      -- Source-level args
540   -> CoreExpr                   -- RHS
541   -> CoreAlt
542
543 mkReboxingAlt us con args rhs
544   | not (any isMarkedUnboxed stricts)
545   = (DataAlt con, args, rhs)
546
547   | otherwise
548   = let
549         (binds, args') = go args stricts us
550     in
551     (DataAlt con, args', mkLets binds rhs)
552
553   where
554     stricts = dataConStrictMarks con
555
556     go [] stricts us = ([], [])
557
558         -- Type variable case
559     go (arg:args) stricts us 
560       | isTyVar arg
561       = let (binds, args') = go args stricts us
562         in  (binds, arg:args')
563
564         -- Term variable case
565     go (arg:args) (str:stricts) us
566       | isMarkedUnboxed str
567       = let
568           (_, tycon_args, pack_con, con_arg_tys)
569                  = splitProductType "mkReboxingAlt" (idType arg)
570
571           unpacked_args  = zipWith (mkSysLocal FSLIT("rb")) us con_arg_tys
572           (binds, args') = go args stricts (dropList con_arg_tys us)
573           con_app        = mkConApp pack_con (map Type tycon_args ++ map Var unpacked_args)
574         in
575         (NonRec arg con_app : binds, unpacked_args ++ args')
576
577       | otherwise
578       = let (binds, args') = go args stricts us
579         in  (binds, arg:args')
580 \end{code}
581
582
583 %************************************************************************
584 %*                                                                      *
585 \subsection{Dictionary selectors}
586 %*                                                                      *
587 %************************************************************************
588
589 Selecting a field for a dictionary.  If there is just one field, then
590 there's nothing to do.  
591
592 Dictionary selectors may get nested forall-types.  Thus:
593
594         class Foo a where
595           op :: forall b. Ord b => a -> b -> b
596
597 Then the top-level type for op is
598
599         op :: forall a. Foo a => 
600               forall b. Ord b => 
601               a -> b -> b
602
603 This is unlike ordinary record selectors, which have all the for-alls
604 at the outside.  When dealing with classes it's very convenient to
605 recover the original type signature from the class op selector.
606
607 ToDo: unify with mkRecordSelId?
608
609 \begin{code}
610 mkDictSelId :: Name -> Class -> Id
611 mkDictSelId name clas
612   = mkGlobalId (RecordSelId field_lbl) name sel_ty info
613   where
614     sel_ty = mkForAllTys tyvars (mkFunTy (idType dict_id) (idType the_arg_id))
615         -- We can't just say (exprType rhs), because that would give a type
616         --      C a -> C a
617         -- for a single-op class (after all, the selector is the identity)
618         -- But it's type must expose the representation of the dictionary
619         -- to gat (say)         C a -> (a -> a)
620
621     field_lbl = mkFieldLabel name tycon sel_ty tag
622     tag       = assoc "MkId.mkDictSelId" (map idName (classSelIds clas) `zip` allFieldLabelTags) name
623
624     info      = noCafIdInfo
625                 `setArityInfo`          1
626                 `setUnfoldingInfo`      mkTopUnfolding rhs
627                 `setAllStrictnessInfo`  Just strict_sig
628
629         -- We no longer use 'must-inline' on record selectors.  They'll
630         -- inline like crazy if they scrutinise a constructor
631
632         -- The strictness signature is of the form U(AAAVAAAA) -> T
633         -- where the V depends on which item we are selecting
634         -- It's worth giving one, so that absence info etc is generated
635         -- even if the selector isn't inlined
636     strict_sig = mkStrictSig (mkTopDmdType [arg_dmd] TopRes)
637     arg_dmd | isNewTyCon tycon = evalDmd
638             | otherwise        = Eval (Prod [ if the_arg_id == id then evalDmd else Abs
639                                             | id <- arg_ids ])
640
641     tyvars  = classTyVars clas
642
643     tycon      = classTyCon clas
644     [data_con] = tyConDataCons tycon
645     tyvar_tys  = mkTyVarTys tyvars
646     arg_tys    = dataConArgTys data_con tyvar_tys
647     the_arg_id = arg_ids !! (tag - firstFieldLabelTag)
648
649     pred              = mkClassPred clas tyvar_tys
650     (dict_id:arg_ids) = mkTemplateLocals (mkPredTy pred : arg_tys)
651
652     rhs | isNewTyCon tycon = mkLams tyvars $ Lam dict_id $ 
653                              mkNewTypeBody tycon (head arg_tys) (Var dict_id)
654         | otherwise        = mkLams tyvars $ Lam dict_id $
655                              Case (Var dict_id) dict_id
656                                   [(DataAlt data_con, arg_ids, Var the_arg_id)]
657
658 mkNewTypeBody tycon result_ty result_expr
659         -- Adds a coerce where necessary
660         -- Used for both wrapping and unwrapping
661   | isRecursiveTyCon tycon      -- Recursive case; use a coerce
662   = Note (Coerce result_ty (exprType result_expr)) result_expr
663   | otherwise                   -- Normal case
664   = result_expr
665 \end{code}
666
667
668 %************************************************************************
669 %*                                                                      *
670 \subsection{Primitive operations
671 %*                                                                      *
672 %************************************************************************
673
674 \begin{code}
675 mkPrimOpId :: PrimOp -> Id
676 mkPrimOpId prim_op 
677   = id
678   where
679     (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
680     ty   = mkForAllTys tyvars (mkFunTys arg_tys res_ty)
681     name = mkPrimOpIdName prim_op
682     id   = mkGlobalId (PrimOpId prim_op) name ty info
683                 
684     info = noCafIdInfo
685            `setSpecInfo`        rules
686            `setArityInfo`       arity
687            `setAllStrictnessInfo` Just strict_sig
688
689     rules = foldl (addRule id) emptyCoreRules (primOpRules prim_op)
690
691
692 -- For each ccall we manufacture a separate CCallOpId, giving it
693 -- a fresh unique, a type that is correct for this particular ccall,
694 -- and a CCall structure that gives the correct details about calling
695 -- convention etc.  
696 --
697 -- The *name* of this Id is a local name whose OccName gives the full
698 -- details of the ccall, type and all.  This means that the interface 
699 -- file reader can reconstruct a suitable Id
700
701 mkFCallId :: Unique -> ForeignCall -> Type -> Id
702 mkFCallId uniq fcall ty
703   = ASSERT( isEmptyVarSet (tyVarsOfType ty) )
704         -- A CCallOpId should have no free type variables; 
705         -- when doing substitutions won't substitute over it
706     mkGlobalId (FCallId fcall) name ty info
707   where
708     occ_str = showSDoc (braces (ppr fcall <+> ppr ty))
709         -- The "occurrence name" of a ccall is the full info about the
710         -- ccall; it is encoded, but may have embedded spaces etc!
711
712     name = mkFCallName uniq occ_str
713
714     info = noCafIdInfo
715            `setArityInfo`               arity
716            `setAllStrictnessInfo`       Just strict_sig
717
718     (_, tau)     = tcSplitForAllTys ty
719     (arg_tys, _) = tcSplitFunTys tau
720     arity        = length arg_tys
721     strict_sig   = mkStrictSig (mkTopDmdType (replicate arity evalDmd) TopRes)
722 \end{code}
723
724
725 %************************************************************************
726 %*                                                                      *
727 \subsection{DictFuns and default methods}
728 %*                                                                      *
729 %************************************************************************
730
731 Important notes about dict funs and default methods
732 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
733 Dict funs and default methods are *not* ImplicitIds.  Their definition
734 involves user-written code, so we can't figure out their strictness etc
735 based on fixed info, as we can for constructors and record selectors (say).
736
737 We build them as GlobalIds, but when in the module where they are
738 bound, we turn the Id at the *binding site* into an exported LocalId.
739 This ensures that they are taken to account by free-variable finding
740 and dependency analysis (e.g. CoreFVs.exprFreeVars).   The simplifier
741 will propagate the LocalId to all occurrence sites. 
742
743 Why shouldn't they be bound as GlobalIds?  Because, in particular, if
744 they are globals, the specialiser floats dict uses above their defns,
745 which prevents good simplifications happening.  Also the strictness
746 analyser treats a occurrence of a GlobalId as imported and assumes it
747 contains strictness in its IdInfo, which isn't true if the thing is
748 bound in the same module as the occurrence.
749
750 It's OK for dfuns to be LocalIds, because we form the instance-env to
751 pass on to the next module (md_insts) in CoreTidy, afer tidying
752 and globalising the top-level Ids.
753
754 BUT make sure they are *exported* LocalIds (setIdLocalExported) so 
755 that they aren't discarded by the occurrence analyser.
756
757 \begin{code}
758 mkDefaultMethodId dm_name ty 
759   = setIdLocalExported (mkLocalId dm_name ty)
760
761 mkDictFunId :: Name             -- Name to use for the dict fun;
762             -> [TyVar]
763             -> ThetaType
764             -> Class 
765             -> [Type]
766             -> Id
767
768 mkDictFunId dfun_name inst_tyvars dfun_theta clas inst_tys
769   = setIdLocalExported (mkLocalId dfun_name dfun_ty)
770   where
771     dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_tys)
772
773 {-  1 dec 99: disable the Mark Jones optimisation for the sake
774     of compatibility with Hugs.
775     See `types/InstEnv' for a discussion related to this.
776
777     (class_tyvars, sc_theta, _, _) = classBigSig clas
778     not_const (clas, tys) = not (isEmptyVarSet (tyVarsOfTypes tys))
779     sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys) sc_theta
780     dfun_theta = case inst_decl_theta of
781                    []    -> []  -- If inst_decl_theta is empty, then we don't
782                                 -- want to have any dict arguments, so that we can
783                                 -- expose the constant methods.
784
785                    other -> nub (inst_decl_theta ++ filter not_const sc_theta')
786                                 -- Otherwise we pass the superclass dictionaries to
787                                 -- the dictionary function; the Mark Jones optimisation.
788                                 --
789                                 -- NOTE the "nub".  I got caught by this one:
790                                 --   class Monad m => MonadT t m where ...
791                                 --   instance Monad m => MonadT (EnvT env) m where ...
792                                 -- Here, the inst_decl_theta has (Monad m); but so
793                                 -- does the sc_theta'!
794                                 --
795                                 -- NOTE the "not_const".  I got caught by this one too:
796                                 --   class Foo a => Baz a b where ...
797                                 --   instance Wob b => Baz T b where..
798                                 -- Now sc_theta' has Foo T
799 -}
800 \end{code}
801
802
803 %************************************************************************
804 %*                                                                      *
805 \subsection{Un-definable}
806 %*                                                                      *
807 %************************************************************************
808
809 These Ids can't be defined in Haskell.  They could be defined in
810 unfoldings in the wired-in GHC.Prim interface file, but we'd have to
811 ensure that they were definitely, definitely inlined, because there is
812 no curried identifier for them.  That's what mkCompulsoryUnfolding
813 does.  If we had a way to get a compulsory unfolding from an interface
814 file, we could do that, but we don't right now.
815
816 unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
817 just gets expanded into a type coercion wherever it occurs.  Hence we
818 add it as a built-in Id with an unfolding here.
819
820 The type variables we use here are "open" type variables: this means
821 they can unify with both unlifted and lifted types.  Hence we provide
822 another gun with which to shoot yourself in the foot.
823
824 \begin{code}
825 -- unsafeCoerce# :: forall a b. a -> b
826 unsafeCoerceId
827   = pcMiscPrelId unsafeCoerceName ty info
828   where
829     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
830            
831
832     ty  = mkForAllTys [openAlphaTyVar,openBetaTyVar]
833                       (mkFunTy openAlphaTy openBetaTy)
834     [x] = mkTemplateLocals [openAlphaTy]
835     rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $
836           Note (Coerce openBetaTy openAlphaTy) (Var x)
837
838 -- nullAddr# :: Addr#
839 -- The reason is is here is because we don't provide 
840 -- a way to write this literal in Haskell.
841 nullAddrId 
842   = pcMiscPrelId nullAddrName addrPrimTy info
843   where
844     info = noCafIdInfo `setUnfoldingInfo` 
845            mkCompulsoryUnfolding (Lit nullAddrLit)
846
847 seqId
848   = pcMiscPrelId seqName ty info
849   where
850     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
851            
852
853     ty  = mkForAllTys [alphaTyVar,betaTyVar]
854                       (mkFunTy alphaTy (mkFunTy betaTy betaTy))
855     [x,y] = mkTemplateLocals [alphaTy, betaTy]
856     rhs = mkLams [alphaTyVar,betaTyVar,x,y] (Case (Var x) x [(DEFAULT, [], Var y)])
857
858 -- lazy :: forall a?. a? -> a?   (i.e. works for unboxed types too)
859 -- Used to lazify pseq:         pseq a b = a `seq` lazy b
860 -- No unfolding: it gets "inlined" by the worker/wrapper pass
861 -- Also, no strictness: by being a built-in Id, it overrides all
862 -- the info in PrelBase.hi.  This is important, because the strictness
863 -- analyser will spot it as strict!
864 lazyId
865   = pcMiscPrelId lazyIdName ty info
866   where
867     info = noCafIdInfo
868     ty  = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
869
870 lazyIdUnfolding :: CoreExpr     -- Used to expand LazyOp after strictness anal
871 lazyIdUnfolding = mkLams [openAlphaTyVar,x] (Var x)
872                 where
873                   [x] = mkTemplateLocals [openAlphaTy]
874 \end{code}
875
876 @getTag#@ is another function which can't be defined in Haskell.  It needs to
877 evaluate its argument and call the dataToTag# primitive.
878
879 \begin{code}
880 getTagId
881   = pcMiscPrelId getTagName ty info
882   where
883     info = noCafIdInfo `setUnfoldingInfo` mkCompulsoryUnfolding rhs
884         -- We don't provide a defn for this; you must inline it
885
886     ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy intPrimTy)
887     [x,y] = mkTemplateLocals [alphaTy,alphaTy]
888     rhs = mkLams [alphaTyVar,x] $
889           Case (Var x) y [ (DEFAULT, [], mkApps (Var dataToTagId) [Type alphaTy, Var y]) ]
890
891 dataToTagId = mkPrimOpId DataToTagOp
892 \end{code}
893
894 @realWorld#@ used to be a magic literal, \tr{void#}.  If things get
895 nasty as-is, change it back to a literal (@Literal@).
896
897 voidArgId is a Local Id used simply as an argument in functions
898 where we just want an arg to avoid having a thunk of unlifted type.
899 E.g.
900         x = \ void :: State# RealWorld -> (# p, q #)
901
902 This comes up in strictness analysis
903
904 \begin{code}
905 realWorldPrimId -- :: State# RealWorld
906   = pcMiscPrelId realWorldName realWorldStatePrimTy
907                  (noCafIdInfo `setUnfoldingInfo` mkOtherCon [])
908         -- The mkOtherCon makes it look that realWorld# is evaluated
909         -- which in turn makes Simplify.interestingArg return True,
910         -- which in turn makes INLINE things applied to realWorld# likely
911         -- to be inlined
912
913 voidArgId       -- :: State# RealWorld
914   = mkSysLocal FSLIT("void") voidArgIdKey realWorldStatePrimTy
915 \end{code}
916
917
918 %************************************************************************
919 %*                                                                      *
920 \subsection[PrelVals-error-related]{@error@ and friends; @trace@}
921 %*                                                                      *
922 %************************************************************************
923
924 GHC randomly injects these into the code.
925
926 @patError@ is just a version of @error@ for pattern-matching
927 failures.  It knows various ``codes'' which expand to longer
928 strings---this saves space!
929
930 @absentErr@ is a thing we put in for ``absent'' arguments.  They jolly
931 well shouldn't be yanked on, but if one is, then you will get a
932 friendly message from @absentErr@ (rather than a totally random
933 crash).
934
935 @parError@ is a special version of @error@ which the compiler does
936 not know to be a bottoming Id.  It is used in the @_par_@ and @_seq_@
937 templates, but we don't ever expect to generate code for it.
938
939 \begin{code}
940 mkRuntimeErrorApp 
941         :: Id           -- Should be of type (forall a. Addr# -> a)
942                         --      where Addr# points to a UTF8 encoded string
943         -> Type         -- The type to instantiate 'a'
944         -> String       -- The string to print
945         -> CoreExpr
946
947 mkRuntimeErrorApp err_id res_ty err_msg 
948   = mkApps (Var err_id) [Type res_ty, err_string]
949   where
950     err_string = Lit (MachStr (mkFastString (stringToUtf8 err_msg)))
951
952 rEC_SEL_ERROR_ID                = mkRuntimeErrorId recSelErrorName
953 rUNTIME_ERROR_ID                = mkRuntimeErrorId runtimeErrorName
954 iRREFUT_PAT_ERROR_ID            = mkRuntimeErrorId irrefutPatErrorName
955 rEC_CON_ERROR_ID                = mkRuntimeErrorId recConErrorName
956 nON_EXHAUSTIVE_GUARDS_ERROR_ID  = mkRuntimeErrorId nonExhaustiveGuardsErrorName
957 pAT_ERROR_ID                    = mkRuntimeErrorId patErrorName
958 nO_METHOD_BINDING_ERROR_ID      = mkRuntimeErrorId noMethodBindingErrorName
959
960 -- The runtime error Ids take a UTF8-encoded string as argument
961 mkRuntimeErrorId name = pc_bottoming_Id name runtimeErrorTy
962 runtimeErrorTy        = mkSigmaTy [openAlphaTyVar] [] (mkFunTy addrPrimTy openAlphaTy)
963 \end{code}
964
965 \begin{code}
966 eRROR_ID = pc_bottoming_Id errorName errorTy
967
968 errorTy  :: Type
969 errorTy  = mkSigmaTy [openAlphaTyVar] [] (mkFunTys [mkListTy charTy] openAlphaTy)
970     -- Notice the openAlphaTyVar.  It says that "error" can be applied
971     -- to unboxed as well as boxed types.  This is OK because it never
972     -- returns, so the return type is irrelevant.
973 \end{code}
974
975
976 %************************************************************************
977 %*                                                                      *
978 \subsection{Utilities}
979 %*                                                                      *
980 %************************************************************************
981
982 \begin{code}
983 pcMiscPrelId :: Name -> Type -> IdInfo -> Id
984 pcMiscPrelId name ty info
985   = mkVanillaGlobal name ty info
986     -- We lie and say the thing is imported; otherwise, we get into
987     -- a mess with dependency analysis; e.g., core2stg may heave in
988     -- random calls to GHCbase.unpackPS__.  If GHCbase is the module
989     -- being compiled, then it's just a matter of luck if the definition
990     -- will be in "the right place" to be in scope.
991
992 pc_bottoming_Id name ty
993  = pcMiscPrelId name ty bottoming_info
994  where
995     bottoming_info = hasCafIdInfo `setAllStrictnessInfo` Just strict_sig
996         -- Do *not* mark them as NoCafRefs, because they can indeed have
997         -- CAF refs.  For example, pAT_ERROR_ID calls GHC.Err.untangle,
998         -- which has some CAFs
999         -- In due course we may arrange that these error-y things are
1000         -- regarded by the GC as permanently live, in which case we
1001         -- can give them NoCaf info.  As it is, any function that calls
1002         -- any pc_bottoming_Id will itself have CafRefs, which bloats
1003         -- SRTs.
1004
1005     strict_sig     = mkStrictSig (mkTopDmdType [evalDmd] BotRes)
1006         -- These "bottom" out, no matter what their arguments
1007
1008 (openAlphaTyVar:openBetaTyVar:_) = openAlphaTyVars
1009 openAlphaTy  = mkTyVarTy openAlphaTyVar
1010 openBetaTy   = mkTyVarTy openBetaTyVar
1011 \end{code}
1012