2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[CoreSyn]{A data type for the Haskell compiler midsection}
8 Expr(..), Alt, Bind(..), AltCon(..), Arg, Note(..),
9 CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr,
10 TaggedExpr, TaggedAlt, TaggedBind, TaggedArg,
13 mkApps, mkTyApps, mkValApps, mkVarApps,
14 mkLit, mkIntLitInt, mkIntLit,
19 bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts,
20 collectBinders, collectTyBinders, collectValBinders, collectTyAndValBinders,
21 collectArgs, collectBindersIgnoringNotes,
25 isValArg, isTypeArg, valArgCount, valBndrCount, isRuntimeArg, isRuntimeVar,
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,
35 seqRules, seqExpr, seqExprs, seqUnfolding,
37 -- Annotated expressions
38 AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt,
39 deAnnotate, deAnnotate', deAnnAlt,
42 CoreRules(..), -- Representation needed by friends
43 CoreRule(..), -- CoreSubst, CoreTidy, CoreFVs, PprCore only
46 emptyCoreRules, isEmptyCoreRules, rulesRhsFreeVars, rulesRules,
50 #include "HsVersions.h"
52 import CmdLineOpts ( opt_RuntimeTypes )
53 import CostCentre ( CostCentre, noCostCentre )
54 import Var ( Var, Id, TyVar, isTyVar, isId )
55 import Type ( Type, mkTyVarTy, seqType )
56 import Literal ( Literal, mkMachInt )
57 import DataCon ( DataCon, dataConId )
62 %************************************************************************
64 \subsection{The main data types}
66 %************************************************************************
68 These data types are the heart of the compiler
71 infixl 8 `App` -- App brackets to the left
73 data Expr b -- "b" for the type of binders,
76 | App (Expr b) (Arg b)
78 | Let (Bind b) (Expr b)
79 | Case (Expr b) b [Alt b] -- Binder gets bound to value of scrutinee
80 -- DEFAULT case must be *first*, if it occurs at all
82 | Type Type -- This should only show up at the top
85 type Arg b = Expr b -- Can be a Type
87 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
89 data AltCon = DataAlt DataCon
94 data Bind b = NonRec b (Expr b)
101 Type -- The to-type: type of whole coerce expression
102 Type -- The from-type: type of enclosed expression
104 | InlineCall -- Instructs simplifier to inline
107 | InlineMe -- Instructs simplifer to treat the enclosed expression
108 -- as very small, and inline it at its call sites
110 -- NOTE: we also treat expressions wrapped in InlineMe as
111 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
112 -- What this means is that we obediently inline even things that don't
113 -- look like valuse. This is sometimes important:
116 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
117 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
118 -- should inline f even inside lambdas. In effect, we should trust the programmer.
123 * The RHS of a letrec, and the RHSs of all top-level lets,
124 must be of LIFTED type.
126 * The RHS of a let, may be of UNLIFTED type, but only if the expression
127 is ok-for-speculation. This means that the let can be floated around
128 without difficulty. e.g.
130 y::Int# = fac 4# not ok [use case instead]
132 * The argument of an App can be of any type.
134 * The simplifier tries to ensure that if the RHS of a let is a constructor
135 application, its arguments are trivial, so that the constructor can be
139 %************************************************************************
141 \subsection{Transformation rules}
143 %************************************************************************
145 The CoreRule type and its friends are dealt with mainly in CoreRules,
146 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
151 VarSet -- Locally-defined free vars of RHSs
153 emptyCoreRules :: CoreRules
154 emptyCoreRules = Rules [] emptyVarSet
156 isEmptyCoreRules :: CoreRules -> Bool
157 isEmptyCoreRules (Rules rs _) = null rs
159 rulesRhsFreeVars :: CoreRules -> VarSet
160 rulesRhsFreeVars (Rules _ fvs) = fvs
162 rulesRules :: CoreRules -> [CoreRule]
163 rulesRules (Rules rules _) = rules
167 type RuleName = FAST_STRING
168 type IdCoreRule = (Id,CoreRule) -- Rules don't have their leading Id inside them
172 [CoreBndr] -- Forall'd variables
173 [CoreExpr] -- LHS args
176 | BuiltinRule -- Built-in rules are used for constant folding
177 -- and suchlike. It has no free variables.
178 ([CoreExpr] -> Maybe (RuleName, CoreExpr))
180 isBuiltinRule (BuiltinRule _) = True
181 isBuiltinRule _ = False
185 %************************************************************************
187 \subsection{@Unfolding@ type}
189 %************************************************************************
191 The @Unfolding@ type is declared here to avoid numerous loops, but it
192 should be abstract everywhere except in CoreUnfold.lhs
198 | OtherCon [AltCon] -- It ain't one of these
199 -- (OtherCon xs) also indicates that something has been evaluated
200 -- and hence there's no point in re-evaluating it.
201 -- OtherCon [] is used even for non-data-type values
202 -- to indicated evaluated-ness. Notably:
203 -- data C = C !(Int -> Int)
204 -- case x of { C f -> ... }
205 -- Here, f gets an OtherCon [] unfolding.
207 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
208 -- so you'd better unfold.
210 | CoreUnfolding -- An unfolding with redundant cached information
211 CoreExpr -- Template; binder-info is correct
212 Bool -- True <=> top level binding
213 Bool -- exprIsValue template (cached); it is ok to discard a `seq` on
215 Bool -- True <=> doesn't waste (much) work to expand inside an inlining
216 -- Basically it's exprIsCheap
217 UnfoldingGuidance -- Tells about the *size* of the template.
220 data UnfoldingGuidance
222 | UnfoldIfGoodArgs Int -- and "n" value args
224 [Int] -- Discount if the argument is evaluated.
225 -- (i.e., a simplification will definitely
226 -- be possible). One elt of the list per *value* arg.
228 Int -- The "size" of the unfolding; to be elaborated
231 Int -- Scrutinee discount: the discount to substract if the thing is in
232 -- a context (case (thing args) of ...),
233 -- (where there are the right number of arguments.)
235 noUnfolding = NoUnfolding
236 mkOtherCon = OtherCon
238 seqUnfolding :: Unfolding -> ()
239 seqUnfolding (CoreUnfolding e top b1 b2 g)
240 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
241 seqUnfolding other = ()
243 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
244 seqGuidance other = ()
248 unfoldingTemplate :: Unfolding -> CoreExpr
249 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
250 unfoldingTemplate (CompulsoryUnfolding expr) = expr
251 unfoldingTemplate other = panic "getUnfoldingTemplate"
253 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
254 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
255 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
256 maybeUnfoldingTemplate other = Nothing
258 otherCons :: Unfolding -> [AltCon]
259 otherCons (OtherCon cons) = cons
262 isValueUnfolding :: Unfolding -> Bool
263 -- Returns False for OtherCon
264 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
265 isValueUnfolding other = False
267 isEvaldUnfolding :: Unfolding -> Bool
268 -- Returns True for OtherCon
269 isEvaldUnfolding (OtherCon _) = True
270 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
271 isEvaldUnfolding other = False
273 isCheapUnfolding :: Unfolding -> Bool
274 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
275 isCheapUnfolding other = False
277 isCompulsoryUnfolding :: Unfolding -> Bool
278 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
279 isCompulsoryUnfolding other = False
281 hasUnfolding :: Unfolding -> Bool
282 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
283 hasUnfolding (CompulsoryUnfolding _) = True
284 hasUnfolding other = False
286 hasSomeUnfolding :: Unfolding -> Bool
287 hasSomeUnfolding NoUnfolding = False
288 hasSomeUnfolding other = True
290 neverUnfold :: Unfolding -> Bool
291 neverUnfold NoUnfolding = True
292 neverUnfold (OtherCon _) = True
293 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
294 neverUnfold other = False
298 %************************************************************************
300 \subsection{The main data type}
302 %************************************************************************
305 -- The Ord is needed for the FiniteMap used in the lookForConstructor
306 -- in SimplEnv. If you declared that lookForConstructor *ignores*
307 -- constructor-applications with LitArg args, then you could get
310 instance Outputable AltCon where
311 ppr (DataAlt dc) = ppr dc
312 ppr (LitAlt lit) = ppr lit
313 ppr DEFAULT = ptext SLIT("__DEFAULT")
315 instance Show AltCon where
316 showsPrec p con = showsPrecSDoc p (ppr con)
320 %************************************************************************
322 \subsection{Useful synonyms}
324 %************************************************************************
330 type CoreExpr = Expr CoreBndr
331 type CoreArg = Arg CoreBndr
332 type CoreBind = Bind CoreBndr
333 type CoreAlt = Alt CoreBndr
336 Binders are ``tagged'' with a \tr{t}:
339 type Tagged t = (CoreBndr, t)
341 type TaggedBind t = Bind (Tagged t)
342 type TaggedExpr t = Expr (Tagged t)
343 type TaggedArg t = Arg (Tagged t)
344 type TaggedAlt t = Alt (Tagged t)
348 %************************************************************************
350 \subsection{Core-constructing functions with checking}
352 %************************************************************************
355 mkApps :: Expr b -> [Arg b] -> Expr b
356 mkTyApps :: Expr b -> [Type] -> Expr b
357 mkValApps :: Expr b -> [Expr b] -> Expr b
358 mkVarApps :: Expr b -> [Var] -> Expr b
360 mkApps f args = foldl App f args
361 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
362 mkValApps f args = foldl (\ e a -> App e a) f args
363 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
365 mkLit :: Literal -> Expr b
366 mkIntLit :: Integer -> Expr b
367 mkIntLitInt :: Int -> Expr b
368 mkConApp :: DataCon -> [Arg b] -> Expr b
369 mkLets :: [Bind b] -> Expr b -> Expr b
370 mkLams :: [b] -> Expr b -> Expr b
373 mkConApp con args = mkApps (Var (dataConId con)) args
375 mkLams binders body = foldr Lam body binders
376 mkLets binds body = foldr Let body binds
378 mkIntLit n = Lit (mkMachInt n)
379 mkIntLitInt n = Lit (mkMachInt (toInteger n))
381 varToCoreExpr :: CoreBndr -> Expr b
382 varToCoreExpr v | isId v = Var v
383 | otherwise = Type (mkTyVarTy v)
387 %************************************************************************
389 \subsection{Simple access functions}
391 %************************************************************************
394 bindersOf :: Bind b -> [b]
395 bindersOf (NonRec binder _) = [binder]
396 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
398 bindersOfBinds :: [Bind b] -> [b]
399 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
401 rhssOfBind :: Bind b -> [Expr b]
402 rhssOfBind (NonRec _ rhs) = [rhs]
403 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
405 rhssOfAlts :: [Alt b] -> [Expr b]
406 rhssOfAlts alts = [e | (_,_,e) <- alts]
408 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
409 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
410 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
414 We often want to strip off leading lambdas before getting down to
415 business. @collectBinders@ is your friend.
417 We expect (by convention) type-, and value- lambdas in that
421 collectBinders :: Expr b -> ([b], Expr b)
422 collectBindersIgnoringNotes :: Expr b -> ([b], Expr b)
423 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
424 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
425 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
430 go bs (Lam b e) = go (b:bs) e
431 go bs e = (reverse bs, e)
433 -- This one ignores notes. It's used in CoreUnfold and StrAnal
434 -- when we aren't going to put the expression back together from
435 -- the pieces, so we don't mind losing the Notes
436 collectBindersIgnoringNotes expr
439 go bs (Lam b e) = go (b:bs) e
440 go bs (Note _ e) = go bs e
441 go bs e = (reverse bs, e)
443 collectTyAndValBinders expr
446 (tvs, body1) = collectTyBinders expr
447 (ids, body) = collectValBinders body1
449 collectTyBinders expr
452 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
453 go tvs e = (reverse tvs, e)
455 collectValBinders expr
458 go ids (Lam b e) | isId b = go (b:ids) e
459 go ids body = (reverse ids, body)
463 @collectArgs@ takes an application expression, returning the function
464 and the arguments to which it is applied.
467 collectArgs :: Expr b -> (Expr b, [Arg b])
471 go (App f a) as = go f (a:as)
475 coreExprCc gets the cost centre enclosing an expression, if any.
476 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
479 coreExprCc :: Expr b -> CostCentre
480 coreExprCc (Note (SCC cc) e) = cc
481 coreExprCc (Note other_note e) = coreExprCc e
482 coreExprCc (Lam _ e) = coreExprCc e
483 coreExprCc other = noCostCentre
488 %************************************************************************
490 \subsection{Predicates}
492 %************************************************************************
494 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
495 i.e. if type applications are actual lambdas because types are kept around
498 Similarly isRuntimeArg.
501 isRuntimeVar :: Var -> Bool
502 isRuntimeVar | opt_RuntimeTypes = \v -> True
503 | otherwise = \v -> isId v
505 isRuntimeArg :: CoreExpr -> Bool
506 isRuntimeArg | opt_RuntimeTypes = \e -> True
507 | otherwise = \e -> isValArg e
511 isValArg (Type _) = False
512 isValArg other = True
514 isTypeArg (Type _) = True
515 isTypeArg other = False
517 valBndrCount :: [CoreBndr] -> Int
519 valBndrCount (b : bs) | isId b = 1 + valBndrCount bs
520 | otherwise = valBndrCount bs
522 valArgCount :: [Arg b] -> Int
524 valArgCount (Type _ : args) = valArgCount args
525 valArgCount (other : args) = 1 + valArgCount args
529 %************************************************************************
531 \subsection{Seq stuff}
533 %************************************************************************
536 seqExpr :: CoreExpr -> ()
537 seqExpr (Var v) = v `seq` ()
538 seqExpr (Lit lit) = lit `seq` ()
539 seqExpr (App f a) = seqExpr f `seq` seqExpr a
540 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
541 seqExpr (Let b e) = seqBind b `seq` seqExpr e
542 seqExpr (Case e b as) = seqExpr e `seq` seqBndr b `seq` seqAlts as
543 seqExpr (Note n e) = seqNote n `seq` seqExpr e
544 seqExpr (Type t) = seqType t
547 seqExprs (e:es) = seqExpr e `seq` seqExprs es
549 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
552 seqBndr b = b `seq` ()
555 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
557 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
558 seqBind (Rec prs) = seqPairs prs
561 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
564 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
566 seqRules :: CoreRules -> ()
567 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
570 seq_rules (Rule fs bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
571 seq_rules (BuiltinRule _ : rules) = seq_rules rules
576 %************************************************************************
578 \subsection{Annotated core; annotation at every node in the tree}
580 %************************************************************************
583 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
585 data AnnExpr' bndr annot
588 | AnnLam bndr (AnnExpr bndr annot)
589 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
590 | AnnCase (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
591 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
592 | AnnNote Note (AnnExpr bndr annot)
595 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
597 data AnnBind bndr annot
598 = AnnNonRec bndr (AnnExpr bndr annot)
599 | AnnRec [(bndr, AnnExpr bndr annot)]
603 deAnnotate :: AnnExpr bndr annot -> Expr bndr
604 deAnnotate (_, e) = deAnnotate' e
606 deAnnotate' (AnnType t) = Type t
607 deAnnotate' (AnnVar v) = Var v
608 deAnnotate' (AnnLit lit) = Lit lit
609 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
610 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
611 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
613 deAnnotate' (AnnLet bind body)
614 = Let (deAnnBind bind) (deAnnotate body)
616 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
617 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
619 deAnnotate' (AnnCase scrut v alts)
620 = Case (deAnnotate scrut) v (map deAnnAlt alts)
622 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
623 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)