49e66879a54fe5b3a1f2395e9dfbb3f6103ff2dc
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreSyn.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[CoreSyn]{A data type for the Haskell compiler midsection}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module CoreSyn (
10         GenCoreBinding(..), GenCoreExpr(..),
11         GenCoreArg(..), GenCoreBinder(..), GenCoreCaseAlts(..),
12         GenCoreCaseDefault(..),
13         Coercion(..),
14
15         bindersOf, pairsFromCoreBinds, rhssOfBind,
16
17         mkGenApp, mkValApp, mkTyApp, mkUseApp,
18         mkApp, mkCon, mkPrim,
19         mkValLam, mkTyLam, mkUseLam,
20         mkLam,
21         collectBinders, isValBinder, notValBinder,
22         
23         collectArgs, isValArg, notValArg, numValArgs,
24
25         mkCoLetAny, mkCoLetNoUnboxed, mkCoLetUnboxedToCase,
26         mkCoLetsAny, mkCoLetsNoUnboxed, mkCoLetsUnboxedToCase,
27         mkCoLetrecAny, mkCoLetrecNoUnboxed,
28
29         rhssOfAlts,
30
31         -- Common type instantiation...
32         CoreBinding(..),
33         CoreExpr(..),
34         CoreBinder(..),
35         CoreArg(..),
36         CoreCaseAlts(..),
37         CoreCaseDefault(..),
38
39         -- And not-so-common type instantiations...
40         TaggedCoreBinding(..),
41         TaggedCoreExpr(..),
42         TaggedCoreBinder(..),
43         TaggedCoreArg(..),
44         TaggedCoreCaseAlts(..),
45         TaggedCoreCaseDefault(..),
46
47         SimplifiableCoreBinding(..),
48         SimplifiableCoreExpr(..),
49         SimplifiableCoreBinder(..),
50         SimplifiableCoreArg(..),
51         SimplifiableCoreCaseAlts(..),
52         SimplifiableCoreCaseDefault(..)
53
54         -- and to make the interface self-sufficient ...
55
56     ) where
57
58 import Ubiq{-uitous-}
59
60 -- ToDo:rm:
61 --import PprCore                ( GenCoreExpr{-instance-} )
62 --import PprStyle               ( PprStyle(..) )
63
64 import CostCentre       ( showCostCentre, CostCentre )
65 import Id               ( idType, GenId{-instance Eq-} )
66 import Type             ( isUnboxedType )
67 import Usage            ( UVar(..) )
68 import Util             ( panic, assertPanic {-pprTrace:ToDo:rm-} )
69 \end{code}
70
71 %************************************************************************
72 %*                                                                      *
73 \subsection[CoreTopBinding_and_CoreBinding]{@CoreTopBinding@ and @GenCoreBinding@}
74 %*                                                                      *
75 %************************************************************************
76
77 Core programs, bindings, expressions, etc., are parameterised with
78 respect to the information kept about binding and bound occurrences of
79 variables, called {\em binders} and {\em val_occ tyvar uvars}, respectively.  [I
80 don't really like the pair of names; I prefer {\em binder} and {\em
81 bounder}.  Or {\em binder} and {\em var}.]
82
83 A @GenCoreBinding@ is either a single non-recursive binding of a
84 ``binder'' to an expression, or a mutually-recursive blob of same.
85 \begin{code}
86 data GenCoreBinding val_bdr val_occ tyvar uvar
87   = NonRec      val_bdr (GenCoreExpr val_bdr val_occ tyvar uvar)
88   | Rec         [(val_bdr, GenCoreExpr val_bdr val_occ tyvar uvar)]
89 \end{code}
90
91 \begin{code}
92 bindersOf :: GenCoreBinding val_bdr val_occ tyvar uvar -> [val_bdr]
93
94 pairsFromCoreBinds ::
95   [GenCoreBinding val_bdr val_occ tyvar uvar] ->
96   [(val_bdr, GenCoreExpr val_bdr val_occ tyvar uvar)]
97
98 rhssOfBind :: GenCoreBinding val_bdr val_occ tyvar uvar -> [GenCoreExpr val_bdr val_occ tyvar uvar]
99
100 bindersOf (NonRec binder _) = [binder]
101 bindersOf (Rec pairs)       = [binder | (binder, _) <- pairs]
102
103 pairsFromCoreBinds []                  = []
104 pairsFromCoreBinds ((NonRec b e) : bs) = (b,e) :  pairsFromCoreBinds bs
105 pairsFromCoreBinds ((Rec  pairs) : bs) = pairs ++ pairsFromCoreBinds bs
106
107 rhssOfBind (NonRec _ rhs) = [rhs]
108 rhssOfBind (Rec pairs)    = [rhs | (_,rhs) <- pairs]
109 \end{code}
110
111 %************************************************************************
112 %*                                                                      *
113 \subsection[GenCoreExpr]{Core expressions: @GenCoreExpr@}
114 %*                                                                      *
115 %************************************************************************
116
117 @GenCoreExpr@ is the heart of the ``core'' data types; it is
118 (more-or-less) boiled-down second-order polymorphic lambda calculus.
119 For types in the core world, we just keep using @Types@.
120 \begin{code}
121 data GenCoreExpr val_bdr val_occ tyvar uvar
122      = Var    val_occ
123      | Lit    Literal   -- literal constants
124 \end{code}
125
126 @Cons@ and @Prims@ are saturated constructor and primitive-op
127 applications (see the comment).  Note: @Con@s are only set up by the
128 simplifier (and by the desugarer when it knows what it's doing).  The
129 desugarer sets up constructors as applications of global @Vars@s.
130
131 \begin{code}
132      | Con      Id [GenCoreArg val_occ tyvar uvar]
133                 -- Saturated constructor application:
134                 -- The constructor is a function of the form:
135                 --      /\ a1 -> ... /\ am -> \ b1 -> ... \ bn ->
136                 -- <expr> where "/\" is a type lambda and "\" the
137                 -- regular kind; there will be "m" Types and
138                 -- "n" bindees in the Con args.
139
140      | Prim     PrimOp [GenCoreArg val_occ tyvar uvar]
141                 -- saturated primitive operation;
142                 -- comment on Cons applies here, too.
143 \end{code}
144
145 Ye olde abstraction and application operators.
146 \begin{code}
147      | Lam      (GenCoreBinder val_bdr tyvar uvar)
148                 (GenCoreExpr   val_bdr val_occ tyvar uvar)
149
150      | App      (GenCoreExpr val_bdr val_occ tyvar uvar)
151                 (GenCoreArg  val_occ tyvar uvar)
152 \end{code}
153
154 Case expressions (\tr{case <expr> of <List of alternatives>}): there
155 are really two flavours masquerading here---those for scrutinising
156 {\em algebraic} types and those for {\em primitive} types.  Please see
157 under @GenCoreCaseAlts@.
158 \begin{code}
159      | Case     (GenCoreExpr val_bdr val_occ tyvar uvar)
160                 (GenCoreCaseAlts val_bdr val_occ tyvar uvar)
161 \end{code}
162
163 A Core case expression \tr{case e of v -> ...} implies evaluation of
164 \tr{e}; it is not equivalent to \tr{let v = in ...} (as with a Haskell
165 \tr{case}).
166
167 Non-recursive @Lets@ only have one binding; having more than one
168 doesn't buy you much, and it is an easy way to mess up variable
169 scoping.
170 \begin{code}
171      | Let      (GenCoreBinding val_bdr val_occ tyvar uvar)
172                 (GenCoreExpr val_bdr val_occ tyvar uvar)
173                 -- both recursive and non-.
174                 -- The "GenCoreBinding" records that information
175 \end{code}
176
177 For cost centre scc expressions we introduce a new core construct
178 @SCC@ so transforming passes have to deal with it explicitly. The
179 alternative of using a new PrimativeOp may result in a bad
180 transformations of which we are unaware.
181 \begin{code}
182      | SCC      CostCentre                                  -- label of scc
183                 (GenCoreExpr val_bdr val_occ tyvar uvar)    -- scc expression
184 \end{code}
185
186 Coercions arise from uses of the constructor of a @newtype@
187 declaration, either in construction (resulting in a @CoreceIn@) or
188 pattern matching (resulting in a @CoerceOut@).
189
190 \begin{code}
191     | Coerce    Coercion
192                 (GenType tyvar uvar)            -- Type of the whole expression
193                 (GenCoreExpr val_bdr val_occ tyvar uvar)
194 \end{code}
195
196 \begin{code}
197 data Coercion   = CoerceIn Id           -- Apply this constructor
198                 | CoerceOut Id          -- Strip this constructor
199 \end{code}
200
201
202 %************************************************************************
203 %*                                                                      *
204 \subsection{Core-constructing functions with checking}
205 %*                                                                      *
206 %************************************************************************
207
208 When making @Lets@, we may want to take evasive action if the thing
209 being bound has unboxed type. We have different variants ...
210
211 @mkCoLet(s|rec)Any@             let-binds any binding, regardless of type
212 @mkCoLet(s|rec)NoUnboxed@       prohibits unboxed bindings
213 @mkCoLet(s)UnboxedToCase@       converts an unboxed binding to a case
214                                 (unboxed bindings in a letrec are still prohibited)
215
216 \begin{code}
217 mkCoLetAny :: GenCoreBinding Id Id tyvar uvar
218            -> GenCoreExpr    Id Id tyvar uvar
219            -> GenCoreExpr    Id Id tyvar uvar
220 mkCoLetsAny :: [GenCoreBinding Id Id tyvar uvar] ->
221                 GenCoreExpr Id Id tyvar uvar ->
222                 GenCoreExpr Id Id tyvar uvar
223
224 mkCoLetrecAny :: [(val_bdr, GenCoreExpr val_bdr val_occ tyvar uvar)]
225               -> GenCoreExpr val_bdr val_occ tyvar uvar
226               -> GenCoreExpr val_bdr val_occ tyvar uvar
227
228 mkCoLetrecAny []    body = body
229 mkCoLetrecAny binds body = Let (Rec binds) body
230
231 mkCoLetsAny []    expr = expr
232 mkCoLetsAny binds expr = foldr mkCoLetAny expr binds
233
234 mkCoLetAny bind@(Rec binds) body = mkCoLetrecAny binds body
235 mkCoLetAny bind@(NonRec binder rhs) body
236   = case body of
237       Var binder2 | binder == binder2
238          -> rhs   -- hey, I have the rhs
239       other
240          -> Let bind body
241 \end{code}
242
243 \begin{code}
244 --mkCoLetNoUnboxed ::
245 --  GenCoreBinding val_bdr val_occ tyvar uvar ->
246 --  GenCoreExpr val_bdr val_occ tyvar uvar ->
247 --  GenCoreExpr val_bdr val_occ tyvar uvar
248
249 mkCoLetNoUnboxed bind@(Rec binds) body
250   = mkCoLetrecNoUnboxed binds body
251 mkCoLetNoUnboxed bind@(NonRec binder rhs) body
252   = --ASSERT (not (isUnboxedType (idType binder)))
253     case body of
254       Var binder2 | binder == binder2
255          -> rhs   -- hey, I have the rhs
256       other
257          -> Let bind body
258
259 mkCoLetsNoUnboxed []    expr = expr
260 mkCoLetsNoUnboxed binds expr = foldr mkCoLetNoUnboxed expr binds
261
262 mkCoLetrecNoUnboxed :: [(GenId (GenType a b), GenCoreExpr (GenId (GenType a b)) c d e)]
263                     -> GenCoreExpr (GenId (GenType a b)) c d e
264                     -> GenCoreExpr (GenId (GenType a b)) c d e
265
266 mkCoLetrecNoUnboxed []    body = body
267 mkCoLetrecNoUnboxed binds body
268   = ASSERT (all is_boxed_bind binds)
269     Let (Rec binds) body
270   where
271     is_boxed_bind (binder, rhs)
272       = (not . isUnboxedType . idType) binder
273 \end{code}
274
275 \begin{code}
276 --mkCoLetUnboxedToCase ::
277 --  GenCoreBinding val_bdr val_occ tyvar uvar ->
278 --  GenCoreExpr val_bdr val_occ tyvar uvar ->
279 --  GenCoreExpr val_bdr val_occ tyvar uvar
280
281 mkCoLetUnboxedToCase bind@(Rec binds) body
282   = mkCoLetrecNoUnboxed binds body
283 mkCoLetUnboxedToCase bind@(NonRec binder rhs) body
284   = case body of
285       Var binder2 | binder == binder2
286          -> rhs   -- hey, I have the rhs
287       other
288          -> if (not (isUnboxedType (idType binder))) then
289                 Let bind body            -- boxed...
290             else
291                 Case rhs                  -- unboxed...
292                   (PrimAlts []
293                     (BindDefault binder body))
294
295 mkCoLetsUnboxedToCase []    expr = expr
296 mkCoLetsUnboxedToCase binds expr = foldr mkCoLetUnboxedToCase expr binds
297 \end{code}
298
299 %************************************************************************
300 %*                                                                      *
301 \subsection{Case alternatives in @GenCoreExpr@}
302 %*                                                                      *
303 %************************************************************************
304
305 We have different kinds of @case@s, the differences being reflected in
306 the kinds of alternatives a case has.  We maintain a distinction
307 between cases for scrutinising algebraic datatypes, as opposed to
308 primitive types.  In both cases, we carry around a @TyCon@, as a
309 handle with which we can get info about the case (e.g., total number
310 of data constructors for this type).
311
312 For example:
313 \begin{verbatim}
314 let# x=e in b
315 \end{verbatim}
316 becomes
317 \begin{verbatim}
318 Case e [ BindDefaultAlt x -> b ]
319 \end{verbatim}
320
321 \begin{code}
322 data GenCoreCaseAlts val_bdr val_occ tyvar uvar
323   = AlgAlts     [(Id,                           -- alts: data constructor,
324                   [val_bdr],                    -- constructor's parameters,
325                   GenCoreExpr val_bdr val_occ tyvar uvar)]      -- rhs.
326                 (GenCoreCaseDefault val_bdr val_occ tyvar uvar)
327
328   | PrimAlts    [(Literal,                      -- alts: unboxed literal,
329                   GenCoreExpr val_bdr val_occ tyvar uvar)]      -- rhs.
330                 (GenCoreCaseDefault val_bdr val_occ tyvar uvar)
331
332 -- obvious things: if there are no alts in the list, then the default
333 -- can't be NoDefault.
334
335 data GenCoreCaseDefault val_bdr val_occ tyvar uvar
336   = NoDefault                                   -- small con family: all
337                                                 -- constructor accounted for
338   | BindDefault val_bdr                         -- form: var -> expr;
339                 (GenCoreExpr val_bdr val_occ tyvar uvar)        -- "val_bdr" may or may not
340                                                 -- be used in RHS.
341 \end{code}
342
343 \begin{code}
344 rhssOfAlts (AlgAlts alts deflt)  = rhssOfDeflt deflt ++ [rhs | (_,_,rhs) <- alts]
345 rhssOfAlts (PrimAlts alts deflt) = rhssOfDeflt deflt ++ [rhs | (_,rhs)   <- alts]
346
347 rhssOfDeflt NoDefault           = []
348 rhssOfDeflt (BindDefault _ rhs) = [rhs]
349 \end{code}
350
351 %************************************************************************
352 %*                                                                      *
353 \subsection{Core binders}
354 %*                                                                      *
355 %************************************************************************
356
357 \begin{code}
358 data GenCoreBinder val_bdr tyvar uvar
359   = ValBinder   val_bdr
360   | TyBinder    tyvar
361   | UsageBinder uvar
362
363 isValBinder (ValBinder _) = True
364 isValBinder _             = False
365
366 notValBinder = not . isValBinder
367 \end{code}
368
369 Clump Lams together if possible.
370
371 \begin{code}
372 mkValLam :: [val_bdr]
373          -> GenCoreExpr val_bdr val_occ tyvar uvar
374          -> GenCoreExpr val_bdr val_occ tyvar uvar
375 mkTyLam  :: [tyvar]
376          -> GenCoreExpr val_bdr val_occ tyvar uvar
377          -> GenCoreExpr val_bdr val_occ tyvar uvar
378 mkUseLam :: [uvar]
379          -> GenCoreExpr val_bdr val_occ tyvar uvar
380          -> GenCoreExpr val_bdr val_occ tyvar uvar
381
382 mkValLam binders body = foldr (Lam . ValBinder)   body binders
383 mkTyLam  binders body = foldr (Lam . TyBinder)    body binders
384 mkUseLam binders body = foldr (Lam . UsageBinder) body binders
385
386 mkLam :: [tyvar] -> [val_bdr] -- ToDo: could add a [uvar] arg...
387          -> GenCoreExpr val_bdr val_occ tyvar uvar
388          -> GenCoreExpr val_bdr val_occ tyvar uvar
389
390 mkLam tyvars valvars body
391   = mkTyLam tyvars (mkValLam valvars body)
392 \end{code}
393
394 We often want to strip off leading lambdas before getting down to
395 business.  @collectBinders@ is your friend.
396
397 We expect (by convention) usage-, type-, and value- lambdas in that
398 order.
399
400 \begin{code}
401 collectBinders ::
402   GenCoreExpr val_bdr val_occ tyvar uvar ->
403   ([uvar], [tyvar], [val_bdr], GenCoreExpr val_bdr val_occ tyvar uvar)
404
405 collectBinders expr
406   = usages expr []
407   where
408     usages (Lam (UsageBinder u) body) uacc = usages body (u:uacc)
409     usages other uacc
410       = case (tyvars other []) of { (tacc, vacc, expr) ->
411         (reverse uacc, tacc, vacc, expr) }
412
413     tyvars (Lam (TyBinder t)    body) tacc = tyvars body (t:tacc)
414     tyvars other tacc
415       = ASSERT(not (usage_lambda other))
416         case (valvars other []) of { (vacc, expr) ->
417         (reverse tacc, vacc, expr) }
418
419     valvars (Lam (ValBinder v)  body) vacc = valvars body (v:vacc)
420     valvars other vacc
421       = ASSERT(not (usage_lambda other))
422         ASSERT(not (tyvar_lambda other))
423         (reverse vacc, other)
424
425     ---------------------------------------
426     usage_lambda (Lam (UsageBinder _) _) = True
427     usage_lambda _                       = False
428
429     tyvar_lambda (Lam (TyBinder _) _)    = True
430     tyvar_lambda _                       = False
431 \end{code}
432
433 %************************************************************************
434 %*                                                                      *
435 \subsection{Core arguments (atoms)}
436 %*                                                                      *
437 %************************************************************************
438
439 \begin{code}
440 data GenCoreArg val_occ tyvar uvar
441   = LitArg      Literal
442   | VarArg      val_occ
443   | TyArg       (GenType tyvar uvar)
444   | UsageArg    (GenUsage uvar)
445 \end{code}
446
447 General and specific forms:
448 \begin{code}
449 mkGenApp :: GenCoreExpr val_bdr val_occ tyvar uvar
450          -> [GenCoreArg val_occ tyvar uvar]
451          -> GenCoreExpr val_bdr val_occ tyvar uvar
452 mkTyApp  :: GenCoreExpr val_bdr val_occ tyvar uvar
453          -> [GenType tyvar uvar]
454          -> GenCoreExpr val_bdr val_occ tyvar uvar
455 mkUseApp :: GenCoreExpr val_bdr val_occ tyvar uvar
456          -> [GenUsage uvar]
457          -> GenCoreExpr val_bdr val_occ tyvar uvar
458 mkValApp :: GenCoreExpr val_bdr val_occ tyvar uvar
459          -> [GenCoreArg val_occ tyvar uvar] -- but we ASSERT they are LitArg or VarArg
460          -> GenCoreExpr val_bdr val_occ tyvar uvar
461
462 mkGenApp f args = foldl App                                f args
463 mkTyApp  f args = foldl (\ e a -> App e (TyArg a))         f args
464 mkUseApp f args = foldl (\ e a -> App e (UsageArg a))      f args
465 mkValApp f args = foldl (\ e a -> App e (is_Lit_or_Var a)) f args
466
467 #ifndef DEBUG
468 is_Lit_or_Var a = a
469 #else
470 is_Lit_or_Var a
471   = if isValArg a then a else panic "CoreSyn.mkValApps:not LitArg or VarArg"
472 #endif
473
474 isValArg (LitArg _) = True  -- often used for sanity-checking
475 isValArg (VarArg _) = True
476 isValArg _          = False
477
478 notValArg = not . isValArg -- exists only because it's a common use of isValArg
479
480 numValArgs as = length [ a | a <- as, isValArg a ] -- again, convenience
481 \end{code}
482
483 \begin{code}
484 mkApp  fun = mk_thing (mkGenApp fun)
485 mkCon  con = mk_thing (Con      con)
486 mkPrim op  = mk_thing (Prim     op)
487
488 mk_thing thing uses tys vals
489   = thing (map UsageArg uses ++ map TyArg tys ++ map is_Lit_or_Var vals)
490 \end{code}
491
492 @collectArgs@ takes an application expression, returning the function
493 and the arguments to which it is applied.
494
495 \begin{code}
496 collectArgs :: GenCoreExpr val_bdr val_occ tyvar uvar
497             -> (GenCoreExpr val_bdr val_occ tyvar uvar,
498                 [GenUsage uvar],
499                 [GenType tyvar uvar],
500                 [GenCoreArg val_occ tyvar uvar]{-ValArgs-})
501
502 collectArgs expr
503   = valvars expr []
504   where
505     valvars (App fun v) vacc | isValArg v = valvars fun (v:vacc)
506     valvars fun vacc
507       = case (tyvars fun []) of { (expr, uacc, tacc) ->
508         (expr, uacc, tacc, vacc) }
509
510     tyvars (App fun (TyArg t))    tacc = tyvars fun (t:tacc)
511     tyvars fun tacc
512       = case (usages fun []) of { (expr, uacc) ->
513         (expr, uacc, tacc) }
514
515     usages (App fun (UsageArg u)) uacc = usages fun (u:uacc)
516     usages fun uacc
517       = (fun,uacc)
518 \end{code}
519
520 %************************************************************************
521 %*                                                                      *
522 \subsection{The main @Core*@ instantiation of the @GenCore*@ types}
523 %*                                                                      *
524 %************************************************************************
525
526 \begin{code}
527 type CoreBinding = GenCoreBinding  Id Id TyVar UVar
528 type CoreExpr    = GenCoreExpr     Id Id TyVar UVar
529 type CoreBinder  = GenCoreBinder   Id    TyVar UVar
530 type CoreArg     = GenCoreArg         Id TyVar UVar
531
532 type CoreCaseAlts    = GenCoreCaseAlts    Id Id TyVar UVar
533 type CoreCaseDefault = GenCoreCaseDefault Id Id TyVar UVar
534 \end{code}
535
536 %************************************************************************
537 %*                                                                      *
538 \subsection{The @TaggedCore*@ instantiation of the @GenCore*@ types}
539 %*                                                                      *
540 %************************************************************************
541
542 Binders are ``tagged'' with a \tr{t}:
543 \begin{code}
544 type Tagged t = (Id, t)
545
546 type TaggedCoreBinding t = GenCoreBinding (Tagged t) Id TyVar UVar
547 type TaggedCoreExpr    t = GenCoreExpr    (Tagged t) Id TyVar UVar
548 type TaggedCoreBinder  t = GenCoreBinder  (Tagged t)    TyVar UVar
549 type TaggedCoreArg     t = GenCoreArg                Id TyVar UVar
550
551 type TaggedCoreCaseAlts    t = GenCoreCaseAlts    (Tagged t) Id TyVar UVar
552 type TaggedCoreCaseDefault t = GenCoreCaseDefault (Tagged t) Id TyVar UVar
553 \end{code}
554
555 %************************************************************************
556 %*                                                                      *
557 \subsection{The @SimplifiableCore*@ instantiation of the @GenCore*@ types}
558 %*                                                                      *
559 %************************************************************************
560
561 Binders are tagged with @BinderInfo@:
562 \begin{code}
563 type Simplifiable = (Id, BinderInfo)
564
565 type SimplifiableCoreBinding = GenCoreBinding Simplifiable Id TyVar UVar
566 type SimplifiableCoreExpr    = GenCoreExpr    Simplifiable Id TyVar UVar
567 type SimplifiableCoreBinder  = GenCoreBinder  Simplifiable    TyVar UVar
568 type SimplifiableCoreArg     = GenCoreArg                  Id TyVar UVar
569
570 type SimplifiableCoreCaseAlts    = GenCoreCaseAlts    Simplifiable Id TyVar UVar
571 type SimplifiableCoreCaseDefault = GenCoreCaseDefault Simplifiable Id TyVar UVar
572 \end{code}