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