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