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 | Case (Expr b) b [Alt b] -- Binder gets bound to value of scrutinee
82 -- DEFAULT case must be *first*, if it occurs at all
84 | Type Type -- This should only show up at the top
87 type Arg b = Expr b -- Can be a Type
89 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
91 data AltCon = DataAlt DataCon
96 data Bind b = NonRec b (Expr b)
103 Type -- The to-type: type of whole coerce expression
104 Type -- The from-type: type of enclosed expression
106 | InlineCall -- Instructs simplifier to inline
109 | InlineMe -- Instructs simplifer to treat the enclosed expression
110 -- as very small, and inline it at its call sites
112 -- NOTE: we also treat expressions wrapped in InlineMe as
113 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
114 -- What this means is that we obediently inline even things that don't
115 -- look like valuse. This is sometimes important:
118 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
119 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
120 -- should inline f even inside lambdas. In effect, we should trust the programmer.
125 * The RHS of a letrec, and the RHSs of all top-level lets,
126 must be of LIFTED type.
128 * The RHS of a let, may be of UNLIFTED type, but only if the expression
129 is ok-for-speculation. This means that the let can be floated around
130 without difficulty. e.g.
132 y::Int# = fac 4# not ok [use case instead]
134 * The argument of an App can be of any type.
136 * The simplifier tries to ensure that if the RHS of a let is a constructor
137 application, its arguments are trivial, so that the constructor can be
141 %************************************************************************
143 \subsection{Transformation rules}
145 %************************************************************************
147 The CoreRule type and its friends are dealt with mainly in CoreRules,
148 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
153 VarSet -- Locally-defined free vars of RHSs
155 emptyCoreRules :: CoreRules
156 emptyCoreRules = Rules [] emptyVarSet
158 isEmptyCoreRules :: CoreRules -> Bool
159 isEmptyCoreRules (Rules rs _) = null rs
161 rulesRhsFreeVars :: CoreRules -> VarSet
162 rulesRhsFreeVars (Rules _ fvs) = fvs
164 rulesRules :: CoreRules -> [CoreRule]
165 rulesRules (Rules rules _) = rules
169 type RuleName = FastString
170 type IdCoreRule = (Id,CoreRule) -- Rules don't have their leading Id inside them
174 Activation -- When the rule is active
175 [CoreBndr] -- Forall'd variables
176 [CoreExpr] -- LHS args
179 | BuiltinRule -- Built-in rules are used for constant folding
180 RuleName -- and suchlike. It has no free variables.
181 ([CoreExpr] -> Maybe CoreExpr)
183 isBuiltinRule (BuiltinRule _ _) = True
184 isBuiltinRule _ = False
186 ruleName :: CoreRule -> RuleName
187 ruleName (Rule n _ _ _ _) = n
188 ruleName (BuiltinRule n _) = n
192 %************************************************************************
194 \subsection{@Unfolding@ type}
196 %************************************************************************
198 The @Unfolding@ type is declared here to avoid numerous loops, but it
199 should be abstract everywhere except in CoreUnfold.lhs
205 | OtherCon [AltCon] -- It ain't one of these
206 -- (OtherCon xs) also indicates that something has been evaluated
207 -- and hence there's no point in re-evaluating it.
208 -- OtherCon [] is used even for non-data-type values
209 -- to indicated evaluated-ness. Notably:
210 -- data C = C !(Int -> Int)
211 -- case x of { C f -> ... }
212 -- Here, f gets an OtherCon [] unfolding.
214 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
215 -- so you'd better unfold.
217 | CoreUnfolding -- An unfolding with redundant cached information
218 CoreExpr -- Template; binder-info is correct
219 Bool -- True <=> top level binding
220 Bool -- exprIsValue template (cached); it is ok to discard a `seq` on
222 Bool -- True <=> doesn't waste (much) work to expand inside an inlining
223 -- Basically it's exprIsCheap
224 UnfoldingGuidance -- Tells about the *size* of the template.
227 data UnfoldingGuidance
229 | UnfoldIfGoodArgs Int -- and "n" value args
231 [Int] -- Discount if the argument is evaluated.
232 -- (i.e., a simplification will definitely
233 -- be possible). One elt of the list per *value* arg.
235 Int -- The "size" of the unfolding; to be elaborated
238 Int -- Scrutinee discount: the discount to substract if the thing is in
239 -- a context (case (thing args) of ...),
240 -- (where there are the right number of arguments.)
242 noUnfolding = NoUnfolding
243 mkOtherCon = OtherCon
245 seqUnfolding :: Unfolding -> ()
246 seqUnfolding (CoreUnfolding e top b1 b2 g)
247 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
248 seqUnfolding other = ()
250 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
251 seqGuidance other = ()
255 unfoldingTemplate :: Unfolding -> CoreExpr
256 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
257 unfoldingTemplate (CompulsoryUnfolding expr) = expr
258 unfoldingTemplate other = panic "getUnfoldingTemplate"
260 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
261 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
262 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
263 maybeUnfoldingTemplate other = Nothing
265 otherCons :: Unfolding -> [AltCon]
266 otherCons (OtherCon cons) = cons
269 isValueUnfolding :: Unfolding -> Bool
270 -- Returns False for OtherCon
271 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
272 isValueUnfolding other = False
274 isEvaldUnfolding :: Unfolding -> Bool
275 -- Returns True for OtherCon
276 isEvaldUnfolding (OtherCon _) = True
277 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
278 isEvaldUnfolding other = False
280 isCheapUnfolding :: Unfolding -> Bool
281 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
282 isCheapUnfolding other = False
284 isCompulsoryUnfolding :: Unfolding -> Bool
285 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
286 isCompulsoryUnfolding other = False
288 hasUnfolding :: Unfolding -> Bool
289 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
290 hasUnfolding (CompulsoryUnfolding _) = True
291 hasUnfolding other = False
293 hasSomeUnfolding :: Unfolding -> Bool
294 hasSomeUnfolding NoUnfolding = False
295 hasSomeUnfolding other = True
297 neverUnfold :: Unfolding -> Bool
298 neverUnfold NoUnfolding = True
299 neverUnfold (OtherCon _) = True
300 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
301 neverUnfold other = False
305 %************************************************************************
307 \subsection{The main data type}
309 %************************************************************************
312 -- The Ord is needed for the FiniteMap used in the lookForConstructor
313 -- in SimplEnv. If you declared that lookForConstructor *ignores*
314 -- constructor-applications with LitArg args, then you could get
317 instance Outputable AltCon where
318 ppr (DataAlt dc) = ppr dc
319 ppr (LitAlt lit) = ppr lit
320 ppr DEFAULT = ptext SLIT("__DEFAULT")
322 instance Show AltCon where
323 showsPrec p con = showsPrecSDoc p (ppr con)
327 %************************************************************************
329 \subsection{Useful synonyms}
331 %************************************************************************
337 type CoreExpr = Expr CoreBndr
338 type CoreArg = Arg CoreBndr
339 type CoreBind = Bind CoreBndr
340 type CoreAlt = Alt CoreBndr
343 Binders are ``tagged'' with a \tr{t}:
346 data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder"
348 type TaggedBind t = Bind (TaggedBndr t)
349 type TaggedExpr t = Expr (TaggedBndr t)
350 type TaggedArg t = Arg (TaggedBndr t)
351 type TaggedAlt t = Alt (TaggedBndr t)
353 instance Outputable b => Outputable (TaggedBndr b) where
354 ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
356 instance Outputable b => OutputableBndr (TaggedBndr b) where
357 pprBndr _ b = ppr b -- Simple
361 %************************************************************************
363 \subsection{Core-constructing functions with checking}
365 %************************************************************************
368 mkApps :: Expr b -> [Arg b] -> Expr b
369 mkTyApps :: Expr b -> [Type] -> Expr b
370 mkValApps :: Expr b -> [Expr b] -> Expr b
371 mkVarApps :: Expr b -> [Var] -> Expr b
373 mkApps f args = foldl App f args
374 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
375 mkValApps f args = foldl (\ e a -> App e a) f args
376 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
378 mkLit :: Literal -> Expr b
379 mkIntLit :: Integer -> Expr b
380 mkIntLitInt :: Int -> Expr b
381 mkConApp :: DataCon -> [Arg b] -> Expr b
382 mkLets :: [Bind b] -> Expr b -> Expr b
383 mkLams :: [b] -> Expr b -> Expr b
386 mkConApp con args = mkApps (Var (dataConWorkId con)) args
388 mkLams binders body = foldr Lam body binders
389 mkLets binds body = foldr Let body binds
391 mkIntLit n = Lit (mkMachInt n)
392 mkIntLitInt n = Lit (mkMachInt (toInteger n))
394 varToCoreExpr :: CoreBndr -> Expr b
395 varToCoreExpr v | isId v = Var v
396 | otherwise = Type (mkTyVarTy v)
400 %************************************************************************
402 \subsection{Simple access functions}
404 %************************************************************************
407 bindersOf :: Bind b -> [b]
408 bindersOf (NonRec binder _) = [binder]
409 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
411 bindersOfBinds :: [Bind b] -> [b]
412 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
414 rhssOfBind :: Bind b -> [Expr b]
415 rhssOfBind (NonRec _ rhs) = [rhs]
416 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
418 rhssOfAlts :: [Alt b] -> [Expr b]
419 rhssOfAlts alts = [e | (_,_,e) <- alts]
421 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
422 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
423 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
427 We often want to strip off leading lambdas before getting down to
428 business. @collectBinders@ is your friend.
430 We expect (by convention) type-, and value- lambdas in that
434 collectBinders :: Expr b -> ([b], Expr b)
435 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
436 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
437 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
442 go bs (Lam b e) = go (b:bs) e
443 go bs e = (reverse bs, e)
445 collectTyAndValBinders expr
448 (tvs, body1) = collectTyBinders expr
449 (ids, body) = collectValBinders body1
451 collectTyBinders expr
454 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
455 go tvs e = (reverse tvs, e)
457 collectValBinders expr
460 go ids (Lam b e) | isId b = go (b:ids) e
461 go ids body = (reverse ids, body)
465 @collectArgs@ takes an application expression, returning the function
466 and the arguments to which it is applied.
469 collectArgs :: Expr b -> (Expr b, [Arg b])
473 go (App f a) as = go f (a:as)
477 coreExprCc gets the cost centre enclosing an expression, if any.
478 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
481 coreExprCc :: Expr b -> CostCentre
482 coreExprCc (Note (SCC cc) e) = cc
483 coreExprCc (Note other_note e) = coreExprCc e
484 coreExprCc (Lam _ e) = coreExprCc e
485 coreExprCc other = noCostCentre
490 %************************************************************************
492 \subsection{Predicates}
494 %************************************************************************
496 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
497 i.e. if type applications are actual lambdas because types are kept around
500 Similarly isRuntimeArg.
503 isRuntimeVar :: Var -> Bool
504 isRuntimeVar | opt_RuntimeTypes = \v -> True
505 | otherwise = \v -> isId v
507 isRuntimeArg :: CoreExpr -> Bool
508 isRuntimeArg | opt_RuntimeTypes = \e -> True
509 | otherwise = \e -> isValArg e
513 isValArg (Type _) = False
514 isValArg other = True
516 isTypeArg (Type _) = True
517 isTypeArg other = False
519 valBndrCount :: [CoreBndr] -> Int
521 valBndrCount (b : bs) | isId b = 1 + valBndrCount bs
522 | otherwise = valBndrCount bs
524 valArgCount :: [Arg b] -> Int
526 valArgCount (Type _ : args) = valArgCount args
527 valArgCount (other : args) = 1 + valArgCount args
531 %************************************************************************
533 \subsection{Seq stuff}
535 %************************************************************************
538 seqExpr :: CoreExpr -> ()
539 seqExpr (Var v) = v `seq` ()
540 seqExpr (Lit lit) = lit `seq` ()
541 seqExpr (App f a) = seqExpr f `seq` seqExpr a
542 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
543 seqExpr (Let b e) = seqBind b `seq` seqExpr e
544 seqExpr (Case e b as) = seqExpr e `seq` seqBndr b `seq` seqAlts as
545 seqExpr (Note n e) = seqNote n `seq` seqExpr e
546 seqExpr (Type t) = seqType t
549 seqExprs (e:es) = seqExpr e `seq` seqExprs es
551 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
554 seqBndr b = b `seq` ()
557 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
559 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
560 seqBind (Rec prs) = seqPairs prs
563 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
566 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
568 seqRules :: CoreRules -> ()
569 seqRules (Rules rules fvs) = seq_rules rules `seq` seqVarSet fvs
572 seq_rules (Rule fs _ bs es e : rules) = seqBndrs bs `seq` seqExprs (e:es) `seq` seq_rules rules
573 seq_rules (BuiltinRule _ _ : rules) = seq_rules rules
578 %************************************************************************
580 \subsection{Annotated core; annotation at every node in the tree}
582 %************************************************************************
585 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
587 data AnnExpr' bndr annot
590 | AnnLam bndr (AnnExpr bndr annot)
591 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
592 | AnnCase (AnnExpr bndr annot) bndr [AnnAlt bndr annot]
593 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
594 | AnnNote Note (AnnExpr bndr annot)
597 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
599 data AnnBind bndr annot
600 = AnnNonRec bndr (AnnExpr bndr annot)
601 | AnnRec [(bndr, AnnExpr bndr annot)]
605 deAnnotate :: AnnExpr bndr annot -> Expr bndr
606 deAnnotate (_, e) = deAnnotate' e
608 deAnnotate' (AnnType t) = Type t
609 deAnnotate' (AnnVar v) = Var v
610 deAnnotate' (AnnLit lit) = Lit lit
611 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
612 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
613 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
615 deAnnotate' (AnnLet bind body)
616 = Let (deAnnBind bind) (deAnnotate body)
618 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
619 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
621 deAnnotate' (AnnCase scrut v alts)
622 = Case (deAnnotate scrut) v (map deAnnAlt alts)
624 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
625 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
629 collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
633 collect bs (_, AnnLam b body) = collect (b:bs) body
634 collect bs body = (reverse bs, body)