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, TaggedBndr(..),
13 mkApps, mkTyApps, mkValApps, mkVarApps,
14 mkLit, mkIntLitInt, mkIntLit,
19 bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts,
20 collectBinders, collectTyBinders, collectValBinders, collectTyAndValBinders,
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, collectAnnBndrs,
42 CoreRules(..), -- Representation needed by friends
43 CoreRule(..), -- CoreSubst, CoreTidy, CoreFVs, PprCore only
46 emptyCoreRules, isEmptyCoreRules, rulesRhsFreeVars, rulesRules,
47 isBuiltinRule, ruleName
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, dataConWorkId )
58 import BasicTypes ( Activation )
64 %************************************************************************
66 \subsection{The main data types}
68 %************************************************************************
70 These data types are the heart of the compiler
73 infixl 8 `App` -- App brackets to the left
75 data Expr b -- "b" for the type of binders,
78 | App (Expr b) (Arg b)
80 | Let (Bind b) (Expr b)
81 -- gaw 2004, added Type field
82 | Case (Expr b) b Type [Alt b] -- Binder gets bound to value of scrutinee
83 -- Invariant: The list of alternatives is ALWAYS EXHAUSTIVE,
84 -- meaning that it covers all cases that can occur
85 -- See the example below
87 -- Invariant: The DEFAULT case must be *first*, if it occurs at all
89 | Type Type -- This should only show up at the top
92 -- An "exhausive" case does not necessarily mention all constructors:
93 -- data Foo = Red | Green | Blue
97 -- other -> f (case x of
100 -- The inner case does not need a Red alternative, because x can't be Red at
101 -- that program point.
104 type Arg b = Expr b -- Can be a Type
106 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
108 data AltCon = DataAlt DataCon
113 data Bind b = NonRec b (Expr b)
114 | Rec [(b, (Expr b))]
120 Type -- The to-type: type of whole coerce expression
121 Type -- The from-type: type of enclosed expression
123 | InlineCall -- Instructs simplifier to inline
126 | InlineMe -- Instructs simplifer to treat the enclosed expression
127 -- as very small, and inline it at its call sites
129 | CoreNote String -- A generic core annotation, propagated but not used by GHC
131 -- NOTE: we also treat expressions wrapped in InlineMe as
132 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
133 -- What this means is that we obediently inline even things that don't
134 -- look like valuse. This is sometimes important:
137 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
138 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
139 -- should inline f even inside lambdas. In effect, we should trust the programmer.
144 * The RHS of a letrec, and the RHSs of all top-level lets,
145 must be of LIFTED type.
147 * The RHS of a let, may be of UNLIFTED type, but only if the expression
148 is ok-for-speculation. This means that the let can be floated around
149 without difficulty. e.g.
151 y::Int# = fac 4# not ok [use case instead]
153 * The argument of an App can be of any type.
155 * The simplifier tries to ensure that if the RHS of a let is a constructor
156 application, its arguments are trivial, so that the constructor can be
160 %************************************************************************
162 \subsection{Transformation rules}
164 %************************************************************************
166 The CoreRule type and its friends are dealt with mainly in CoreRules,
167 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
172 VarSet -- Locally-defined free vars of RHSs
174 emptyCoreRules :: CoreRules
175 emptyCoreRules = Rules [] emptyVarSet
177 isEmptyCoreRules :: CoreRules -> Bool
178 isEmptyCoreRules (Rules rs _) = null rs
180 rulesRhsFreeVars :: CoreRules -> VarSet
181 rulesRhsFreeVars (Rules _ fvs) = fvs
183 rulesRules :: CoreRules -> [CoreRule]
184 rulesRules (Rules rules _) = rules
188 type RuleName = FastString
189 type IdCoreRule = (Id,CoreRule) -- Rules don't have their leading Id inside them
193 Activation -- When the rule is active
194 [CoreBndr] -- Forall'd variables
195 [CoreExpr] -- LHS args
198 | BuiltinRule -- Built-in rules are used for constant folding
199 RuleName -- and suchlike. It has no free variables.
200 ([CoreExpr] -> Maybe CoreExpr)
202 isBuiltinRule (BuiltinRule _ _) = True
203 isBuiltinRule _ = False
205 ruleName :: CoreRule -> RuleName
206 ruleName (Rule n _ _ _ _) = n
207 ruleName (BuiltinRule n _) = n
211 %************************************************************************
213 \subsection{@Unfolding@ type}
215 %************************************************************************
217 The @Unfolding@ type is declared here to avoid numerous loops, but it
218 should be abstract everywhere except in CoreUnfold.lhs
224 | OtherCon [AltCon] -- It ain't one of these
225 -- (OtherCon xs) also indicates that something has been evaluated
226 -- and hence there's no point in re-evaluating it.
227 -- OtherCon [] is used even for non-data-type values
228 -- to indicated evaluated-ness. Notably:
229 -- data C = C !(Int -> Int)
230 -- case x of { C f -> ... }
231 -- Here, f gets an OtherCon [] unfolding.
233 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
234 -- so you'd better unfold.
236 | CoreUnfolding -- An unfolding with redundant cached information
237 CoreExpr -- Template; binder-info is correct
238 Bool -- True <=> top level binding
239 Bool -- exprIsValue template (cached); it is ok to discard a `seq` on
241 Bool -- True <=> doesn't waste (much) work to expand inside an inlining
242 -- Basically it's exprIsCheap
243 UnfoldingGuidance -- Tells about the *size* of the template.
246 data UnfoldingGuidance
248 | UnfoldIfGoodArgs Int -- and "n" value args
250 [Int] -- Discount if the argument is evaluated.
251 -- (i.e., a simplification will definitely
252 -- be possible). One elt of the list per *value* arg.
254 Int -- The "size" of the unfolding; to be elaborated
257 Int -- Scrutinee discount: the discount to substract if the thing is in
258 -- a context (case (thing args) of ...),
259 -- (where there are the right number of arguments.)
261 noUnfolding = NoUnfolding
262 mkOtherCon = OtherCon
264 seqUnfolding :: Unfolding -> ()
265 seqUnfolding (CoreUnfolding e top b1 b2 g)
266 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
267 seqUnfolding other = ()
269 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
270 seqGuidance other = ()
274 unfoldingTemplate :: Unfolding -> CoreExpr
275 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
276 unfoldingTemplate (CompulsoryUnfolding expr) = expr
277 unfoldingTemplate other = panic "getUnfoldingTemplate"
279 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
280 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
281 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
282 maybeUnfoldingTemplate other = Nothing
284 otherCons :: Unfolding -> [AltCon]
285 otherCons (OtherCon cons) = cons
288 isValueUnfolding :: Unfolding -> Bool
289 -- Returns False for OtherCon
290 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
291 isValueUnfolding other = False
293 isEvaldUnfolding :: Unfolding -> Bool
294 -- Returns True for OtherCon
295 isEvaldUnfolding (OtherCon _) = True
296 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
297 isEvaldUnfolding other = False
299 isCheapUnfolding :: Unfolding -> Bool
300 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
301 isCheapUnfolding other = False
303 isCompulsoryUnfolding :: Unfolding -> Bool
304 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
305 isCompulsoryUnfolding other = False
307 hasUnfolding :: Unfolding -> Bool
308 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
309 hasUnfolding (CompulsoryUnfolding _) = True
310 hasUnfolding other = False
312 hasSomeUnfolding :: Unfolding -> Bool
313 hasSomeUnfolding NoUnfolding = False
314 hasSomeUnfolding other = True
316 neverUnfold :: Unfolding -> Bool
317 neverUnfold NoUnfolding = True
318 neverUnfold (OtherCon _) = True
319 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
320 neverUnfold other = False
324 %************************************************************************
326 \subsection{The main data type}
328 %************************************************************************
331 -- The Ord is needed for the FiniteMap used in the lookForConstructor
332 -- in SimplEnv. If you declared that lookForConstructor *ignores*
333 -- constructor-applications with LitArg args, then you could get
336 instance Outputable AltCon where
337 ppr (DataAlt dc) = ppr dc
338 ppr (LitAlt lit) = ppr lit
339 ppr DEFAULT = ptext SLIT("__DEFAULT")
341 instance Show AltCon where
342 showsPrec p con = showsPrecSDoc p (ppr con)
346 %************************************************************************
348 \subsection{Useful synonyms}
350 %************************************************************************
356 type CoreExpr = Expr CoreBndr
357 type CoreArg = Arg CoreBndr
358 type CoreBind = Bind CoreBndr
359 type CoreAlt = Alt CoreBndr
362 Binders are ``tagged'' with a \tr{t}:
365 data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder"
367 type TaggedBind t = Bind (TaggedBndr t)
368 type TaggedExpr t = Expr (TaggedBndr t)
369 type TaggedArg t = Arg (TaggedBndr t)
370 type TaggedAlt t = Alt (TaggedBndr t)
372 instance Outputable b => Outputable (TaggedBndr b) where
373 ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
375 instance Outputable b => OutputableBndr (TaggedBndr b) where
376 pprBndr _ b = ppr b -- Simple
380 %************************************************************************
382 \subsection{Core-constructing functions with checking}
384 %************************************************************************
387 mkApps :: Expr b -> [Arg b] -> Expr b
388 mkTyApps :: Expr b -> [Type] -> Expr b
389 mkValApps :: Expr b -> [Expr b] -> Expr b
390 mkVarApps :: Expr b -> [Var] -> Expr b
392 mkApps f args = foldl App f args
393 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
394 mkValApps f args = foldl (\ e a -> App e a) f args
395 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
397 mkLit :: Literal -> Expr b
398 mkIntLit :: Integer -> Expr b
399 mkIntLitInt :: Int -> Expr b
400 mkConApp :: DataCon -> [Arg b] -> Expr b
401 mkLets :: [Bind b] -> Expr b -> Expr b
402 mkLams :: [b] -> Expr b -> Expr b
405 mkConApp con args = mkApps (Var (dataConWorkId con)) args
407 mkLams binders body = foldr Lam body binders
408 mkLets binds body = foldr Let body binds
410 mkIntLit n = Lit (mkMachInt n)
411 mkIntLitInt n = Lit (mkMachInt (toInteger n))
413 varToCoreExpr :: CoreBndr -> Expr b
414 varToCoreExpr v | isId v = Var v
415 | otherwise = Type (mkTyVarTy v)
419 %************************************************************************
421 \subsection{Simple access functions}
423 %************************************************************************
426 bindersOf :: Bind b -> [b]
427 bindersOf (NonRec binder _) = [binder]
428 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
430 bindersOfBinds :: [Bind b] -> [b]
431 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
433 rhssOfBind :: Bind b -> [Expr b]
434 rhssOfBind (NonRec _ rhs) = [rhs]
435 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
437 rhssOfAlts :: [Alt b] -> [Expr b]
438 rhssOfAlts alts = [e | (_,_,e) <- alts]
440 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
441 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
442 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
446 We often want to strip off leading lambdas before getting down to
447 business. @collectBinders@ is your friend.
449 We expect (by convention) type-, and value- lambdas in that
453 collectBinders :: Expr b -> ([b], Expr b)
454 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
455 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
456 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
461 go bs (Lam b e) = go (b:bs) e
462 go bs e = (reverse bs, e)
464 collectTyAndValBinders expr
467 (tvs, body1) = collectTyBinders expr
468 (ids, body) = collectValBinders body1
470 collectTyBinders expr
473 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
474 go tvs e = (reverse tvs, e)
476 collectValBinders expr
479 go ids (Lam b e) | isId b = go (b:ids) e
480 go ids body = (reverse ids, body)
484 @collectArgs@ takes an application expression, returning the function
485 and the arguments to which it is applied.
488 collectArgs :: Expr b -> (Expr b, [Arg b])
492 go (App f a) as = go f (a:as)
496 coreExprCc gets the cost centre enclosing an expression, if any.
497 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
500 coreExprCc :: Expr b -> CostCentre
501 coreExprCc (Note (SCC cc) e) = cc
502 coreExprCc (Note other_note e) = coreExprCc e
503 coreExprCc (Lam _ e) = coreExprCc e
504 coreExprCc other = noCostCentre
509 %************************************************************************
511 \subsection{Predicates}
513 %************************************************************************
515 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
516 i.e. if type applications are actual lambdas because types are kept around
519 Similarly isRuntimeArg.
522 isRuntimeVar :: Var -> Bool
523 isRuntimeVar | opt_RuntimeTypes = \v -> True
524 | otherwise = \v -> isId v
526 isRuntimeArg :: CoreExpr -> Bool
527 isRuntimeArg | opt_RuntimeTypes = \e -> True
528 | otherwise = \e -> isValArg e
532 isValArg (Type _) = False
533 isValArg other = True
535 isTypeArg (Type _) = True
536 isTypeArg other = False
538 valBndrCount :: [CoreBndr] -> Int
540 valBndrCount (b : bs) | isId b = 1 + valBndrCount bs
541 | otherwise = valBndrCount bs
543 valArgCount :: [Arg b] -> Int
545 valArgCount (Type _ : args) = valArgCount args
546 valArgCount (other : args) = 1 + valArgCount args
550 %************************************************************************
552 \subsection{Seq stuff}
554 %************************************************************************
557 seqExpr :: CoreExpr -> ()
558 seqExpr (Var v) = v `seq` ()
559 seqExpr (Lit lit) = lit `seq` ()
560 seqExpr (App f a) = seqExpr f `seq` seqExpr a
561 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
562 seqExpr (Let b e) = seqBind b `seq` seqExpr e
564 seqExpr (Case e b t as) = seqExpr e `seq` seqBndr b `seq` seqType t `seq` seqAlts as
565 seqExpr (Note n e) = seqNote n `seq` seqExpr e
566 seqExpr (Type t) = seqType t
569 seqExprs (e:es) = seqExpr e `seq` seqExprs es
571 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
572 seqNote (CoreNote s) = s `seq` ()
575 seqBndr b = b `seq` ()
578 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
580 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
581 seqBind (Rec prs) = seqPairs prs
584 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
587 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
589 seqRules :: CoreRules -> ()
590 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
593 seq_rules (Rule fs _ bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
594 seq_rules (BuiltinRule _ _ : rules) = seq_rules rules
599 %************************************************************************
601 \subsection{Annotated core; annotation at every node in the tree}
603 %************************************************************************
606 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
608 data AnnExpr' bndr annot
611 | AnnLam bndr (AnnExpr bndr annot)
612 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
614 | AnnCase (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot]
615 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
616 | AnnNote Note (AnnExpr bndr annot)
619 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
621 data AnnBind bndr annot
622 = AnnNonRec bndr (AnnExpr bndr annot)
623 | AnnRec [(bndr, AnnExpr bndr annot)]
627 deAnnotate :: AnnExpr bndr annot -> Expr bndr
628 deAnnotate (_, e) = deAnnotate' e
630 deAnnotate' (AnnType t) = Type t
631 deAnnotate' (AnnVar v) = Var v
632 deAnnotate' (AnnLit lit) = Lit lit
633 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
634 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
635 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
637 deAnnotate' (AnnLet bind body)
638 = Let (deAnnBind bind) (deAnnotate body)
640 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
641 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
644 deAnnotate' (AnnCase scrut v t alts)
645 = Case (deAnnotate scrut) v t (map deAnnAlt alts)
647 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
648 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
652 collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
656 collect bs (_, AnnLam b body) = collect (b:bs) body
657 collect bs body = (reverse bs, body)