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,
16 varToCoreExpr, varsToCoreExprs,
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 )
53 import Coercion ( Coercion )
55 import OccName ( OccName )
56 import Literal ( Literal, mkMachInt )
57 import DataCon ( DataCon, dataConWorkId, dataConTag )
58 import BasicTypes ( Activation )
62 infixl 4 `mkApps`, `mkValApps`, `mkTyApps`, `mkVarApps`
63 -- Left associative, so that we can say (f `mkTyApps` xs `mkVarApps` ys)
66 %************************************************************************
68 \subsection{The main data types}
70 %************************************************************************
72 These data types are the heart of the compiler
75 infixl 8 `App` -- App brackets to the left
77 data Expr b -- "b" for the type of binders,
80 | App (Expr b) (Arg b)
82 | Let (Bind b) (Expr b)
83 | Case (Expr b) b Type [Alt b] -- Binder gets bound to value of scrutinee
84 -- Invariant: The list of alternatives is ALWAYS EXHAUSTIVE,
85 -- meaning that it covers all cases that can occur
86 -- See the example below
88 -- Invariant: The DEFAULT case must be *first*, if it occurs at all
89 -- Invariant: The remaining cases are in order of increasing
92 -- This makes finding the relevant constructor easy,
93 -- and makes comparison easier too
94 | Cast (Expr b) Coercion
96 | Type Type -- This should only show up at the top
99 -- An "exhausive" case does not necessarily mention all constructors:
100 -- data Foo = Red | Green | Blue
104 -- other -> f (case x of
107 -- The inner case does not need a Red alternative, because x can't be Red at
108 -- that program point.
111 type Arg b = Expr b -- Can be a Type
113 type Alt b = (AltCon, [b], Expr b) -- (DEFAULT, [], rhs) is the default alternative
115 data AltCon = DataAlt DataCon
121 data Bind b = NonRec b (Expr b)
122 | Rec [(b, (Expr b))]
127 | InlineMe -- Instructs simplifer to treat the enclosed expression
128 -- as very small, and inline it at its call sites
130 | CoreNote String -- A generic core annotation, propagated but not used by GHC
132 -- NOTE: we also treat expressions wrapped in InlineMe as
133 -- 'cheap' and 'dupable' (in the sense of exprIsCheap, exprIsDupable)
134 -- What this means is that we obediently inline even things that don't
135 -- look like valuse. This is sometimes important:
138 -- Here, f looks like a redex, and we aren't going to inline (.) because it's
139 -- inside an INLINE, so it'll stay looking like a redex. Nevertheless, we
140 -- should inline f even inside lambdas. In effect, we should trust the programmer.
145 * The RHS of a letrec, and the RHSs of all top-level lets,
146 must be of LIFTED type.
148 * The RHS of a let, may be of UNLIFTED type, but only if the expression
149 is ok-for-speculation. This means that the let can be floated around
150 without difficulty. e.g.
152 y::Int# = fac 4# not ok [use case instead]
154 * The argument of an App can be of any type.
156 * The simplifier tries to ensure that if the RHS of a let is a constructor
157 application, its arguments are trivial, so that the constructor can be
161 %************************************************************************
163 \subsection{Transformation rules}
165 %************************************************************************
167 The CoreRule type and its friends are dealt with mainly in CoreRules,
168 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
172 "local" if the function it is a rule for is defined in the
173 same module as the rule itself.
175 "orphan" if nothing on the LHS is defined in the same module
179 type RuleName = FastString
184 ru_act :: Activation, -- When the rule is active
186 -- Rough-matching stuff
187 -- see comments with InstEnv.Instance( is_cls, is_rough )
188 ru_fn :: Name, -- Name of the Id at the head of this rule
189 ru_rough :: [Maybe Name], -- Name at the head of each argument
191 -- Proper-matching stuff
192 -- see comments with InstEnv.Instance( is_tvs, is_tys )
193 ru_bndrs :: [CoreBndr], -- Forall'd variables
194 ru_args :: [CoreExpr], -- LHS args
196 -- And the right-hand side
200 ru_local :: Bool, -- The fn at the head of the rule is
201 -- defined in the same module as the rule
203 -- Orphan-hood; see comments is InstEnv.Instance( is_orph )
204 ru_orph :: Maybe OccName }
206 | BuiltinRule { -- Built-in rules are used for constant folding
207 ru_name :: RuleName, -- and suchlike. It has no free variables.
208 ru_fn :: Name, -- Name of the Id at
209 -- the head of this rule
210 ru_try :: [CoreExpr] -> Maybe CoreExpr }
212 isBuiltinRule (BuiltinRule {}) = True
213 isBuiltinRule _ = False
215 ruleName :: CoreRule -> RuleName
218 ruleIdName :: CoreRule -> Name
221 isLocalRule :: CoreRule -> Bool
222 isLocalRule = ru_local
226 %************************************************************************
230 %************************************************************************
232 The @Unfolding@ type is declared here to avoid numerous loops, but it
233 should be abstract everywhere except in CoreUnfold.lhs
239 | OtherCon [AltCon] -- It ain't one of these
240 -- (OtherCon xs) also indicates that something has been evaluated
241 -- and hence there's no point in re-evaluating it.
242 -- OtherCon [] is used even for non-data-type values
243 -- to indicated evaluated-ness. Notably:
244 -- data C = C !(Int -> Int)
245 -- case x of { C f -> ... }
246 -- Here, f gets an OtherCon [] unfolding.
248 | CompulsoryUnfolding CoreExpr -- There is no "original" definition,
249 -- so you'd better unfold.
251 | CoreUnfolding -- An unfolding with redundant cached information
252 CoreExpr -- Template; binder-info is correct
253 Bool -- True <=> top level binding
254 Bool -- exprIsHNF template (cached); it is ok to discard a `seq` on
256 Bool -- True <=> doesn't waste (much) work to expand inside an inlining
257 -- Basically it's exprIsCheap
258 UnfoldingGuidance -- Tells about the *size* of the template.
261 data UnfoldingGuidance
263 | UnfoldIfGoodArgs Int -- and "n" value args
265 [Int] -- Discount if the argument is evaluated.
266 -- (i.e., a simplification will definitely
267 -- be possible). One elt of the list per *value* arg.
269 Int -- The "size" of the unfolding; to be elaborated
272 Int -- Scrutinee discount: the discount to substract if the thing is in
273 -- a context (case (thing args) of ...),
274 -- (where there are the right number of arguments.)
276 noUnfolding = NoUnfolding
277 evaldUnfolding = OtherCon []
279 mkOtherCon = OtherCon
281 seqUnfolding :: Unfolding -> ()
282 seqUnfolding (CoreUnfolding e top b1 b2 g)
283 = seqExpr e `seq` top `seq` b1 `seq` b2 `seq` seqGuidance g
284 seqUnfolding other = ()
286 seqGuidance (UnfoldIfGoodArgs n ns a b) = n `seq` sum ns `seq` a `seq` b `seq` ()
287 seqGuidance other = ()
291 unfoldingTemplate :: Unfolding -> CoreExpr
292 unfoldingTemplate (CoreUnfolding expr _ _ _ _) = expr
293 unfoldingTemplate (CompulsoryUnfolding expr) = expr
294 unfoldingTemplate other = panic "getUnfoldingTemplate"
296 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
297 maybeUnfoldingTemplate (CoreUnfolding expr _ _ _ _) = Just expr
298 maybeUnfoldingTemplate (CompulsoryUnfolding expr) = Just expr
299 maybeUnfoldingTemplate other = Nothing
301 otherCons :: Unfolding -> [AltCon]
302 otherCons (OtherCon cons) = cons
305 isValueUnfolding :: Unfolding -> Bool
306 -- Returns False for OtherCon
307 isValueUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
308 isValueUnfolding other = False
310 isEvaldUnfolding :: Unfolding -> Bool
311 -- Returns True for OtherCon
312 isEvaldUnfolding (OtherCon _) = True
313 isEvaldUnfolding (CoreUnfolding _ _ is_evald _ _) = is_evald
314 isEvaldUnfolding other = False
316 isCheapUnfolding :: Unfolding -> Bool
317 isCheapUnfolding (CoreUnfolding _ _ _ is_cheap _) = is_cheap
318 isCheapUnfolding other = False
320 isCompulsoryUnfolding :: Unfolding -> Bool
321 isCompulsoryUnfolding (CompulsoryUnfolding _) = True
322 isCompulsoryUnfolding other = False
324 hasUnfolding :: Unfolding -> Bool
325 hasUnfolding (CoreUnfolding _ _ _ _ _) = True
326 hasUnfolding (CompulsoryUnfolding _) = True
327 hasUnfolding other = False
329 hasSomeUnfolding :: Unfolding -> Bool
330 hasSomeUnfolding NoUnfolding = False
331 hasSomeUnfolding other = True
333 neverUnfold :: Unfolding -> Bool
334 neverUnfold NoUnfolding = True
335 neverUnfold (OtherCon _) = True
336 neverUnfold (CoreUnfolding _ _ _ _ UnfoldNever) = True
337 neverUnfold other = False
341 %************************************************************************
343 \subsection{The main data type}
345 %************************************************************************
348 -- The Ord is needed for the FiniteMap used in the lookForConstructor
349 -- in SimplEnv. If you declared that lookForConstructor *ignores*
350 -- constructor-applications with LitArg args, then you could get
353 instance Outputable AltCon where
354 ppr (DataAlt dc) = ppr dc
355 ppr (LitAlt lit) = ppr lit
356 ppr DEFAULT = ptext SLIT("__DEFAULT")
358 instance Show AltCon where
359 showsPrec p con = showsPrecSDoc p (ppr con)
361 cmpAlt :: Alt b -> Alt b -> Ordering
362 cmpAlt (con1, _, _) (con2, _, _) = con1 `cmpAltCon` con2
364 ltAlt :: Alt b -> Alt b -> Bool
365 ltAlt a1 a2 = case a1 `cmpAlt` a2 of { LT -> True; other -> False }
367 cmpAltCon :: AltCon -> AltCon -> Ordering
368 -- Compares AltCons within a single list of alternatives
369 cmpAltCon DEFAULT DEFAULT = EQ
370 cmpAltCon DEFAULT con = LT
372 cmpAltCon (DataAlt d1) (DataAlt d2) = dataConTag d1 `compare` dataConTag d2
373 cmpAltCon (DataAlt _) DEFAULT = GT
374 cmpAltCon (LitAlt l1) (LitAlt l2) = l1 `compare` l2
375 cmpAltCon (LitAlt _) DEFAULT = GT
377 cmpAltCon con1 con2 = WARN( True, text "Comparing incomparable AltCons" <+>
378 ppr con1 <+> ppr con2 )
383 %************************************************************************
385 \subsection{Useful synonyms}
387 %************************************************************************
393 type CoreExpr = Expr CoreBndr
394 type CoreArg = Arg CoreBndr
395 type CoreBind = Bind CoreBndr
396 type CoreAlt = Alt CoreBndr
399 Binders are ``tagged'' with a \tr{t}:
402 data TaggedBndr t = TB CoreBndr t -- TB for "tagged binder"
404 type TaggedBind t = Bind (TaggedBndr t)
405 type TaggedExpr t = Expr (TaggedBndr t)
406 type TaggedArg t = Arg (TaggedBndr t)
407 type TaggedAlt t = Alt (TaggedBndr t)
409 instance Outputable b => Outputable (TaggedBndr b) where
410 ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
412 instance Outputable b => OutputableBndr (TaggedBndr b) where
413 pprBndr _ b = ppr b -- Simple
417 %************************************************************************
419 \subsection{Core-constructing functions with checking}
421 %************************************************************************
424 mkApps :: Expr b -> [Arg b] -> Expr b
425 mkTyApps :: Expr b -> [Type] -> Expr b
426 mkValApps :: Expr b -> [Expr b] -> Expr b
427 mkVarApps :: Expr b -> [Var] -> Expr b
429 mkApps f args = foldl App f args
430 mkTyApps f args = foldl (\ e a -> App e (Type a)) f args
431 mkValApps f args = foldl (\ e a -> App e a) f args
432 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
434 mkLit :: Literal -> Expr b
435 mkIntLit :: Integer -> Expr b
436 mkIntLitInt :: Int -> Expr b
437 mkConApp :: DataCon -> [Arg b] -> Expr b
438 mkLets :: [Bind b] -> Expr b -> Expr b
439 mkLams :: [b] -> Expr b -> Expr b
442 mkConApp con args = pprTrace "mkConApp" (ppr con) $ mkApps (Var (dataConWorkId con)) args
444 mkLams binders body = foldr Lam body binders
445 mkLets binds body = foldr Let body binds
447 mkIntLit n = Lit (mkMachInt n)
448 mkIntLitInt n = Lit (mkMachInt (toInteger n))
450 varToCoreExpr :: CoreBndr -> Expr b
451 varToCoreExpr v | isId v = Var v
452 | otherwise = Type (mkTyVarTy v)
454 varsToCoreExprs :: [CoreBndr] -> [Expr b]
455 varsToCoreExprs vs = map varToCoreExpr vs
457 mkCast :: Expr b -> Coercion -> Expr b
458 mkCast e co = Cast e co
462 %************************************************************************
464 \subsection{Simple access functions}
466 %************************************************************************
469 bindersOf :: Bind b -> [b]
470 bindersOf (NonRec binder _) = [binder]
471 bindersOf (Rec pairs) = [binder | (binder, _) <- pairs]
473 bindersOfBinds :: [Bind b] -> [b]
474 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
476 rhssOfBind :: Bind b -> [Expr b]
477 rhssOfBind (NonRec _ rhs) = [rhs]
478 rhssOfBind (Rec pairs) = [rhs | (_,rhs) <- pairs]
480 rhssOfAlts :: [Alt b] -> [Expr b]
481 rhssOfAlts alts = [e | (_,_,e) <- alts]
483 flattenBinds :: [Bind b] -> [(b, Expr b)] -- Get all the lhs/rhs pairs
484 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
485 flattenBinds (Rec prs1 : binds) = prs1 ++ flattenBinds binds
489 We often want to strip off leading lambdas before getting down to
490 business. @collectBinders@ is your friend.
492 We expect (by convention) type-, and value- lambdas in that
496 collectBinders :: Expr b -> ([b], Expr b)
497 collectTyBinders :: CoreExpr -> ([TyVar], CoreExpr)
498 collectValBinders :: CoreExpr -> ([Id], CoreExpr)
499 collectTyAndValBinders :: CoreExpr -> ([TyVar], [Id], CoreExpr)
504 go bs (Lam b e) = go (b:bs) e
505 go bs e = (reverse bs, e)
507 collectTyAndValBinders expr
510 (tvs, body1) = collectTyBinders expr
511 (ids, body) = collectValBinders body1
513 collectTyBinders expr
516 go tvs (Lam b e) | isTyVar b = go (b:tvs) e
517 go tvs e = (reverse tvs, e)
519 collectValBinders expr
522 go ids (Lam b e) | isId b = go (b:ids) e
523 go ids body = (reverse ids, body)
527 @collectArgs@ takes an application expression, returning the function
528 and the arguments to which it is applied.
531 collectArgs :: Expr b -> (Expr b, [Arg b])
535 go (App f a) as = go f (a:as)
539 coreExprCc gets the cost centre enclosing an expression, if any.
540 It looks inside lambdas because (scc "foo" \x.e) = \x.scc "foo" e
543 coreExprCc :: Expr b -> CostCentre
544 coreExprCc (Note (SCC cc) e) = cc
545 coreExprCc (Note other_note e) = coreExprCc e
546 coreExprCc (Lam _ e) = coreExprCc e
547 coreExprCc other = noCostCentre
552 %************************************************************************
554 \subsection{Predicates}
556 %************************************************************************
558 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
559 i.e. if type applications are actual lambdas because types are kept around
562 Similarly isRuntimeArg.
565 isRuntimeVar :: Var -> Bool
566 isRuntimeVar | opt_RuntimeTypes = \v -> True
567 | otherwise = \v -> isId v
569 isRuntimeArg :: CoreExpr -> Bool
570 isRuntimeArg | opt_RuntimeTypes = \e -> True
571 | otherwise = \e -> isValArg e
575 isValArg (Type _) = False
576 isValArg other = True
578 isTypeArg (Type _) = True
579 isTypeArg other = False
581 valBndrCount :: [CoreBndr] -> Int
583 valBndrCount (b : bs) | isId b = 1 + valBndrCount bs
584 | otherwise = valBndrCount bs
586 valArgCount :: [Arg b] -> Int
588 valArgCount (Type _ : args) = valArgCount args
589 valArgCount (other : args) = 1 + valArgCount args
593 %************************************************************************
595 \subsection{Seq stuff}
597 %************************************************************************
600 seqExpr :: CoreExpr -> ()
601 seqExpr (Var v) = v `seq` ()
602 seqExpr (Lit lit) = lit `seq` ()
603 seqExpr (App f a) = seqExpr f `seq` seqExpr a
604 seqExpr (Lam b e) = seqBndr b `seq` seqExpr e
605 seqExpr (Let b e) = seqBind b `seq` seqExpr e
607 seqExpr (Case e b t as) = seqExpr e `seq` seqBndr b `seq` seqType t `seq` seqAlts as
608 seqExpr (Cast e co) = seqExpr e `seq` seqType co
609 seqExpr (Note n e) = seqNote n `seq` seqExpr e
610 seqExpr (Type t) = seqType t
613 seqExprs (e:es) = seqExpr e `seq` seqExprs es
615 seqNote (CoreNote s) = s `seq` ()
618 seqBndr b = b `seq` ()
621 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
623 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
624 seqBind (Rec prs) = seqPairs prs
627 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
630 seqAlts ((c,bs,e):alts) = seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
633 seqRules (Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs } : rules)
634 = seqBndrs bndrs `seq` seqExprs (rhs:args) `seq` seqRules rules
635 seqRules (BuiltinRule {} : rules) = seqRules rules
640 %************************************************************************
642 \subsection{Annotated core; annotation at every node in the tree}
644 %************************************************************************
647 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
649 data AnnExpr' bndr annot
652 | AnnLam bndr (AnnExpr bndr annot)
653 | AnnApp (AnnExpr bndr annot) (AnnExpr bndr annot)
655 | AnnCase (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot]
656 | AnnLet (AnnBind bndr annot) (AnnExpr bndr annot)
657 | AnnCast (AnnExpr bndr annot) Coercion
658 | AnnNote Note (AnnExpr bndr annot)
661 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
663 data AnnBind bndr annot
664 = AnnNonRec bndr (AnnExpr bndr annot)
665 | AnnRec [(bndr, AnnExpr bndr annot)]
669 deAnnotate :: AnnExpr bndr annot -> Expr bndr
670 deAnnotate (_, e) = deAnnotate' e
672 deAnnotate' (AnnType t) = Type t
673 deAnnotate' (AnnVar v) = Var v
674 deAnnotate' (AnnLit lit) = Lit lit
675 deAnnotate' (AnnLam binder body) = Lam binder (deAnnotate body)
676 deAnnotate' (AnnApp fun arg) = App (deAnnotate fun) (deAnnotate arg)
677 deAnnotate' (AnnCast e co) = Cast (deAnnotate e) co
678 deAnnotate' (AnnNote note body) = Note note (deAnnotate body)
680 deAnnotate' (AnnLet bind body)
681 = Let (deAnnBind bind) (deAnnotate body)
683 deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
684 deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
687 deAnnotate' (AnnCase scrut v t alts)
688 = Case (deAnnotate scrut) v t (map deAnnAlt alts)
690 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
691 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
695 collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
699 collect bs (_, AnnLam b body) = collect (b:bs) body
700 collect bs body = (reverse bs, body)