2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[CoreUtils]{Utility functions on @Core@ syntax}
9 mkNote, mkInlineMe, mkSCC, mkCoerce,
10 bindNonRec, mkIfThenElse, mkAltExpr,
13 -- Taking expressions apart
16 -- Properties of expressions
17 exprType, coreAltsType,
18 exprIsBottom, exprIsDupable, exprIsTrivial, exprIsCheap,
19 exprIsValue,exprOkForSpeculation, exprIsBig,
20 exprIsConApp_maybe, exprIsAtom,
21 idAppIsBottom, idAppIsCheap,
24 -- Expr transformation
26 exprArity, exprEtaExpandArity,
35 cheapEqExpr, eqExpr, applyTypeToArgs
38 #include "HsVersions.h"
41 import GlaExts -- For `xori`
44 import CoreFVs ( exprFreeVars )
45 import PprCore ( pprCoreExpr )
46 import Var ( Var, isId, isTyVar )
49 import Name ( hashName )
50 import Literal ( hashLiteral, literalType, litIsDupable )
51 import DataCon ( DataCon, dataConRepArity )
52 import PrimOp ( primOpOkForSpeculation, primOpIsCheap,
54 import Id ( Id, idType, globalIdDetails, idStrictness, idLBVarInfo,
55 mkWildId, idArity, idName, idUnfolding, idInfo, isOneShotLambda,
56 isDataConId_maybe, isPrimOpId_maybe, mkSysLocal, hasNoBinding
58 import IdInfo ( LBVarInfo(..),
61 import Demand ( appIsBottom )
62 import Type ( Type, mkFunTy, mkForAllTy, splitFunTy_maybe,
63 applyTys, isUnLiftedType, seqType, mkUTy, mkTyVarTy,
64 splitForAllTy_maybe, splitNewType_maybe
66 import TysWiredIn ( boolTy, trueDataCon, falseDataCon )
67 import CostCentre ( CostCentre )
68 import UniqSupply ( UniqSupply, splitUniqSupply, uniqFromSupply )
69 import Maybes ( maybeToBool )
71 import TysPrim ( alphaTy ) -- Debugging only
75 %************************************************************************
77 \subsection{Find the type of a Core atom/expression}
79 %************************************************************************
82 exprType :: CoreExpr -> Type
84 exprType (Var var) = idType var
85 exprType (Lit lit) = literalType lit
86 exprType (Let _ body) = exprType body
87 exprType (Case _ _ alts) = coreAltsType alts
88 exprType (Note (Coerce ty _) e) = ty -- **! should take usage from e
89 exprType (Note other_note e) = exprType e
90 exprType (Lam binder expr) = mkPiType binder (exprType expr)
92 = case collectArgs e of
93 (fun, args) -> applyTypeToArgs e (exprType fun) args
95 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
97 coreAltsType :: [CoreAlt] -> Type
98 coreAltsType ((_,_,rhs) : _) = exprType rhs
101 @mkPiType@ makes a (->) type or a forall type, depending on whether
102 it is given a type variable or a term variable. We cleverly use the
103 lbvarinfo field to figure out the right annotation for the arrove in
104 case of a term variable.
107 mkPiType :: Var -> Type -> Type -- The more polymorphic version doesn't work...
108 mkPiType v ty | isId v = (case idLBVarInfo v of
109 LBVarInfo u -> mkUTy u
111 mkFunTy (idType v) ty
112 | isTyVar v = mkForAllTy v ty
116 -- The first argument is just for debugging
117 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
118 applyTypeToArgs e op_ty [] = op_ty
120 applyTypeToArgs e op_ty (Type ty : args)
121 = -- Accumulate type arguments so we can instantiate all at once
122 applyTypeToArgs e (applyTys op_ty tys) rest_args
124 (tys, rest_args) = go [ty] args
125 go tys (Type ty : args) = go (ty:tys) args
126 go tys rest_args = (reverse tys, rest_args)
128 applyTypeToArgs e op_ty (other_arg : args)
129 = case (splitFunTy_maybe op_ty) of
130 Just (_, res_ty) -> applyTypeToArgs e res_ty args
131 Nothing -> pprPanic "applyTypeToArgs" (pprCoreExpr e)
136 %************************************************************************
138 \subsection{Attaching notes}
140 %************************************************************************
142 mkNote removes redundant coercions, and SCCs where possible
145 mkNote :: Note -> CoreExpr -> CoreExpr
146 mkNote (Coerce to_ty from_ty) expr = mkCoerce to_ty from_ty expr
147 mkNote (SCC cc) expr = mkSCC cc expr
148 mkNote InlineMe expr = mkInlineMe expr
149 mkNote note expr = Note note expr
151 -- Slide InlineCall in around the function
152 -- No longer necessary I think (SLPJ Apr 99)
153 -- mkNote InlineCall (App f a) = App (mkNote InlineCall f) a
154 -- mkNote InlineCall (Var v) = Note InlineCall (Var v)
155 -- mkNote InlineCall expr = expr
158 Drop trivial InlineMe's. This is somewhat important, because if we have an unfolding
159 that looks like (Note InlineMe (Var v)), the InlineMe doesn't go away because it may
160 not be *applied* to anything.
162 We don't use exprIsTrivial here, though, because we sometimes generate worker/wrapper
165 f = inline_me (coerce t fw)
166 As usual, the inline_me prevents the worker from getting inlined back into the wrapper.
167 We want the split, so that the coerces can cancel at the call site.
169 However, we can get left with tiresome type applications. Notably, consider
170 f = /\ a -> let t = e in (t, w)
171 Then lifting the let out of the big lambda gives
173 f = /\ a -> let t = inline_me (t' a) in (t, w)
174 The inline_me is to stop the simplifier inlining t' right back
175 into t's RHS. In the next phase we'll substitute for t (since
176 its rhs is trivial) and *then* we could get rid of the inline_me.
177 But it hardly seems worth it, so I don't bother.
180 mkInlineMe (Var v) = Var v
181 mkInlineMe e = Note InlineMe e
187 mkCoerce :: Type -> Type -> CoreExpr -> CoreExpr
189 mkCoerce to_ty from_ty (Note (Coerce to_ty2 from_ty2) expr)
190 = ASSERT( from_ty == to_ty2 )
191 mkCoerce to_ty from_ty2 expr
193 mkCoerce to_ty from_ty expr
194 | to_ty == from_ty = expr
195 | otherwise = ASSERT( from_ty == exprType expr )
196 Note (Coerce to_ty from_ty) expr
200 mkSCC :: CostCentre -> Expr b -> Expr b
201 -- Note: Nested SCC's *are* preserved for the benefit of
202 -- cost centre stack profiling (Durham)
204 mkSCC cc (Lit lit) = Lit lit
205 mkSCC cc (Lam x e) = Lam x (mkSCC cc e) -- Move _scc_ inside lambda
206 mkSCC cc expr = Note (SCC cc) expr
210 %************************************************************************
212 \subsection{Other expression construction}
214 %************************************************************************
217 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
218 -- (bindNonRec x r b) produces either
221 -- case r of x { _DEFAULT_ -> b }
223 -- depending on whether x is unlifted or not
224 -- It's used by the desugarer to avoid building bindings
225 -- that give Core Lint a heart attack. Actually the simplifier
226 -- deals with them perfectly well.
227 bindNonRec bndr rhs body
228 | isUnLiftedType (idType bndr) = Case rhs bndr [(DEFAULT,[],body)]
229 | otherwise = Let (NonRec bndr rhs) body
233 mkAltExpr :: AltCon -> [CoreBndr] -> [Type] -> CoreExpr
234 -- This guy constructs the value that the scrutinee must have
235 -- when you are in one particular branch of a case
236 mkAltExpr (DataAlt con) args inst_tys
237 = mkConApp con (map Type inst_tys ++ map varToCoreExpr args)
238 mkAltExpr (LitAlt lit) [] []
241 mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
242 mkIfThenElse guard then_expr else_expr
243 = Case guard (mkWildId boolTy)
244 [ (DataAlt trueDataCon, [], then_expr),
245 (DataAlt falseDataCon, [], else_expr) ]
249 %************************************************************************
251 \subsection{Taking expressions apart}
253 %************************************************************************
257 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
258 findDefault [] = ([], Nothing)
259 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null alts && null args )
261 findDefault (alt : alts) = case findDefault alts of
262 (alts', deflt) -> (alt : alts', deflt)
264 findAlt :: AltCon -> [CoreAlt] -> CoreAlt
268 go [] = pprPanic "Missing alternative" (ppr con $$ vcat (map ppr alts))
269 go (alt : alts) | matches alt = alt
270 | otherwise = go alts
272 matches (DEFAULT, _, _) = True
273 matches (con1, _, _) = con == con1
277 %************************************************************************
279 \subsection{Figuring out things about expressions}
281 %************************************************************************
283 @exprIsTrivial@ is true of expressions we are unconditionally happy to
284 duplicate; simple variables and constants, and type
285 applications. Note that primop Ids aren't considered
288 @exprIsBottom@ is true of expressions that are guaranteed to diverge
292 exprIsTrivial (Var v)
293 | hasNoBinding v = idArity v == 0
294 -- WAS: | Just op <- isPrimOpId_maybe v = primOpIsDupable op
295 -- The idea here is that a constructor worker, like $wJust, is
296 -- really short for (\x -> $wJust x), becuase $wJust has no binding.
297 -- So it should be treated like a lambda.
298 -- Ditto unsaturated primops.
299 -- This came up when dealing with eta expansion/reduction for
301 -- Here we want to eta-expand. This looks like an optimisation,
302 -- but it's important (albeit tiresome) that CoreSat doesn't increase
305 exprIsTrivial (Type _) = True
306 exprIsTrivial (Lit lit) = True
307 exprIsTrivial (App e arg) = isTypeArg arg && exprIsTrivial e
308 exprIsTrivial (Note _ e) = exprIsTrivial e
309 exprIsTrivial (Lam b body) | isTyVar b = exprIsTrivial body
310 exprIsTrivial other = False
312 exprIsAtom :: CoreExpr -> Bool
313 -- Used to decide whether to let-binding an STG argument
314 -- when compiling to ILX => type applications are not allowed
315 exprIsAtom (Var v) = True -- primOpIsDupable?
316 exprIsAtom (Lit lit) = True
317 exprIsAtom (Type ty) = True
318 exprIsAtom (Note (SCC _) e) = False
319 exprIsAtom (Note _ e) = exprIsAtom e
320 exprIsAtom other = False
324 @exprIsDupable@ is true of expressions that can be duplicated at a modest
325 cost in code size. This will only happen in different case
326 branches, so there's no issue about duplicating work.
328 That is, exprIsDupable returns True of (f x) even if
329 f is very very expensive to call.
331 Its only purpose is to avoid fruitless let-binding
332 and then inlining of case join points
336 exprIsDupable (Type _) = True
337 exprIsDupable (Var v) = True
338 exprIsDupable (Lit lit) = litIsDupable lit
339 exprIsDupable (Note InlineMe e) = True
340 exprIsDupable (Note _ e) = exprIsDupable e
344 go (Var v) n_args = True
345 go (App f a) n_args = n_args < dupAppSize
348 go other n_args = False
351 dupAppSize = 4 -- Size of application we are prepared to duplicate
354 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
355 it is obviously in weak head normal form, or is cheap to get to WHNF.
356 [Note that that's not the same as exprIsDupable; an expression might be
357 big, and hence not dupable, but still cheap.]
359 By ``cheap'' we mean a computation we're willing to:
360 push inside a lambda, or
361 inline at more than one place
362 That might mean it gets evaluated more than once, instead of being
363 shared. The main examples of things which aren't WHNF but are
368 (where e, and all the ei are cheap)
371 (where e and b are cheap)
374 (where op is a cheap primitive operator)
377 (because we are happy to substitute it inside a lambda)
379 Notice that a variable is considered 'cheap': we can push it inside a lambda,
380 because sharing will make sure it is only evaluated once.
383 exprIsCheap :: CoreExpr -> Bool
384 exprIsCheap (Lit lit) = True
385 exprIsCheap (Type _) = True
386 exprIsCheap (Var _) = True
387 exprIsCheap (Note InlineMe e) = True
388 exprIsCheap (Note _ e) = exprIsCheap e
389 exprIsCheap (Lam x e) = if isId x then True else exprIsCheap e
390 exprIsCheap (Case e _ alts) = exprIsCheap e &&
391 and [exprIsCheap rhs | (_,_,rhs) <- alts]
392 -- Experimentally, treat (case x of ...) as cheap
393 -- (and case __coerce x etc.)
394 -- This improves arities of overloaded functions where
395 -- there is only dictionary selection (no construction) involved
396 exprIsCheap (Let (NonRec x _) e)
397 | isUnLiftedType (idType x) = exprIsCheap e
399 -- strict lets always have cheap right hand sides, and
402 exprIsCheap other_expr
403 = go other_expr 0 True
405 go (Var f) n_args args_cheap
406 = (idAppIsCheap f n_args && args_cheap)
407 -- A constructor, cheap primop, or partial application
409 || idAppIsBottom f n_args
410 -- Application of a function which
411 -- always gives bottom; we treat this as cheap
412 -- because it certainly doesn't need to be shared!
414 go (App f a) n_args args_cheap
415 | isTypeArg a = go f n_args args_cheap
416 | otherwise = go f (n_args + 1) (exprIsCheap a && args_cheap)
418 go other n_args args_cheap = False
420 idAppIsCheap :: Id -> Int -> Bool
421 idAppIsCheap id n_val_args
422 | n_val_args == 0 = True -- Just a type application of
423 -- a variable (f t1 t2 t3)
425 | otherwise = case globalIdDetails id of
427 RecordSelId _ -> True -- I'm experimenting with making record selection
428 -- look cheap, so we will substitute it inside a
429 -- lambda. Particularly for dictionary field selection
431 PrimOpId op -> primOpIsCheap op -- In principle we should worry about primops
432 -- that return a type variable, since the result
433 -- might be applied to something, but I'm not going
434 -- to bother to check the number of args
435 other -> n_val_args < idArity id
438 exprOkForSpeculation returns True of an expression that it is
440 * safe to evaluate even if normal order eval might not
441 evaluate the expression at all, or
443 * safe *not* to evaluate even if normal order would do so
447 the expression guarantees to terminate,
449 without raising an exception,
450 without causing a side effect (e.g. writing a mutable variable)
453 let x = case y# +# 1# of { r# -> I# r# }
456 case y# +# 1# of { r# ->
461 We can only do this if the (y+1) is ok for speculation: it has no
462 side effects, and can't diverge or raise an exception.
465 exprOkForSpeculation :: CoreExpr -> Bool
466 exprOkForSpeculation (Lit _) = True
467 exprOkForSpeculation (Var v) = isUnLiftedType (idType v)
468 exprOkForSpeculation (Note _ e) = exprOkForSpeculation e
469 exprOkForSpeculation other_expr
470 = go other_expr 0 True
472 go (Var f) n_args args_ok
473 = case globalIdDetails f of
474 DataConId _ -> True -- The strictness of the constructor has already
475 -- been expressed by its "wrapper", so we don't need
476 -- to take the arguments into account
478 PrimOpId op -> primOpOkForSpeculation op && args_ok
479 -- A bit conservative: we don't really need
480 -- to care about lazy arguments, but this is easy
484 go (App f a) n_args args_ok
485 | isTypeArg a = go f n_args args_ok
486 | otherwise = go f (n_args + 1) (exprOkForSpeculation a && args_ok)
488 go other n_args args_ok = False
493 exprIsBottom :: CoreExpr -> Bool -- True => definitely bottom
494 exprIsBottom e = go 0 e
496 -- n is the number of args
497 go n (Note _ e) = go n e
498 go n (Let _ e) = go n e
499 go n (Case e _ _) = go 0 e -- Just check the scrut
500 go n (App e _) = go (n+1) e
501 go n (Var v) = idAppIsBottom v n
503 go n (Lam _ _) = False
505 idAppIsBottom :: Id -> Int -> Bool
506 idAppIsBottom id n_val_args = appIsBottom (idStrictness id) n_val_args
509 @exprIsValue@ returns true for expressions that are certainly *already*
510 evaluated to WHNF. This is used to decide wether it's ok to change
511 case x of _ -> e ===> e
513 and to decide whether it's safe to discard a `seq`
515 So, it does *not* treat variables as evaluated, unless they say they are.
517 But it *does* treat partial applications and constructor applications
518 as values, even if their arguments are non-trivial;
519 e.g. (:) (f x) (map f xs) is a value
520 map (...redex...) is a value
521 Because `seq` on such things completes immediately
523 A possible worry: constructors with unboxed args:
525 Suppose (f x) diverges; then C (f x) is not a value. True, but
526 this form is illegal (see the invariants in CoreSyn). Args of unboxed
527 type must be ok-for-speculation (or trivial).
530 exprIsValue :: CoreExpr -> Bool -- True => Value-lambda, constructor, PAP
531 exprIsValue (Type ty) = True -- Types are honorary Values; we don't mind
533 exprIsValue (Lit l) = True
534 exprIsValue (Lam b e) = isId b || exprIsValue e
535 exprIsValue (Note _ e) = exprIsValue e
536 exprIsValue other_expr
539 go (Var f) n_args = idAppIsValue f n_args
542 | isTypeArg a = go f n_args
543 | otherwise = go f (n_args + 1)
545 go (Note _ f) n_args = go f n_args
547 go other n_args = False
549 idAppIsValue :: Id -> Int -> Bool
550 idAppIsValue id n_val_args
551 = case globalIdDetails id of
553 PrimOpId _ -> n_val_args < idArity id
554 other | n_val_args == 0 -> isEvaldUnfolding (idUnfolding id)
555 | otherwise -> n_val_args < idArity id
556 -- A worry: what if an Id's unfolding is just itself:
557 -- then we could get an infinite loop...
561 exprIsConApp_maybe :: CoreExpr -> Maybe (DataCon, [CoreExpr])
562 exprIsConApp_maybe expr
563 = analyse (collectArgs expr)
565 analyse (Var fun, args)
566 | Just con <- isDataConId_maybe fun,
567 length args >= dataConRepArity con
568 -- Might be > because the arity excludes type args
571 -- Look through unfoldings, but only cheap ones, because
572 -- we are effectively duplicating the unfolding
573 analyse (Var fun, [])
574 | let unf = idUnfolding fun,
576 = exprIsConApp_maybe (unfoldingTemplate unf)
578 analyse other = Nothing
583 %************************************************************************
585 \subsection{Eta reduction and expansion}
587 %************************************************************************
589 @etaReduce@ trys an eta reduction at the top level of a Core Expr.
591 e.g. \ x y -> f x y ===> f
593 But we only do this if it gets rid of a whole lambda, not part.
594 The idea is that lambdas are often quite helpful: they indicate
595 head normal forms, so we don't want to chuck them away lightly.
598 etaReduce :: CoreExpr -> CoreExpr
599 -- ToDo: we should really check that we don't turn a non-bottom
600 -- lambda into a bottom variable. Sigh
602 etaReduce expr@(Lam bndr body)
603 = check (reverse binders) body
605 (binders, body) = collectBinders expr
608 | not (any (`elemVarSet` body_fvs) binders)
611 body_fvs = exprFreeVars body
613 check (b : bs) (App fun arg)
614 | (varToCoreExpr b `cheapEqExpr` arg)
617 check _ _ = expr -- Bale out
619 etaReduce expr = expr -- The common case
624 exprEtaExpandArity :: CoreExpr -> (Int, Bool)
625 -- The Int is number of value args the thing can be
626 -- applied to without doing much work
627 -- The Bool is True iff there are enough explicit value lambdas
628 -- at the top to make this arity apparent
629 -- (but ignore it when arity==0)
631 -- This is used when eta expanding
632 -- e ==> \xy -> e x y
634 -- It returns 1 (or more) to:
635 -- case x of p -> \s -> ...
636 -- because for I/O ish things we really want to get that \s to the top.
637 -- We are prepared to evaluate x each time round the loop in order to get that
639 -- Consider let x = expensive in \y z -> E
640 -- We want this to have arity 2 if the \y-abstraction is a 1-shot lambda
642 -- Hence the list of Bools returned by go1
643 -- NB: this is particularly important/useful for IO state
644 -- transformers, where we often get
645 -- let x = E in \ s -> ...
646 -- and the \s is a real-world state token abstraction. Such
647 -- abstractions are almost invariably 1-shot, so we want to
648 -- pull the \s out, past the let x=E.
649 -- The hack is in Id.isOneShotLambda
654 go :: Int -> CoreExpr -> (Int,Bool)
655 go ar (Lam x e) | isId x = go (ar+1) e
656 | otherwise = go ar e
657 go ar (Note n e) | ok_note n = go ar e
658 go ar other = (ar + ar', ar' == 0)
660 ar' = length (go1 other)
662 go1 :: CoreExpr -> [Bool]
663 -- (go1 e) = [b1,..,bn]
664 -- means expression can be rewritten \x_b1 -> ... \x_bn -> body
665 -- where bi is True <=> the lambda is one-shot
667 go1 (Note n e) | ok_note n = go1 e
668 go1 (Var v) = replicate (idArity v) False -- When the type of the Id
669 -- encodes one-shot-ness, use
672 -- Lambdas; increase arity
673 go1 (Lam x e) | isId x = isOneShotLambda x : go1 e
676 -- Applications; decrease arity
677 go1 (App f (Type _)) = go1 f
678 go1 (App f a) = case go1 f of
679 (one_shot : xs) | one_shot || exprIsCheap a -> xs
682 -- Case/Let; keep arity if either the expression is cheap
683 -- or it's a 1-shot lambda
684 go1 (Case scrut _ alts) = case foldr1 (zipWith (&&)) [go1 rhs | (_,_,rhs) <- alts] of
685 xs@(one_shot : _) | one_shot || exprIsCheap scrut -> xs
687 go1 (Let b e) = case go1 e of
688 xs@(one_shot : _) | one_shot || all exprIsCheap (rhssOfBind b) -> xs
693 ok_note (Coerce _ _) = True
694 ok_note InlineCall = True
695 ok_note other = False
696 -- Notice that we do not look through __inline_me__
697 -- This may seem surprising, but consider
698 -- f = _inline_me (\x -> e)
699 -- We DO NOT want to eta expand this to
700 -- f = \x -> (_inline_me (\x -> e)) x
701 -- because the _inline_me gets dropped now it is applied,
706 min_zero :: [Int] -> Int -- Find the minimum, but zero is the smallest
707 min_zero (x:xs) = go x xs
709 go 0 xs = 0 -- Nothing beats zero
711 go min (x:xs) | x < min = go x xs
712 | otherwise = go min xs
718 etaExpand :: Int -- Add this number of value args
720 -> CoreExpr -> Type -- Expression and its type
722 -- (etaExpand n us e ty) returns an expression with
723 -- the same meaning as 'e', but with arity 'n'.
725 -- Given e' = etaExpand n us e ty
727 -- ty = exprType e = exprType e'
729 -- etaExpand deals with for-alls and coerces. For example:
731 -- where E :: forall a. T
732 -- newtype T = MkT (A -> B)
735 -- (/\b. coerce T (\y::A -> (coerce (A->B) (E b) y)
737 etaExpand n us expr ty
738 | n == 0 -- Saturated, so nothing to do
741 | otherwise -- An unsaturated constructor or primop; eta expand it
742 = case splitForAllTy_maybe ty of {
743 Just (tv,ty') -> Lam tv (etaExpand n us (App expr (Type (mkTyVarTy tv))) ty')
747 case splitFunTy_maybe ty of {
748 Just (arg_ty, res_ty) -> Lam arg1 (etaExpand (n-1) us2 (App expr (Var arg1)) res_ty)
750 arg1 = mkSysLocal SLIT("eta") uniq arg_ty
751 (us1, us2) = splitUniqSupply us
752 uniq = uniqFromSupply us1
756 case splitNewType_maybe ty of {
757 Just ty' -> mkCoerce ty ty' (etaExpand n us (mkCoerce ty' ty expr) ty') ;
759 Nothing -> pprTrace "Bad eta expand" (ppr expr $$ ppr ty) expr
764 exprArity is a cheap-and-cheerful version of exprEtaExpandArity.
765 It tells how many things the expression can be applied to before doing
766 any work. It doesn't look inside cases, lets, etc. The idea is that
767 exprEtaExpandArity will do the hard work, leaving something that's easy
768 for exprArity to grapple with. In particular, Simplify uses exprArity to
769 compute the ArityInfo for the Id.
771 Originally I thought that it was enough just to look for top-level lambdas, but
772 it isn't. I've seen this
774 foo = PrelBase.timesInt
776 We want foo to get arity 2 even though the eta-expander will leave it
777 unchanged, in the expectation that it'll be inlined. But occasionally it
778 isn't, because foo is blacklisted (used in a rule).
780 Similarly, see the ok_note check in exprEtaExpandArity. So
781 f = __inline_me (\x -> e)
782 won't be eta-expanded.
784 And in any case it seems more robust to have exprArity be a bit more intelligent.
787 exprArity :: CoreExpr -> Int
788 exprArity e = go e `max` 0
790 go (Lam x e) | isId x = go e + 1
793 go (App e (Type t)) = go e
794 go (App f a) = go f - 1
795 go (Var v) = idArity v
800 %************************************************************************
802 \subsection{Equality}
804 %************************************************************************
806 @cheapEqExpr@ is a cheap equality test which bales out fast!
807 True => definitely equal
808 False => may or may not be equal
811 cheapEqExpr :: Expr b -> Expr b -> Bool
813 cheapEqExpr (Var v1) (Var v2) = v1==v2
814 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
815 cheapEqExpr (Type t1) (Type t2) = t1 == t2
817 cheapEqExpr (App f1 a1) (App f2 a2)
818 = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
820 cheapEqExpr _ _ = False
822 exprIsBig :: Expr b -> Bool
823 -- Returns True of expressions that are too big to be compared by cheapEqExpr
824 exprIsBig (Lit _) = False
825 exprIsBig (Var v) = False
826 exprIsBig (Type t) = False
827 exprIsBig (App f a) = exprIsBig f || exprIsBig a
828 exprIsBig other = True
833 eqExpr :: CoreExpr -> CoreExpr -> Bool
834 -- Works ok at more general type, but only needed at CoreExpr
836 = eq emptyVarEnv e1 e2
838 -- The "env" maps variables in e1 to variables in ty2
839 -- So when comparing lambdas etc,
840 -- we in effect substitute v2 for v1 in e1 before continuing
841 eq env (Var v1) (Var v2) = case lookupVarEnv env v1 of
842 Just v1' -> v1' == v2
845 eq env (Lit lit1) (Lit lit2) = lit1 == lit2
846 eq env (App f1 a1) (App f2 a2) = eq env f1 f2 && eq env a1 a2
847 eq env (Lam v1 e1) (Lam v2 e2) = eq (extendVarEnv env v1 v2) e1 e2
848 eq env (Let (NonRec v1 r1) e1)
849 (Let (NonRec v2 r2) e2) = eq env r1 r2 && eq (extendVarEnv env v1 v2) e1 e2
850 eq env (Let (Rec ps1) e1)
851 (Let (Rec ps2) e2) = length ps1 == length ps2 &&
852 and (zipWith eq_rhs ps1 ps2) &&
855 env' = extendVarEnvList env [(v1,v2) | ((v1,_),(v2,_)) <- zip ps1 ps2]
856 eq_rhs (_,r1) (_,r2) = eq env' r1 r2
857 eq env (Case e1 v1 a1)
858 (Case e2 v2 a2) = eq env e1 e2 &&
859 length a1 == length a2 &&
860 and (zipWith (eq_alt env') a1 a2)
862 env' = extendVarEnv env v1 v2
864 eq env (Note n1 e1) (Note n2 e2) = eq_note env n1 n2 && eq env e1 e2
865 eq env (Type t1) (Type t2) = t1 == t2
868 eq_list env [] [] = True
869 eq_list env (e1:es1) (e2:es2) = eq env e1 e2 && eq_list env es1 es2
870 eq_list env es1 es2 = False
872 eq_alt env (c1,vs1,r1) (c2,vs2,r2) = c1==c2 &&
873 eq (extendVarEnvList env (vs1 `zip` vs2)) r1 r2
875 eq_note env (SCC cc1) (SCC cc2) = cc1 == cc2
876 eq_note env (Coerce t1 f1) (Coerce t2 f2) = t1==t2 && f1==f2
877 eq_note env InlineCall InlineCall = True
878 eq_note env other1 other2 = False
882 %************************************************************************
884 \subsection{The size of an expression}
886 %************************************************************************
889 coreBindsSize :: [CoreBind] -> Int
890 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
892 exprSize :: CoreExpr -> Int
893 -- A measure of the size of the expressions
894 -- It also forces the expression pretty drastically as a side effect
895 exprSize (Var v) = varSize v
896 exprSize (Lit lit) = lit `seq` 1
897 exprSize (App f a) = exprSize f + exprSize a
898 exprSize (Lam b e) = varSize b + exprSize e
899 exprSize (Let b e) = bindSize b + exprSize e
900 exprSize (Case e b as) = exprSize e + varSize b + foldr ((+) . altSize) 0 as
901 exprSize (Note n e) = noteSize n + exprSize e
902 exprSize (Type t) = seqType t `seq` 1
904 noteSize (SCC cc) = cc `seq` 1
905 noteSize (Coerce t1 t2) = seqType t1 `seq` seqType t2 `seq` 1
906 noteSize InlineCall = 1
907 noteSize InlineMe = 1
909 varSize :: Var -> Int
910 varSize b | isTyVar b = 1
911 | otherwise = seqType (idType b) `seq`
912 megaSeqIdInfo (idInfo b) `seq`
915 varsSize = foldr ((+) . varSize) 0
917 bindSize (NonRec b e) = varSize b + exprSize e
918 bindSize (Rec prs) = foldr ((+) . pairSize) 0 prs
920 pairSize (b,e) = varSize b + exprSize e
922 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
926 %************************************************************************
930 %************************************************************************
933 hashExpr :: CoreExpr -> Int
934 hashExpr e | hash < 0 = 77 -- Just in case we hit -maxInt
937 hash = abs (hash_expr e) -- Negative numbers kill UniqFM
939 hash_expr (Note _ e) = hash_expr e
940 hash_expr (Let (NonRec b r) e) = hashId b
941 hash_expr (Let (Rec ((b,r):_)) e) = hashId b
942 hash_expr (Case _ b _) = hashId b
943 hash_expr (App f e) = hash_expr f * fast_hash_expr e
944 hash_expr (Var v) = hashId v
945 hash_expr (Lit lit) = hashLiteral lit
946 hash_expr (Lam b _) = hashId b
947 hash_expr (Type t) = trace "hash_expr: type" 1 -- Shouldn't happen
949 fast_hash_expr (Var v) = hashId v
950 fast_hash_expr (Lit lit) = hashLiteral lit
951 fast_hash_expr (App f (Type _)) = fast_hash_expr f
952 fast_hash_expr (App f a) = fast_hash_expr a
953 fast_hash_expr (Lam b _) = hashId b
954 fast_hash_expr other = 1
957 hashId id = hashName (idName id)