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,
18 isTyVar, isId, cmpAltCon, cmpAlt, ltAlt,
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, evaldUnfolding, mkOtherCon,
30 unfoldingTemplate, maybeUnfoldingTemplate, otherCons,
31 isValueUnfolding, isEvaldUnfolding, isCheapUnfolding, isCompulsoryUnfolding,
32 hasUnfolding, hasSomeUnfolding, neverUnfold,
35 seqExpr, seqExprs, seqUnfolding,
37 -- Annotated expressions
38 AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt,
39 deAnnotate, deAnnotate', deAnnAlt, collectAnnBndrs,
42 CoreRule(..), -- CoreSubst, CoreTidy, CoreFVs, PprCore only
44 isBuiltinRule, ruleName, isLocalRule, ruleIdName
47 #include "HsVersions.h"
49 import StaticFlags ( opt_RuntimeTypes )
50 import CostCentre ( CostCentre, noCostCentre )
51 import Var ( Var, Id, TyVar, isTyVar, isId )
52 import Type ( Type, mkTyVarTy, seqType )
54 import OccName ( OccName )
55 import Literal ( Literal, mkMachInt )
56 import DataCon ( DataCon, dataConWorkId, dataConTag )
57 import BasicTypes ( Activation )
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 Type [Alt b] -- Binder gets bound to value of scrutinee
80 -- Invariant: The list of alternatives is ALWAYS EXHAUSTIVE,
81 -- meaning that it covers all cases that can occur
82 -- See the example below
84 -- Invariant: The DEFAULT case must be *first*, if it occurs at all
85 -- Invariant: The remaining cases are in order of increasing
88 -- This makes finding the relevant constructor easy,
89 -- and makes comparison easier too
91 | Type Type -- This should only show up at the top
94 -- An "exhausive" case does not necessarily mention all constructors:
95 -- data Foo = Red | Green | Blue
99 -- other -> f (case x of
102 -- The inner case does not need a Red alternative, because x can't be Red at
103 -- that program point.
106 type Arg b = Expr b -- Can be a Type
108 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
110 data AltCon = DataAlt DataCon
116 data Bind b = NonRec b (Expr b)
117 | Rec [(b, (Expr b))]
123 Type -- The to-type: type of whole coerce expression
124 Type -- The from-type: type of enclosed expression
126 | InlineCall -- Instructs simplifier to inline
129 | InlineMe -- Instructs simplifer to treat the enclosed expression
130 -- as very small, and inline it at its call sites
132 | CoreNote String -- A generic core annotation, propagated but not used by GHC
134 -- NOTE: we also treat expressions wrapped in InlineMe as
135 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
136 -- What this means is that we obediently inline even things that don't
137 -- look like valuse. This is sometimes important:
140 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
141 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
142 -- should inline f even inside lambdas. In effect, we should trust the programmer.
147 * The RHS of a letrec, and the RHSs of all top-level lets,
148 must be of LIFTED type.
150 * The RHS of a let, may be of UNLIFTED type, but only if the expression
151 is ok-for-speculation. This means that the let can be floated around
152 without difficulty. e.g.
154 y::Int# = fac 4# not ok [use case instead]
156 * The argument of an App can be of any type.
158 * The simplifier tries to ensure that if the RHS of a let is a constructor
159 application, its arguments are trivial, so that the constructor can be
163 %************************************************************************
165 \subsection{Transformation rules}
167 %************************************************************************
169 The CoreRule type and its friends are dealt with mainly in CoreRules,
170 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
174 "local" if the function it is a rule for is defined in the
175 same module as the rule itself.
177 "orphan" if nothing on the LHS is defined in the same module
181 type RuleName = FastString
186 ru_act :: Activation, -- When the rule is active
188 -- Rough-matching stuff
189 -- see comments with InstEnv.Instance( is_cls, is_rough )
190 ru_fn :: Name, -- Name of the Id at the head of this rule
191 ru_rough :: [Maybe Name], -- Name at the head of each argument
193 -- Proper-matching stuff
194 -- see comments with InstEnv.Instance( is_tvs, is_tys )
195 ru_bndrs :: [CoreBndr], -- Forall'd variables
196 ru_args :: [CoreExpr], -- LHS args
198 -- And the right-hand side
202 ru_local :: Bool, -- The fn at the head of the rule is
203 -- defined in the same module as the rule
205 -- Orphan-hood; see comments is InstEnv.Instance( is_orph )
206 ru_orph :: Maybe OccName }
208 | BuiltinRule { -- Built-in rules are used for constant folding
209 ru_name :: RuleName, -- and suchlike. It has no free variables.
210 ru_fn :: Name, -- Name of the Id at
211 -- the head of this rule
212 ru_try :: [CoreExpr] -> Maybe CoreExpr }
214 isBuiltinRule (BuiltinRule {}) = True
215 isBuiltinRule _ = False
217 ruleName :: CoreRule -> RuleName
220 ruleIdName :: CoreRule -> Name
223 isLocalRule :: CoreRule -> Bool
224 isLocalRule = ru_local
228 %************************************************************************
232 %************************************************************************
234 The @Unfolding@ type is declared here to avoid numerous loops, but it
235 should be abstract everywhere except in CoreUnfold.lhs
241 | OtherCon [AltCon] -- It ain't one of these
242 -- (OtherCon xs) also indicates that something has been evaluated
243 -- and hence there's no point in re-evaluating it.
244 -- OtherCon [] is used even for non-data-type values
245 -- to indicated evaluated-ness. Notably:
246 -- data C = C !(Int -> Int)
247 -- case x of { C f -> ... }
248 -- Here, f gets an OtherCon [] unfolding.
250 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
251 -- so you'd better unfold.
253 | CoreUnfolding -- An unfolding with redundant cached information
254 CoreExpr -- Template; binder-info is correct
255 Bool -- True <=> top level binding
256 Bool -- exprIsHNF template (cached); it is ok to discard a `seq` on
258 Bool -- True <=> doesn't waste (much) work to expand inside an inlining
259 -- Basically it's exprIsCheap
260 UnfoldingGuidance -- Tells about the *size* of the template.
263 data UnfoldingGuidance
265 | UnfoldIfGoodArgs Int -- and "n" value args
267 [Int] -- Discount if the argument is evaluated.
268 -- (i.e., a simplification will definitely
269 -- be possible). One elt of the list per *value* arg.
271 Int -- The "size" of the unfolding; to be elaborated
274 Int -- Scrutinee discount: the discount to substract if the thing is in
275 -- a context (case (thing args) of ...),
276 -- (where there are the right number of arguments.)
278 noUnfolding = NoUnfolding
279 evaldUnfolding = OtherCon []
281 mkOtherCon = OtherCon
283 seqUnfolding :: Unfolding -> ()
284 seqUnfolding (CoreUnfolding e top b1 b2 g)
285 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
286 seqUnfolding other = ()
288 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
289 seqGuidance other = ()
293 unfoldingTemplate :: Unfolding -> CoreExpr
294 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
295 unfoldingTemplate (CompulsoryUnfolding expr) = expr
296 unfoldingTemplate other = panic "getUnfoldingTemplate"
298 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
299 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
300 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
301 maybeUnfoldingTemplate other = Nothing
303 otherCons :: Unfolding -> [AltCon]
304 otherCons (OtherCon cons) = cons
307 isValueUnfolding :: Unfolding -> Bool
308 -- Returns False for OtherCon
309 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
310 isValueUnfolding other = False
312 isEvaldUnfolding :: Unfolding -> Bool
313 -- Returns True for OtherCon
314 isEvaldUnfolding (OtherCon _) = True
315 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
316 isEvaldUnfolding other = False
318 isCheapUnfolding :: Unfolding -> Bool
319 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
320 isCheapUnfolding other = False
322 isCompulsoryUnfolding :: Unfolding -> Bool
323 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
324 isCompulsoryUnfolding other = False
326 hasUnfolding :: Unfolding -> Bool
327 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
328 hasUnfolding (CompulsoryUnfolding _) = True
329 hasUnfolding other = False
331 hasSomeUnfolding :: Unfolding -> Bool
332 hasSomeUnfolding NoUnfolding = False
333 hasSomeUnfolding other = True
335 neverUnfold :: Unfolding -> Bool
336 neverUnfold NoUnfolding = True
337 neverUnfold (OtherCon _) = True
338 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
339 neverUnfold other = False
343 %************************************************************************
345 \subsection{The main data type}
347 %************************************************************************
350 -- The Ord is needed for the FiniteMap used in the lookForConstructor
351 -- in SimplEnv. If you declared that lookForConstructor *ignores*
352 -- constructor-applications with LitArg args, then you could get
355 instance Outputable AltCon where
356 ppr (DataAlt dc) = ppr dc
357 ppr (LitAlt lit) = ppr lit
358 ppr DEFAULT = ptext SLIT("__DEFAULT")
360 instance Show AltCon where
361 showsPrec p con = showsPrecSDoc p (ppr con)
363 cmpAlt :: Alt b -> Alt b -> Ordering
364 cmpAlt (con1, _, _) (con2, _, _) = con1 `cmpAltCon` con2
366 ltAlt :: Alt b -> Alt b -> Bool
367 ltAlt a1 a2 = case a1 `cmpAlt` a2 of { LT -> True; other -> False }
369 cmpAltCon :: AltCon -> AltCon -> Ordering
370 -- Compares AltCons within a single list of alternatives
371 cmpAltCon DEFAULT DEFAULT = EQ
372 cmpAltCon DEFAULT con = LT
374 cmpAltCon (DataAlt d1) (DataAlt d2) = dataConTag d1 `compare` dataConTag d2
375 cmpAltCon (DataAlt _) DEFAULT = GT
376 cmpAltCon (LitAlt l1) (LitAlt l2) = l1 `compare` l2
377 cmpAltCon (LitAlt _) DEFAULT = GT
379 cmpAltCon con1 con2 = WARN( True, text "Comparing incomparable AltCons" <+>
380 ppr con1 <+> ppr con2 )
385 %************************************************************************
387 \subsection{Useful synonyms}
389 %************************************************************************
395 type CoreExpr = Expr CoreBndr
396 type CoreArg = Arg CoreBndr
397 type CoreBind = Bind CoreBndr
398 type CoreAlt = Alt CoreBndr
401 Binders are ``tagged'' with a \tr{t}:
404 data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder"
406 type TaggedBind t = Bind (TaggedBndr t)
407 type TaggedExpr t = Expr (TaggedBndr t)
408 type TaggedArg t = Arg (TaggedBndr t)
409 type TaggedAlt t = Alt (TaggedBndr t)
411 instance Outputable b => Outputable (TaggedBndr b) where
412 ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
414 instance Outputable b => OutputableBndr (TaggedBndr b) where
415 pprBndr _ b = ppr b -- Simple
419 %************************************************************************
421 \subsection{Core-constructing functions with checking}
423 %************************************************************************
426 mkApps :: Expr b -> [Arg b] -> Expr b
427 mkTyApps :: Expr b -> [Type] -> Expr b
428 mkValApps :: Expr b -> [Expr b] -> Expr b
429 mkVarApps :: Expr b -> [Var] -> Expr b
431 mkApps f args = foldl App f args
432 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
433 mkValApps f args = foldl (\ e a -> App e a) f args
434 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
436 mkLit :: Literal -> Expr b
437 mkIntLit :: Integer -> Expr b
438 mkIntLitInt :: Int -> Expr b
439 mkConApp :: DataCon -> [Arg b] -> Expr b
440 mkLets :: [Bind b] -> Expr b -> Expr b
441 mkLams :: [b] -> Expr b -> Expr b
444 mkConApp con args = mkApps (Var (dataConWorkId con)) args
446 mkLams binders body = foldr Lam body binders
447 mkLets binds body = foldr Let body binds
449 mkIntLit n = Lit (mkMachInt n)
450 mkIntLitInt n = Lit (mkMachInt (toInteger n))
452 varToCoreExpr :: CoreBndr -> Expr b
453 varToCoreExpr v | isId v = Var v
454 | otherwise = Type (mkTyVarTy v)
458 %************************************************************************
460 \subsection{Simple access functions}
462 %************************************************************************
465 bindersOf :: Bind b -> [b]
466 bindersOf (NonRec binder _) = [binder]
467 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
469 bindersOfBinds :: [Bind b] -> [b]
470 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
472 rhssOfBind :: Bind b -> [Expr b]
473 rhssOfBind (NonRec _ rhs) = [rhs]
474 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
476 rhssOfAlts :: [Alt b] -> [Expr b]
477 rhssOfAlts alts = [e | (_,_,e) <- alts]
479 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
480 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
481 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
485 We often want to strip off leading lambdas before getting down to
486 business. @collectBinders@ is your friend.
488 We expect (by convention) type-, and value- lambdas in that
492 collectBinders :: Expr b -> ([b], Expr b)
493 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
494 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
495 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
500 go bs (Lam b e) = go (b:bs) e
501 go bs e = (reverse bs, e)
503 collectTyAndValBinders expr
506 (tvs, body1) = collectTyBinders expr
507 (ids, body) = collectValBinders body1
509 collectTyBinders expr
512 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
513 go tvs e = (reverse tvs, e)
515 collectValBinders expr
518 go ids (Lam b e) | isId b = go (b:ids) e
519 go ids body = (reverse ids, body)
523 @collectArgs@ takes an application expression, returning the function
524 and the arguments to which it is applied.
527 collectArgs :: Expr b -> (Expr b, [Arg b])
531 go (App f a) as = go f (a:as)
535 coreExprCc gets the cost centre enclosing an expression, if any.
536 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
539 coreExprCc :: Expr b -> CostCentre
540 coreExprCc (Note (SCC cc) e) = cc
541 coreExprCc (Note other_note e) = coreExprCc e
542 coreExprCc (Lam _ e) = coreExprCc e
543 coreExprCc other = noCostCentre
548 %************************************************************************
550 \subsection{Predicates}
552 %************************************************************************
554 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
555 i.e. if type applications are actual lambdas because types are kept around
558 Similarly isRuntimeArg.
561 isRuntimeVar :: Var -> Bool
562 isRuntimeVar | opt_RuntimeTypes = \v -> True
563 | otherwise = \v -> isId v
565 isRuntimeArg :: CoreExpr -> Bool
566 isRuntimeArg | opt_RuntimeTypes = \e -> True
567 | otherwise = \e -> isValArg e
571 isValArg (Type _) = False
572 isValArg other = True
574 isTypeArg (Type _) = True
575 isTypeArg other = False
577 valBndrCount :: [CoreBndr] -> Int
579 valBndrCount (b : bs) | isId b = 1 + valBndrCount bs
580 | otherwise = valBndrCount bs
582 valArgCount :: [Arg b] -> Int
584 valArgCount (Type _ : args) = valArgCount args
585 valArgCount (other : args) = 1 + valArgCount args
589 %************************************************************************
591 \subsection{Seq stuff}
593 %************************************************************************
596 seqExpr :: CoreExpr -> ()
597 seqExpr (Var v) = v `seq` ()
598 seqExpr (Lit lit) = lit `seq` ()
599 seqExpr (App f a) = seqExpr f `seq` seqExpr a
600 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
601 seqExpr (Let b e) = seqBind b `seq` seqExpr e
603 seqExpr (Case e b t as) = seqExpr e `seq` seqBndr b `seq` seqType t `seq` seqAlts as
604 seqExpr (Note n e) = seqNote n `seq` seqExpr e
605 seqExpr (Type t) = seqType t
608 seqExprs (e:es) = seqExpr e `seq` seqExprs es
610 seqNote (Coerce t1 t2) = seqType t1 `seq` seqType t2
611 seqNote (CoreNote s) = s `seq` ()
614 seqBndr b = b `seq` ()
617 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
619 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
620 seqBind (Rec prs) = seqPairs prs
623 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
626 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
629 seqRules (Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs } : rules)
630 = seqBndrs bndrs `seq` seqExprs (rhs:args) `seq` seqRules rules
631 seqRules (BuiltinRule {} : rules) = seqRules rules
636 %************************************************************************
638 \subsection{Annotated core; annotation at every node in the tree}
640 %************************************************************************
643 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
645 data AnnExpr' bndr annot
648 | AnnLam bndr (AnnExpr bndr annot)
649 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
651 | AnnCase (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot]
652 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
653 | AnnNote Note (AnnExpr bndr annot)
656 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
658 data AnnBind bndr annot
659 = AnnNonRec bndr (AnnExpr bndr annot)
660 | AnnRec [(bndr, AnnExpr bndr annot)]
664 deAnnotate :: AnnExpr bndr annot -> Expr bndr
665 deAnnotate (_, e) = deAnnotate' e
667 deAnnotate' (AnnType t) = Type t
668 deAnnotate' (AnnVar v) = Var v
669 deAnnotate' (AnnLit lit) = Lit lit
670 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
671 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
672 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
674 deAnnotate' (AnnLet bind body)
675 = Let (deAnnBind bind) (deAnnotate body)
677 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
678 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
681 deAnnotate' (AnnCase scrut v t alts)
682 = Case (deAnnotate scrut) v t (map deAnnAlt alts)
684 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
685 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
689 collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
693 collect bs (_, AnnLam b body) = collect (b:bs) body
694 collect bs body = (reverse bs, body)