[project @ 2000-10-25 12:56:20 by simonpj]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreSyn.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[CoreSyn]{A data type for the Haskell compiler midsection}
5
6 \begin{code}
7 module CoreSyn (
8         Expr(..), Alt, Bind(..), AltCon(..), Arg, Note(..),
9         CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr,
10         TaggedExpr, TaggedAlt, TaggedBind, TaggedArg,
11
12         mkLets, mkLams, 
13         mkApps, mkTyApps, mkValApps, mkVarApps,
14         mkLit, mkIntLitInt, mkIntLit, 
15         mkConApp, 
16         varToCoreExpr,
17
18         bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts, isTyVar, isId,
19         collectBinders, collectTyBinders, collectValBinders, collectTyAndValBinders,
20         collectArgs, collectBindersIgnoringNotes,
21         coreExprCc,
22         flattenBinds, 
23
24         isValArg, isTypeArg, valArgCount, valBndrCount,
25
26         -- Unfoldings
27         Unfolding(..),  UnfoldingGuidance(..),  -- Both abstract everywhere but in CoreUnfold.lhs
28         noUnfolding, mkOtherCon,
29         unfoldingTemplate, maybeUnfoldingTemplate, otherCons, 
30         isValueUnfolding, isEvaldUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
31         hasUnfolding, hasSomeUnfolding, neverUnfold,
32
33         -- Seq stuff
34         seqRules, seqExpr, seqExprs, seqUnfolding,
35
36         -- Annotated expressions
37         AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt, deAnnotate, deAnnotate',
38
39         -- Core rules
40         CoreRules(..),  -- Representation needed by friends
41         CoreRule(..),   -- CoreSubst, CoreTidy, CoreFVs, PprCore only
42         IdCoreRule,
43         RuleName,
44         emptyCoreRules, isEmptyCoreRules, rulesRhsFreeVars, rulesRules,
45         isBuiltinRule
46     ) where
47
48 #include "HsVersions.h"
49
50 import CostCentre       ( CostCentre, noCostCentre )
51 import Var              ( Var, Id, TyVar, isTyVar, isId )
52 import Type             ( Type, UsageAnn, mkTyVarTy, seqType )
53 import Literal          ( Literal, mkMachInt )
54 import DataCon          ( DataCon, dataConId )
55 import VarSet
56 import Outputable
57 \end{code}
58
59 %************************************************************************
60 %*                                                                      *
61 \subsection{The main data types}
62 %*                                                                      *
63 %************************************************************************
64
65 These data types are the heart of the compiler
66
67 \begin{code}
68 infixl 8 `App`  -- App brackets to the left
69
70 data Expr b     -- "b" for the type of binders, 
71   = Var   Id
72   | Lit   Literal
73   | App   (Expr b) (Arg b)
74   | Lam   b (Expr b)
75   | Let   (Bind b) (Expr b)
76   | Case  (Expr b) b [Alt b]    -- Binder gets bound to value of scrutinee
77                                 -- DEFAULT case must be last, if it occurs at all
78   | Note  Note (Expr b)
79   | Type  Type                  -- This should only show up at the top
80                                 -- level of an Arg
81
82 type Arg b = Expr b             -- Can be a Type
83
84 type Alt b = (AltCon, [b], Expr b)      -- (DEFAULT, [], rhs) is the default alternative
85
86 data AltCon = DataAlt DataCon
87             | LitAlt  Literal
88             | DEFAULT
89          deriving (Eq, Ord)
90
91 data Bind b = NonRec b (Expr b)
92               | Rec [(b, (Expr b))]
93
94 data Note
95   = SCC CostCentre
96
97   | Coerce      
98         Type            -- The to-type:   type of whole coerce expression
99         Type            -- The from-type: type of enclosed expression
100
101   | InlineCall          -- Instructs simplifier to inline
102                         -- the enclosed call
103
104   | InlineMe            -- Instructs simplifer to treat the enclosed expression
105                         -- as very small, and inline it at its call sites
106
107   | TermUsg             -- A term-level usage annotation
108         UsageAnn        -- (should not be a variable except during UsageSP inference)
109 \end{code}
110
111
112 %************************************************************************
113 %*                                                                      *
114 \subsection{Transformation rules}
115 %*                                                                      *
116 %************************************************************************
117
118 The CoreRule type and its friends are dealt with mainly in CoreRules,
119 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
120
121 \begin{code}
122 data CoreRules 
123   = Rules [CoreRule]
124           VarSet                -- Locally-defined free vars of RHSs
125
126 emptyCoreRules :: CoreRules
127 emptyCoreRules = Rules [] emptyVarSet
128
129 isEmptyCoreRules :: CoreRules -> Bool
130 isEmptyCoreRules (Rules rs _) = null rs
131
132 rulesRhsFreeVars :: CoreRules -> VarSet
133 rulesRhsFreeVars (Rules _ fvs) = fvs
134
135 rulesRules :: CoreRules -> [CoreRule]
136 rulesRules (Rules rules _) = rules
137 \end{code}
138
139 \begin{code}
140 type RuleName = FAST_STRING
141 type IdCoreRule = (Id,CoreRule)         -- Rules don't have their leading Id inside them
142
143 data CoreRule
144   = Rule RuleName
145          [CoreBndr]     -- Forall'd variables
146          [CoreExpr]     -- LHS args
147          CoreExpr       -- RHS
148
149   | BuiltinRule         -- Built-in rules are used for constant folding
150                         -- and suchlike.  It has no free variables.
151         ([CoreExpr] -> Maybe (RuleName, CoreExpr))
152
153 isBuiltinRule (BuiltinRule _) = True
154 isBuiltinRule _               = False
155 \end{code}
156
157
158 %************************************************************************
159 %*                                                                      *
160 \subsection{@Unfolding@ type}
161 %*                                                                      *
162 %************************************************************************
163
164 The @Unfolding@ type is declared here to avoid numerous loops, but it
165 should be abstract everywhere except in CoreUnfold.lhs
166
167 \begin{code}
168 data Unfolding
169   = NoUnfolding
170
171   | OtherCon [AltCon]           -- It ain't one of these
172                                 -- (OtherCon xs) also indicates that something has been evaluated
173                                 -- and hence there's no point in re-evaluating it.
174                                 -- OtherCon [] is used even for non-data-type values
175                                 -- to indicated evaluated-ness.  Notably:
176                                 --      data C = C !(Int -> Int)
177                                 --      case x of { C f -> ... }
178                                 -- Here, f gets an OtherCon [] unfolding.
179
180   | CompulsoryUnfolding CoreExpr        -- There is no "original" definition,
181                                         -- so you'd better unfold.
182
183   | CoreUnfolding                       -- An unfolding with redundant cached information
184                 CoreExpr                -- Template; binder-info is correct
185                 Bool                    -- True <=> top level binding
186                 Bool                    -- exprIsValue template (cached); it is ok to discard a `seq` on
187                                         --      this variable
188                 Bool                    -- True <=> doesn't waste (much) work to expand inside an inlining
189                                         --      Basically it's exprIsCheap
190                 UnfoldingGuidance       -- Tells about the *size* of the template.
191
192
193 data UnfoldingGuidance
194   = UnfoldNever
195   | UnfoldIfGoodArgs    Int     -- and "n" value args
196
197                         [Int]   -- Discount if the argument is evaluated.
198                                 -- (i.e., a simplification will definitely
199                                 -- be possible).  One elt of the list per *value* arg.
200
201                         Int     -- The "size" of the unfolding; to be elaborated
202                                 -- later. ToDo
203
204                         Int     -- Scrutinee discount: the discount to substract if the thing is in
205                                 -- a context (case (thing args) of ...),
206                                 -- (where there are the right number of arguments.)
207
208 noUnfolding = NoUnfolding
209 mkOtherCon  = OtherCon
210
211 seqUnfolding :: Unfolding -> ()
212 seqUnfolding (CoreUnfolding e top b1 b2 g)
213   = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
214 seqUnfolding other = ()
215
216 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
217 seqGuidance other                       = ()
218 \end{code}
219
220 \begin{code}
221 unfoldingTemplate :: Unfolding -> CoreExpr
222 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
223 unfoldingTemplate (CompulsoryUnfolding expr)   = expr
224 unfoldingTemplate other = panic "getUnfoldingTemplate"
225
226 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
227 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
228 maybeUnfoldingTemplate (CompulsoryUnfolding expr)   = Just expr
229 maybeUnfoldingTemplate other                        = Nothing
230
231 otherCons :: Unfolding -> [AltCon]
232 otherCons (OtherCon cons) = cons
233 otherCons other           = []
234
235 isValueUnfolding :: Unfolding -> Bool
236         -- Returns False for OtherCon
237 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
238 isValueUnfolding other                            = False
239
240 isEvaldUnfolding :: Unfolding -> Bool
241         -- Returns True for OtherCon
242 isEvaldUnfolding (OtherCon _)                     = True
243 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
244 isEvaldUnfolding other                            = False
245
246 isCheapUnfolding :: Unfolding -> Bool
247 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
248 isCheapUnfolding other                            = False
249
250 isCompulsoryUnfolding :: Unfolding -> Bool
251 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
252 isCompulsoryUnfolding other                   = False
253
254 hasUnfolding :: Unfolding -> Bool
255 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
256 hasUnfolding (CompulsoryUnfolding _)   = True
257 hasUnfolding other                     = False
258
259 hasSomeUnfolding :: Unfolding -> Bool
260 hasSomeUnfolding NoUnfolding = False
261 hasSomeUnfolding other       = True
262
263 neverUnfold :: Unfolding -> Bool
264 neverUnfold NoUnfolding                         = True
265 neverUnfold (OtherCon _)                        = True
266 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
267 neverUnfold other                               = False
268 \end{code}
269
270
271 %************************************************************************
272 %*                                                                      *
273 \subsection{The main data type}
274 %*                                                                      *
275 %************************************************************************
276
277 \begin{code}
278 -- The Ord is needed for the FiniteMap used in the lookForConstructor
279 -- in SimplEnv.  If you declared that lookForConstructor *ignores*
280 -- constructor-applications with LitArg args, then you could get
281 -- rid of this Ord.
282
283 instance Outputable AltCon where
284   ppr (DataAlt dc) = ppr dc
285   ppr (LitAlt lit) = ppr lit
286   ppr DEFAULT      = ptext SLIT("__DEFAULT")
287
288 instance Show AltCon where
289   showsPrec p con = showsPrecSDoc p (ppr con)
290 \end{code}
291
292
293 %************************************************************************
294 %*                                                                      *
295 \subsection{Useful synonyms}
296 %*                                                                      *
297 %************************************************************************
298
299 The common case
300
301 \begin{code}
302 type CoreBndr = Var
303 type CoreExpr = Expr CoreBndr
304 type CoreArg  = Arg  CoreBndr
305 type CoreBind = Bind CoreBndr
306 type CoreAlt  = Alt  CoreBndr
307 \end{code}
308
309 Binders are ``tagged'' with a \tr{t}:
310
311 \begin{code}
312 type Tagged t = (CoreBndr, t)
313
314 type TaggedBind t = Bind (Tagged t)
315 type TaggedExpr t = Expr (Tagged t)
316 type TaggedArg  t = Arg  (Tagged t)
317 type TaggedAlt  t = Alt  (Tagged t)
318 \end{code}
319
320
321 %************************************************************************
322 %*                                                                      *
323 \subsection{Core-constructing functions with checking}
324 %*                                                                      *
325 %************************************************************************
326
327 \begin{code}
328 mkApps    :: Expr b -> [Arg b]  -> Expr b
329 mkTyApps  :: Expr b -> [Type]   -> Expr b
330 mkValApps :: Expr b -> [Expr b] -> Expr b
331 mkVarApps :: Expr b -> [Var] -> Expr b
332
333 mkApps    f args = foldl App                       f args
334 mkTyApps  f args = foldl (\ e a -> App e (Type a)) f args
335 mkValApps f args = foldl (\ e a -> App e a)        f args
336 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
337
338 mkLit         :: Literal -> Expr b
339 mkIntLit      :: Integer -> Expr b
340 mkIntLitInt   :: Int     -> Expr b
341 mkConApp      :: DataCon -> [Arg b] -> Expr b
342 mkLets        :: [Bind b] -> Expr b -> Expr b
343 mkLams        :: [b] -> Expr b -> Expr b
344
345 mkLit lit         = Lit lit
346 mkConApp con args = mkApps (Var (dataConId con)) args
347
348 mkLams binders body = foldr Lam body binders
349 mkLets binds body   = foldr Let body binds
350
351 mkIntLit    n = Lit (mkMachInt n)
352 mkIntLitInt n = Lit (mkMachInt (toInteger n))
353
354 varToCoreExpr :: CoreBndr -> Expr b
355 varToCoreExpr v | isId v    = Var v
356                 | otherwise = Type (mkTyVarTy v)
357 \end{code}
358
359
360 %************************************************************************
361 %*                                                                      *
362 \subsection{Simple access functions}
363 %*                                                                      *
364 %************************************************************************
365
366 \begin{code}
367 bindersOf  :: Bind b -> [b]
368 bindersOf (NonRec binder _) = [binder]
369 bindersOf (Rec pairs)       = [binder | (binder, _) <- pairs]
370
371 bindersOfBinds :: [Bind b] -> [b]
372 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
373
374 rhssOfBind :: Bind b -> [Expr b]
375 rhssOfBind (NonRec _ rhs) = [rhs]
376 rhssOfBind (Rec pairs)    = [rhs | (_,rhs) <- pairs]
377
378 rhssOfAlts :: [Alt b] -> [Expr b]
379 rhssOfAlts alts = [e | (_,_,e) <- alts]
380
381 flattenBinds :: [Bind b] -> [(b, Expr b)]       -- Get all the lhs/rhs pairs
382 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
383 flattenBinds (Rec prs1   : binds) = prs1 ++ flattenBinds binds
384 flattenBinds []                   = []
385 \end{code}
386
387 We often want to strip off leading lambdas before getting down to
388 business.  @collectBinders@ is your friend.
389
390 We expect (by convention) type-, and value- lambdas in that
391 order.
392
393 \begin{code}
394 collectBinders               :: Expr b -> ([b],         Expr b)
395 collectBindersIgnoringNotes  :: Expr b -> ([b],         Expr b)
396 collectTyBinders             :: CoreExpr -> ([TyVar],     CoreExpr)
397 collectValBinders            :: CoreExpr -> ([Id],        CoreExpr)
398 collectTyAndValBinders       :: CoreExpr -> ([TyVar], [Id], CoreExpr)
399
400 collectBinders expr
401   = go [] expr
402   where
403     go bs (Lam b e) = go (b:bs) e
404     go bs e          = (reverse bs, e)
405
406 -- This one ignores notes.  It's used in CoreUnfold and StrAnal
407 -- when we aren't going to put the expression back together from
408 -- the pieces, so we don't mind losing the Notes
409 collectBindersIgnoringNotes expr
410   = go [] expr
411   where
412     go bs (Lam b e)  = go (b:bs) e
413     go bs (Note _ e) = go    bs  e
414     go bs e          = (reverse bs, e)
415
416 collectTyAndValBinders expr
417   = (tvs, ids, body)
418   where
419     (tvs, body1) = collectTyBinders expr
420     (ids, body)  = collectValBinders body1
421
422 collectTyBinders expr
423   = go [] expr
424   where
425     go tvs (Lam b e) | isTyVar b = go (b:tvs) e
426     go tvs e                     = (reverse tvs, e)
427
428 collectValBinders expr
429   = go [] expr
430   where
431     go ids (Lam b e) | isId b = go (b:ids) e
432     go ids body               = (reverse ids, body)
433 \end{code}
434
435
436 @collectArgs@ takes an application expression, returning the function
437 and the arguments to which it is applied.
438
439 \begin{code}
440 collectArgs :: Expr b -> (Expr b, [Arg b])
441 collectArgs expr
442   = go expr []
443   where
444     go (App f a) as = go f (a:as)
445     go e         as = (e, as)
446 \end{code}
447
448 coreExprCc gets the cost centre enclosing an expression, if any.
449 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
450
451 \begin{code}
452 coreExprCc :: Expr b -> CostCentre
453 coreExprCc (Note (SCC cc) e)   = cc
454 coreExprCc (Note other_note e) = coreExprCc e
455 coreExprCc (Lam _ e)           = coreExprCc e
456 coreExprCc other               = noCostCentre
457 \end{code}
458
459
460 %************************************************************************
461 %*                                                                      *
462 \subsection{Predicates}
463 %*                                                                      *
464 %************************************************************************
465
466 \begin{code}
467 isValArg (Type _) = False
468 isValArg other    = True
469
470 isTypeArg (Type _) = True
471 isTypeArg other    = False
472
473 valBndrCount :: [CoreBndr] -> Int
474 valBndrCount []                   = 0
475 valBndrCount (b : bs) | isId b    = 1 + valBndrCount bs
476                       | otherwise = valBndrCount bs
477
478 valArgCount :: [Arg b] -> Int
479 valArgCount []              = 0
480 valArgCount (Type _ : args) = valArgCount args
481 valArgCount (other  : args) = 1 + valArgCount args
482 \end{code}
483
484
485 %************************************************************************
486 %*                                                                      *
487 \subsection{Seq stuff}
488 %*                                                                      *
489 %************************************************************************
490
491 \begin{code}
492 seqExpr :: CoreExpr -> ()
493 seqExpr (Var v)       = v `seq` ()
494 seqExpr (Lit lit)     = lit `seq` ()
495 seqExpr (App f a)     = seqExpr f `seq` seqExpr a
496 seqExpr (Lam b e)     = seqBndr b `seq` seqExpr e
497 seqExpr (Let b e)     = seqBind b `seq` seqExpr e
498 seqExpr (Case e b as) = seqExpr e `seq` seqBndr b `seq` seqAlts as
499 seqExpr (Note n e)    = seqNote n `seq` seqExpr e
500 seqExpr (Type t)      = seqType t
501
502 seqExprs [] = ()
503 seqExprs (e:es) = seqExpr e `seq` seqExprs es
504
505 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
506 seqNote other          = ()
507
508 seqBndr b = b `seq` ()
509
510 seqBndrs [] = ()
511 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
512
513 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
514 seqBind (Rec prs)    = seqPairs prs
515
516 seqPairs [] = ()
517 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
518
519 seqAlts [] = ()
520 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
521
522 seqRules :: CoreRules -> ()
523 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
524
525 seq_rules [] = ()
526 seq_rules (Rule fs bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
527 seq_rules (BuiltinRule _ : rules) = seq_rules rules
528 \end{code}
529
530
531
532 %************************************************************************
533 %*                                                                      *
534 \subsection{Annotated core; annotation at every node in the tree}
535 %*                                                                      *
536 %************************************************************************
537
538 \begin{code}
539 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
540
541 data AnnExpr' bndr annot
542   = AnnVar      Id
543   | AnnLit      Literal
544   | AnnLam      bndr (AnnExpr bndr annot)
545   | AnnApp      (AnnExpr bndr annot) (AnnExpr bndr annot)
546   | AnnCase     (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
547   | AnnLet      (AnnBind bndr annot) (AnnExpr bndr annot)
548   | AnnNote     Note (AnnExpr bndr annot)
549   | AnnType     Type
550
551 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
552
553 data AnnBind bndr annot
554   = AnnNonRec bndr (AnnExpr bndr annot)
555   | AnnRec    [(bndr, AnnExpr bndr annot)]
556 \end{code}
557
558 \begin{code}
559 deAnnotate :: AnnExpr bndr annot -> Expr bndr
560 deAnnotate (_, e) = deAnnotate' e
561
562 deAnnotate' (AnnType t)           = Type t
563 deAnnotate' (AnnVar  v)           = Var v
564 deAnnotate' (AnnLit  lit)         = Lit lit
565 deAnnotate' (AnnLam  binder body) = Lam binder (deAnnotate body)
566 deAnnotate' (AnnApp  fun arg)     = App (deAnnotate fun) (deAnnotate arg)
567 deAnnotate' (AnnNote note body)   = Note note (deAnnotate body)
568
569 deAnnotate' (AnnLet bind body)
570   = Let (deAnnBind bind) (deAnnotate body)
571   where
572     deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
573     deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
574
575 deAnnotate' (AnnCase scrut v alts)
576   = Case (deAnnotate scrut) v (map deAnnAlt alts)
577   where
578     deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
579 \end{code}
580