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