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