2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Utility functions on @Core@ syntax
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 -- | Commonly useful utilites for manipulating the Core language
18 -- * Constructing expressions
19 mkInlineMe, mkSCC, mkCoerce, mkCoerceI,
20 bindNonRec, needsCaseBinding,
21 mkAltExpr, mkPiType, mkPiTypes,
23 -- * Taking expressions apart
24 findDefault, findAlt, isDefaultAlt, mergeAlts, trimConArgs,
26 -- * Properties of expressions
27 exprType, coreAltType, coreAltsType,
28 exprIsDupable, exprIsTrivial, exprIsCheap, exprIsExpandable,
29 exprIsHNF,exprOkForSpeculation, exprIsBig,
30 exprIsConApp_maybe, exprIsBottom,
33 -- * Expression and bindings size
34 coreBindsSize, exprSize,
42 -- * Manipulating data constructors and types
43 applyTypeToArgs, applyTypeToArg,
44 dataConOrigInstPat, dataConRepInstPat, dataConRepFSInstPat
47 #include "HsVersions.h"
80 %************************************************************************
82 \subsection{Find the type of a Core atom/expression}
84 %************************************************************************
87 exprType :: CoreExpr -> Type
88 -- ^ Recover the type of a well-typed Core expression. Fails when
89 -- applied to the actual 'CoreSyn.Type' expression as it cannot
90 -- really be said to have a type
91 exprType (Var var) = idType var
92 exprType (Lit lit) = literalType lit
93 exprType (Let _ body) = exprType body
94 exprType (Case _ _ ty _) = ty
95 exprType (Cast _ co) = snd (coercionKind co)
96 exprType (Note _ e) = exprType e
97 exprType (Lam binder expr) = mkPiType binder (exprType expr)
99 = case collectArgs e of
100 (fun, args) -> applyTypeToArgs e (exprType fun) args
102 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
104 coreAltType :: CoreAlt -> Type
105 -- ^ Returns the type of the alternatives right hand side
106 coreAltType (_,_,rhs) = exprType rhs
108 coreAltsType :: [CoreAlt] -> Type
109 -- ^ Returns the type of the first alternative, which should be the same as for all alternatives
110 coreAltsType (alt:_) = coreAltType alt
111 coreAltsType [] = panic "corAltsType"
115 mkPiType :: Var -> Type -> Type
116 -- ^ Makes a @(->)@ type or a forall type, depending
117 -- on whether it is given a type variable or a term variable.
118 mkPiTypes :: [Var] -> Type -> Type
119 -- ^ 'mkPiType' for multiple type or value arguments
122 | isId v = mkFunTy (idType v) ty
123 | otherwise = mkForAllTy v ty
125 mkPiTypes vs ty = foldr mkPiType ty vs
129 applyTypeToArg :: Type -> CoreExpr -> Type
130 -- ^ Determines the type resulting from applying an expression to a function with the given type
131 applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
132 applyTypeToArg fun_ty _ = funResultTy fun_ty
134 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
135 -- ^ A more efficient version of 'applyTypeToArg' when we have several arguments.
136 -- The first argument is just for debugging, and gives some context
137 applyTypeToArgs _ op_ty [] = op_ty
139 applyTypeToArgs e op_ty (Type ty : args)
140 = -- Accumulate type arguments so we can instantiate all at once
143 go rev_tys (Type ty : args) = go (ty:rev_tys) args
144 go rev_tys rest_args = applyTypeToArgs e op_ty' rest_args
146 op_ty' = applyTysD msg op_ty (reverse rev_tys)
147 msg = ptext (sLit "applyTypeToArgs") <+>
150 applyTypeToArgs e op_ty (_ : args)
151 = case (splitFunTy_maybe op_ty) of
152 Just (_, res_ty) -> applyTypeToArgs e res_ty args
153 Nothing -> pprPanic "applyTypeToArgs" (panic_msg e op_ty)
155 panic_msg :: CoreExpr -> Type -> SDoc
156 panic_msg e op_ty = pprCoreExpr e $$ ppr op_ty
159 %************************************************************************
161 \subsection{Attaching notes}
163 %************************************************************************
165 mkNote removes redundant coercions, and SCCs where possible
169 mkNote :: Note -> CoreExpr -> CoreExpr
170 mkNote (SCC cc) expr = mkSCC cc expr
171 mkNote InlineMe expr = mkInlineMe expr
172 mkNote note expr = Note note expr
176 Drop trivial InlineMe's. This is somewhat important, because if we have an unfolding
177 that looks like (Note InlineMe (Var v)), the InlineMe doesn't go away because it may
178 not be *applied* to anything.
180 We don't use exprIsTrivial here, though, because we sometimes generate worker/wrapper
183 f = inline_me (coerce t fw)
184 As usual, the inline_me prevents the worker from getting inlined back into the wrapper.
185 We want the split, so that the coerces can cancel at the call site.
187 However, we can get left with tiresome type applications. Notably, consider
188 f = /\ a -> let t = e in (t, w)
189 Then lifting the let out of the big lambda gives
191 f = /\ a -> let t = inline_me (t' a) in (t, w)
192 The inline_me is to stop the simplifier inlining t' right back
193 into t's RHS. In the next phase we'll substitute for t (since
194 its rhs is trivial) and *then* we could get rid of the inline_me.
195 But it hardly seems worth it, so I don't bother.
198 -- | Wraps the given expression in an inlining hint unless the expression
199 -- is trivial in some sense, so that doing so would usually hurt us
200 mkInlineMe :: CoreExpr -> CoreExpr
201 mkInlineMe e@(Var _) = e
202 mkInlineMe e@(Note InlineMe _) = e
203 mkInlineMe e = Note InlineMe e
207 -- | Wrap the given expression in the coercion, dropping identity coercions and coalescing nested coercions
208 mkCoerceI :: CoercionI -> CoreExpr -> CoreExpr
210 mkCoerceI (ACo co) e = mkCoerce co e
212 -- | Wrap the given expression in the coercion safely, coalescing nested coercions
213 mkCoerce :: Coercion -> CoreExpr -> CoreExpr
214 mkCoerce co (Cast expr co2)
215 = ASSERT(let { (from_ty, _to_ty) = coercionKind co;
216 (_from_ty2, to_ty2) = coercionKind co2} in
217 from_ty `coreEqType` to_ty2 )
218 mkCoerce (mkTransCoercion co2 co) expr
221 = let (from_ty, _to_ty) = coercionKind co in
222 -- if to_ty `coreEqType` from_ty
225 ASSERT2(from_ty `coreEqType` (exprType expr), text "Trying to coerce" <+> text "(" <> ppr expr $$ text "::" <+> ppr (exprType expr) <> text ")" $$ ppr co $$ ppr (coercionKindPredTy co))
230 -- | Wraps the given expression in the cost centre unless
231 -- in a way that maximises their utility to the user
232 mkSCC :: CostCentre -> Expr b -> Expr b
233 -- Note: Nested SCC's *are* preserved for the benefit of
234 -- cost centre stack profiling
235 mkSCC _ (Lit lit) = Lit lit
236 mkSCC cc (Lam x e) = Lam x (mkSCC cc e) -- Move _scc_ inside lambda
237 mkSCC cc (Note (SCC cc') e) = Note (SCC cc) (Note (SCC cc') e)
238 mkSCC cc (Note n e) = Note n (mkSCC cc e) -- Move _scc_ inside notes
239 mkSCC cc (Cast e co) = Cast (mkSCC cc e) co -- Move _scc_ inside cast
240 mkSCC cc expr = Note (SCC cc) expr
244 %************************************************************************
246 \subsection{Other expression construction}
248 %************************************************************************
251 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
252 -- ^ @bindNonRec x r b@ produces either:
258 -- > case r of x { _DEFAULT_ -> b }
260 -- depending on whether we have to use a @case@ or @let@
261 -- binding for the expression (see 'needsCaseBinding').
262 -- It's used by the desugarer to avoid building bindings
263 -- that give Core Lint a heart attack, although actually
264 -- the simplifier deals with them perfectly well. See
265 -- also 'MkCore.mkCoreLet'
266 bindNonRec bndr rhs body
267 | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
268 | otherwise = Let (NonRec bndr rhs) body
270 -- | Tests whether we have to use a @case@ rather than @let@ binding for this expression
271 -- as per the invariants of 'CoreExpr': see "CoreSyn#let_app_invariant"
272 needsCaseBinding :: Type -> CoreExpr -> Bool
273 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
274 -- Make a case expression instead of a let
275 -- These can arise either from the desugarer,
276 -- or from beta reductions: (\x.e) (x +# y)
280 mkAltExpr :: AltCon -- ^ Case alternative constructor
281 -> [CoreBndr] -- ^ Things bound by the pattern match
282 -> [Type] -- ^ The type arguments to the case alternative
284 -- ^ This guy constructs the value that the scrutinee must have
285 -- given that you are in one particular branch of a case
286 mkAltExpr (DataAlt con) args inst_tys
287 = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
288 mkAltExpr (LitAlt lit) [] []
290 mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
291 mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
295 %************************************************************************
297 \subsection{Taking expressions apart}
299 %************************************************************************
301 The default alternative must be first, if it exists at all.
302 This makes it easy to find, though it makes matching marginally harder.
305 -- | Extract the default case alternative
306 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
307 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
308 findDefault alts = (alts, Nothing)
310 isDefaultAlt :: CoreAlt -> Bool
311 isDefaultAlt (DEFAULT, _, _) = True
312 isDefaultAlt _ = False
315 -- | Find the case alternative corresponding to a particular
316 -- constructor: panics if no such constructor exists
317 findAlt :: AltCon -> [CoreAlt] -> Maybe CoreAlt
318 -- A "Nothing" result *is* legitmiate
319 -- See Note [Unreachable code]
322 (deflt@(DEFAULT,_,_):alts) -> go alts (Just deflt)
326 go (alt@(con1,_,_) : alts) deflt
327 = case con `cmpAltCon` con1 of
328 LT -> deflt -- Missed it already; the alts are in increasing order
330 GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
332 ---------------------------------
333 mergeAlts :: [CoreAlt] -> [CoreAlt] -> [CoreAlt]
334 -- ^ Merge alternatives preserving order; alternatives in
335 -- the first argument shadow ones in the second
336 mergeAlts [] as2 = as2
337 mergeAlts as1 [] = as1
338 mergeAlts (a1:as1) (a2:as2)
339 = case a1 `cmpAlt` a2 of
340 LT -> a1 : mergeAlts as1 (a2:as2)
341 EQ -> a1 : mergeAlts as1 as2 -- Discard a2
342 GT -> a2 : mergeAlts (a1:as1) as2
345 ---------------------------------
346 trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
349 -- > case (C a b x y) of
352 -- We want to drop the leading type argument of the scrutinee
353 -- leaving the arguments to match agains the pattern
355 trimConArgs DEFAULT args = ASSERT( null args ) []
356 trimConArgs (LitAlt _) args = ASSERT( null args ) []
357 trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
360 Note [Unreachable code]
361 ~~~~~~~~~~~~~~~~~~~~~~~
362 It is possible (although unusual) for GHC to find a case expression
363 that cannot match. For example:
365 data Col = Red | Green | Blue
369 _ -> ...(case x of { Green -> e1; Blue -> e2 })...
371 Suppose that for some silly reason, x isn't substituted in the case
372 expression. (Perhaps there's a NOINLINE on it, or profiling SCC stuff
373 gets in the way; cf Trac #3118.) Then the full-lazines pass might produce
377 lvl = case x of { Green -> e1; Blue -> e2 })
382 Now if x gets inlined, we won't be able to find a matching alternative
383 for 'Red'. That's because 'lvl' is unreachable. So rather than crashing
384 we generate (error "Inaccessible alternative").
386 Similar things can happen (augmented by GADTs) when the Simplifier
387 filters down the matching alternatives in Simplify.rebuildCase.
391 %************************************************************************
393 \subsection{Figuring out things about expressions}
395 %************************************************************************
397 @exprIsTrivial@ is true of expressions we are unconditionally happy to
398 duplicate; simple variables and constants, and type
399 applications. Note that primop Ids aren't considered
402 There used to be a gruesome test for (hasNoBinding v) in the
404 exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
405 The idea here is that a constructor worker, like \$wJust, is
406 really short for (\x -> \$wJust x), becuase \$wJust has no binding.
407 So it should be treated like a lambda. Ditto unsaturated primops.
408 But now constructor workers are not "have-no-binding" Ids. And
409 completely un-applied primops and foreign-call Ids are sufficiently
410 rare that I plan to allow them to be duplicated and put up with
413 SCC notes. We do not treat (_scc_ "foo" x) as trivial, because
414 a) it really generates code, (and a heap object when it's
415 a function arg) to capture the cost centre
416 b) see the note [SCC-and-exprIsTrivial] in Simplify.simplLazyBind
419 exprIsTrivial :: CoreExpr -> Bool
420 exprIsTrivial (Var _) = True -- See notes above
421 exprIsTrivial (Type _) = True
422 exprIsTrivial (Lit lit) = litIsTrivial lit
423 exprIsTrivial (App e arg) = not (isRuntimeArg arg) && exprIsTrivial e
424 exprIsTrivial (Note (SCC _) _) = False -- See notes above
425 exprIsTrivial (Note _ e) = exprIsTrivial e
426 exprIsTrivial (Cast e _) = exprIsTrivial e
427 exprIsTrivial (Lam b body) = not (isRuntimeVar b) && exprIsTrivial body
428 exprIsTrivial _ = False
432 @exprIsDupable@ is true of expressions that can be duplicated at a modest
433 cost in code size. This will only happen in different case
434 branches, so there's no issue about duplicating work.
436 That is, exprIsDupable returns True of (f x) even if
437 f is very very expensive to call.
439 Its only purpose is to avoid fruitless let-binding
440 and then inlining of case join points
444 exprIsDupable :: CoreExpr -> Bool
445 exprIsDupable (Type _) = True
446 exprIsDupable (Var _) = True
447 exprIsDupable (Lit lit) = litIsDupable lit
448 exprIsDupable (Note InlineMe _) = True
449 exprIsDupable (Note _ e) = exprIsDupable e
450 exprIsDupable (Cast e _) = exprIsDupable e
455 go (App f a) n_args = n_args < dupAppSize
461 dupAppSize = 4 -- Size of application we are prepared to duplicate
464 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
465 it is obviously in weak head normal form, or is cheap to get to WHNF.
466 [Note that that's not the same as exprIsDupable; an expression might be
467 big, and hence not dupable, but still cheap.]
469 By ``cheap'' we mean a computation we're willing to:
470 push inside a lambda, or
471 inline at more than one place
472 That might mean it gets evaluated more than once, instead of being
473 shared. The main examples of things which aren't WHNF but are
478 (where e, and all the ei are cheap)
481 (where e and b are cheap)
484 (where op is a cheap primitive operator)
487 (because we are happy to substitute it inside a lambda)
489 Notice that a variable is considered 'cheap': we can push it inside a lambda,
490 because sharing will make sure it is only evaluated once.
493 exprIsCheap' :: (Id -> Bool) -> CoreExpr -> Bool
494 exprIsCheap' _ (Lit _) = True
495 exprIsCheap' _ (Type _) = True
496 exprIsCheap' _ (Var _) = True
497 exprIsCheap' _ (Note InlineMe _) = True
498 exprIsCheap' is_conlike (Note _ e) = exprIsCheap' is_conlike e
499 exprIsCheap' is_conlike (Cast e _) = exprIsCheap' is_conlike e
500 exprIsCheap' is_conlike (Lam x e) = isRuntimeVar x
501 || exprIsCheap' is_conlike e
502 exprIsCheap' is_conlike (Case e _ _ alts) = exprIsCheap' is_conlike e &&
503 and [exprIsCheap' is_conlike rhs | (_,_,rhs) <- alts]
504 -- Experimentally, treat (case x of ...) as cheap
505 -- (and case __coerce x etc.)
506 -- This improves arities of overloaded functions where
507 -- there is only dictionary selection (no construction) involved
508 exprIsCheap' is_conlike (Let (NonRec x _) e)
509 | isUnLiftedType (idType x) = exprIsCheap' is_conlike e
511 -- strict lets always have cheap right hand sides,
512 -- and do no allocation.
514 exprIsCheap' is_conlike other_expr -- Applications and variables
517 -- Accumulate value arguments, then decide
518 go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
519 | otherwise = go f val_args
521 go (Var _) [] = True -- Just a type application of a variable
522 -- (f t1 t2 t3) counts as WHNF
524 = case idDetails f of
525 RecSelId {} -> go_sel args
526 ClassOpId _ -> go_sel args
527 PrimOpId op -> go_primop op args
529 _ | is_conlike f -> go_pap args
530 | length args < idArity f -> go_pap args
533 -- Application of a function which
534 -- always gives bottom; we treat this as cheap
535 -- because it certainly doesn't need to be shared!
540 go_pap args = all exprIsTrivial args
541 -- For constructor applications and primops, check that all
542 -- the args are trivial. We don't want to treat as cheap, say,
544 -- We'll put up with one constructor application, but not dozens
547 go_primop op args = primOpIsCheap op && all (exprIsCheap' is_conlike) args
548 -- In principle we should worry about primops
549 -- that return a type variable, since the result
550 -- might be applied to something, but I'm not going
551 -- to bother to check the number of args
554 go_sel [arg] = exprIsCheap' is_conlike arg -- I'm experimenting with making record selection
555 go_sel _ = False -- look cheap, so we will substitute it inside a
556 -- lambda. Particularly for dictionary field selection.
557 -- BUT: Take care with (sel d x)! The (sel d) might be cheap, but
558 -- there's no guarantee that (sel d x) will be too. Hence (n_val_args == 1)
560 exprIsCheap :: CoreExpr -> Bool
561 exprIsCheap = exprIsCheap' isDataConWorkId
563 exprIsExpandable :: CoreExpr -> Bool
564 exprIsExpandable = exprIsCheap' isConLikeId
568 -- | 'exprOkForSpeculation' returns True of an expression that is:
570 -- * Safe to evaluate even if normal order eval might not
571 -- evaluate the expression at all, or
573 -- * Safe /not/ to evaluate even if normal order would do so
575 -- Precisely, it returns @True@ iff:
577 -- * The expression guarantees to terminate,
581 -- * without raising an exception,
583 -- * without causing a side effect (e.g. writing a mutable variable)
585 -- Note that if @exprIsHNF e@, then @exprOkForSpecuation e@.
586 -- As an example of the considerations in this test, consider:
588 -- > let x = case y# +# 1# of { r# -> I# r# }
591 -- being translated to:
593 -- > case y# +# 1# of { r# ->
598 -- We can only do this if the @y + 1@ is ok for speculation: it has no
599 -- side effects, and can't diverge or raise an exception.
600 exprOkForSpeculation :: CoreExpr -> Bool
601 exprOkForSpeculation (Lit _) = True
602 exprOkForSpeculation (Type _) = True
603 -- Tick boxes are *not* suitable for speculation
604 exprOkForSpeculation (Var v) = isUnLiftedType (idType v)
605 && not (isTickBoxOp v)
606 exprOkForSpeculation (Note _ e) = exprOkForSpeculation e
607 exprOkForSpeculation (Cast e _) = exprOkForSpeculation e
608 exprOkForSpeculation other_expr
609 = case collectArgs other_expr of
610 (Var f, args) -> spec_ok (idDetails f) args
614 spec_ok (DataConWorkId _) _
615 = True -- The strictness of the constructor has already
616 -- been expressed by its "wrapper", so we don't need
617 -- to take the arguments into account
619 spec_ok (PrimOpId op) args
620 | isDivOp op, -- Special case for dividing operations that fail
621 [arg1, Lit lit] <- args -- only if the divisor is zero
622 = not (isZeroLit lit) && exprOkForSpeculation arg1
623 -- Often there is a literal divisor, and this
624 -- can get rid of a thunk in an inner looop
627 = primOpOkForSpeculation op &&
628 all exprOkForSpeculation args
629 -- A bit conservative: we don't really need
630 -- to care about lazy arguments, but this is easy
634 -- | True of dyadic operators that can fail only if the second arg is zero!
635 isDivOp :: PrimOp -> Bool
636 -- This function probably belongs in PrimOp, or even in
637 -- an automagically generated file.. but it's such a
638 -- special case I thought I'd leave it here for now.
639 isDivOp IntQuotOp = True
640 isDivOp IntRemOp = True
641 isDivOp WordQuotOp = True
642 isDivOp WordRemOp = True
643 isDivOp FloatDivOp = True
644 isDivOp DoubleDivOp = True
649 -- | True of expressions that are guaranteed to diverge upon execution
650 exprIsBottom :: CoreExpr -> Bool
651 exprIsBottom e = go 0 e
653 -- n is the number of args
654 go n (Note _ e) = go n e
655 go n (Cast e _) = go n e
656 go n (Let _ e) = go n e
657 go _ (Case e _ _ _) = go 0 e -- Just check the scrut
658 go n (App e _) = go (n+1) e
659 go n (Var v) = idAppIsBottom v n
661 go _ (Lam _ _) = False
662 go _ (Type _) = False
664 idAppIsBottom :: Id -> Int -> Bool
665 idAppIsBottom id n_val_args = appIsBottom (idNewStrictness id) n_val_args
670 -- | This returns true for expressions that are certainly /already/
671 -- evaluated to /head/ normal form. This is used to decide whether it's ok
674 -- > case x of _ -> e
680 -- and to decide whether it's safe to discard a 'seq'.
681 -- So, it does /not/ treat variables as evaluated, unless they say they are.
682 -- However, it /does/ treat partial applications and constructor applications
683 -- as values, even if their arguments are non-trivial, provided the argument
684 -- type is lifted. For example, both of these are values:
686 -- > (:) (f x) (map f xs)
687 -- > map (...redex...)
689 -- Because 'seq' on such things completes immediately.
691 -- For unlifted argument types, we have to be careful:
695 -- Suppose @f x@ diverges; then @C (f x)@ is not a value. However this can't
696 -- happen: see "CoreSyn#let_app_invariant". This invariant states that arguments of
697 -- unboxed type must be ok-for-speculation (or trivial).
698 exprIsHNF :: CoreExpr -> Bool -- True => Value-lambda, constructor, PAP
699 exprIsHNF (Var v) -- NB: There are no value args at this point
700 = isDataConWorkId v -- Catches nullary constructors,
701 -- so that [] and () are values, for example
702 || idArity v > 0 -- Catches (e.g.) primops that don't have unfoldings
703 || isEvaldUnfolding (idUnfolding v)
704 -- Check the thing's unfolding; it might be bound to a value
705 -- A worry: what if an Id's unfolding is just itself:
706 -- then we could get an infinite loop...
708 exprIsHNF (Lit _) = True
709 exprIsHNF (Type _) = True -- Types are honorary Values;
710 -- we don't mind copying them
711 exprIsHNF (Lam b e) = isRuntimeVar b || exprIsHNF e
712 exprIsHNF (Note _ e) = exprIsHNF e
713 exprIsHNF (Cast e _) = exprIsHNF e
714 exprIsHNF (App e (Type _)) = exprIsHNF e
715 exprIsHNF (App e a) = app_is_value e [a]
718 -- There is at least one value argument
719 app_is_value :: CoreExpr -> [CoreArg] -> Bool
720 app_is_value (Var fun) args
721 = idArity fun > valArgCount args -- Under-applied function
722 || isDataConWorkId fun -- or data constructor
723 app_is_value (Note _ f) as = app_is_value f as
724 app_is_value (Cast f _) as = app_is_value f as
725 app_is_value (App f a) as = app_is_value f (a:as)
726 app_is_value _ _ = False
729 These InstPat functions go here to avoid circularity between DataCon and Id
732 dataConRepInstPat, dataConOrigInstPat :: [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
733 dataConRepFSInstPat :: [FastString] -> [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
735 dataConRepInstPat = dataConInstPat dataConRepArgTys (repeat ((fsLit "ipv")))
736 dataConRepFSInstPat = dataConInstPat dataConRepArgTys
737 dataConOrigInstPat = dataConInstPat dc_arg_tys (repeat ((fsLit "ipv")))
739 dc_arg_tys dc = map mkPredTy (dataConEqTheta dc) ++ map mkPredTy (dataConDictTheta dc) ++ dataConOrigArgTys dc
740 -- Remember to include the existential dictionaries
742 dataConInstPat :: (DataCon -> [Type]) -- function used to find arg tys
743 -> [FastString] -- A long enough list of FSs to use for names
744 -> [Unique] -- An equally long list of uniques, at least one for each binder
746 -> [Type] -- Types to instantiate the universally quantified tyvars
747 -> ([TyVar], [CoVar], [Id]) -- Return instantiated variables
748 -- dataConInstPat arg_fun fss us con inst_tys returns a triple
749 -- (ex_tvs, co_tvs, arg_ids),
751 -- ex_tvs are intended to be used as binders for existential type args
753 -- co_tvs are intended to be used as binders for coercion args and the kinds
754 -- of these vars have been instantiated by the inst_tys and the ex_tys
755 -- The co_tvs include both GADT equalities (dcEqSpec) and
756 -- programmer-specified equalities (dcEqTheta)
758 -- arg_ids are indended to be used as binders for value arguments,
759 -- and their types have been instantiated with inst_tys and ex_tys
760 -- The arg_ids include both dicts (dcDictTheta) and
761 -- programmer-specified arguments (after rep-ing) (deRepArgTys)
764 -- The following constructor T1
767 -- T1 :: forall b. Int -> b -> T(a,b)
770 -- has representation type
771 -- forall a. forall a1. forall b. (a ~ (a1,b)) =>
774 -- dataConInstPat fss us T1 (a1',b') will return
776 -- ([a1'', b''], [c :: (a1', b')~(a1'', b'')], [x :: Int, y :: b''])
778 -- where the double-primed variables are created with the FastStrings and
779 -- Uniques given as fss and us
780 dataConInstPat arg_fun fss uniqs con inst_tys
781 = (ex_bndrs, co_bndrs, arg_ids)
783 univ_tvs = dataConUnivTyVars con
784 ex_tvs = dataConExTyVars con
785 arg_tys = arg_fun con
786 eq_spec = dataConEqSpec con
787 eq_theta = dataConEqTheta con
788 eq_preds = eqSpecPreds eq_spec ++ eq_theta
791 n_co = length eq_preds
793 -- split the Uniques and FastStrings
794 (ex_uniqs, uniqs') = splitAt n_ex uniqs
795 (co_uniqs, id_uniqs) = splitAt n_co uniqs'
797 (ex_fss, fss') = splitAt n_ex fss
798 (co_fss, id_fss) = splitAt n_co fss'
800 -- Make existential type variables
801 ex_bndrs = zipWith3 mk_ex_var ex_uniqs ex_fss ex_tvs
802 mk_ex_var uniq fs var = mkTyVar new_name kind
804 new_name = mkSysTvName uniq fs
807 -- Make the instantiating substitution
808 subst = zipOpenTvSubst (univ_tvs ++ ex_tvs) (inst_tys ++ map mkTyVarTy ex_bndrs)
810 -- Make new coercion vars, instantiating kind
811 co_bndrs = zipWith3 mk_co_var co_uniqs co_fss eq_preds
812 mk_co_var uniq fs eq_pred = mkCoVar new_name co_kind
814 new_name = mkSysTvName uniq fs
815 co_kind = substTy subst (mkPredTy eq_pred)
817 -- make value vars, instantiating types
818 mk_id_var uniq fs ty = mkUserLocal (mkVarOccFS fs) uniq (substTy subst ty) noSrcSpan
819 arg_ids = zipWith3 mk_id_var id_uniqs id_fss arg_tys
821 -- | Returns @Just (dc, [x1..xn])@ if the argument expression is
822 -- a constructor application of the form @dc x1 .. xn@
823 exprIsConApp_maybe :: CoreExpr -> Maybe (DataCon, [CoreExpr])
824 exprIsConApp_maybe (Cast expr co)
825 = -- Here we do the KPush reduction rule as described in the FC paper
826 case exprIsConApp_maybe expr of {
828 Just (dc, dc_args) ->
830 -- The transformation applies iff we have
831 -- (C e1 ... en) `cast` co
832 -- where co :: (T t1 .. tn) ~ (T s1 ..sn)
833 -- That is, with a T at the top of both sides
834 -- The left-hand one must be a T, because exprIsConApp returned True
835 -- but the right-hand one might not be. (Though it usually will.)
837 let (from_ty, to_ty) = coercionKind co
838 (from_tc, from_tc_arg_tys) = splitTyConApp from_ty
839 -- The inner one must be a TyConApp
841 case splitTyConApp_maybe to_ty of {
843 Just (to_tc, to_tc_arg_tys)
844 | from_tc /= to_tc -> Nothing
845 -- These two Nothing cases are possible; we might see
846 -- (C x y) `cast` (g :: T a ~ S [a]),
847 -- where S is a type function. In fact, exprIsConApp
848 -- will probably not be called in such circumstances,
849 -- but there't nothing wrong with it
853 tc_arity = tyConArity from_tc
855 (univ_args, rest1) = splitAt tc_arity dc_args
856 (ex_args, rest2) = splitAt n_ex_tvs rest1
857 (co_args_spec, rest3) = splitAt n_cos_spec rest2
858 (co_args_theta, val_args) = splitAt n_cos_theta rest3
860 arg_tys = dataConRepArgTys dc
861 dc_univ_tyvars = dataConUnivTyVars dc
862 dc_ex_tyvars = dataConExTyVars dc
863 dc_eq_spec = dataConEqSpec dc
864 dc_eq_theta = dataConEqTheta dc
865 dc_tyvars = dc_univ_tyvars ++ dc_ex_tyvars
866 n_ex_tvs = length dc_ex_tyvars
867 n_cos_spec = length dc_eq_spec
868 n_cos_theta = length dc_eq_theta
870 -- Make the "theta" from Fig 3 of the paper
871 gammas = decomposeCo tc_arity co
872 new_tys = gammas ++ map (\ (Type t) -> t) ex_args
873 theta = zipOpenTvSubst dc_tyvars new_tys
875 -- First we cast the existential coercion arguments
876 cast_co_spec (tv, ty) co
877 = cast_co_theta (mkEqPred (mkTyVarTy tv, ty)) co
878 cast_co_theta eqPred (Type co)
879 | (ty1, ty2) <- getEqPredTys eqPred
880 = Type $ mkSymCoercion (substTy theta ty1)
882 `mkTransCoercion` (substTy theta ty2)
883 new_co_args = zipWith cast_co_spec dc_eq_spec co_args_spec ++
884 zipWith cast_co_theta dc_eq_theta co_args_theta
886 -- ...and now value arguments
887 new_val_args = zipWith cast_arg arg_tys val_args
888 cast_arg arg_ty arg = mkCoerce (substTy theta arg_ty) arg
891 ASSERT( length univ_args == tc_arity )
892 ASSERT( from_tc == dataConTyCon dc )
893 ASSERT( and (zipWith coreEqType [t | Type t <- univ_args] from_tc_arg_tys) )
894 ASSERT( all isTypeArg (univ_args ++ ex_args) )
895 ASSERT2( equalLength val_args arg_tys, ppr dc $$ ppr dc_tyvars $$ ppr dc_ex_tyvars $$ ppr arg_tys $$ ppr dc_args $$ ppr univ_args $$ ppr ex_args $$ ppr val_args $$ ppr arg_tys )
897 Just (dc, map Type to_tc_arg_tys ++ ex_args ++ new_co_args ++ new_val_args)
901 -- We do not want to tell the world that we have a
902 -- Cons, to *stop* Case of Known Cons, which removes
904 exprIsConApp_maybe (Note (TickBox {}) expr)
906 exprIsConApp_maybe (Note (BinaryTickBox {}) expr)
910 exprIsConApp_maybe (Note _ expr)
911 = exprIsConApp_maybe expr
912 -- We ignore InlineMe notes in case we have
913 -- x = __inline_me__ (a,b)
914 -- All part of making sure that INLINE pragmas never hurt
915 -- Marcin tripped on this one when making dictionaries more inlinable
917 -- In fact, we ignore all notes. For example,
918 -- case _scc_ "foo" (C a b) of
920 -- should be optimised away, but it will be only if we look
921 -- through the SCC note.
923 exprIsConApp_maybe expr = analyse (collectArgs expr)
925 analyse (Var fun, args)
926 | Just con <- isDataConWorkId_maybe fun,
927 args `lengthAtLeast` dataConRepArity con
928 -- Might be > because the arity excludes type args
931 -- Look through unfoldings, but only cheap ones, because
932 -- we are effectively duplicating the unfolding
933 analyse (Var fun, [])
934 | let unf = idUnfolding fun,
935 isExpandableUnfolding unf
936 = exprIsConApp_maybe (unfoldingTemplate unf)
943 %************************************************************************
945 \subsection{Equality}
947 %************************************************************************
950 -- | A cheap equality test which bales out fast!
951 -- If it returns @True@ the arguments are definitely equal,
952 -- otherwise, they may or may not be equal.
954 -- See also 'exprIsBig'
955 cheapEqExpr :: Expr b -> Expr b -> Bool
957 cheapEqExpr (Var v1) (Var v2) = v1==v2
958 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
959 cheapEqExpr (Type t1) (Type t2) = t1 `coreEqType` t2
961 cheapEqExpr (App f1 a1) (App f2 a2)
962 = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
964 cheapEqExpr (Cast e1 t1) (Cast e2 t2)
965 = e1 `cheapEqExpr` e2 && t1 `coreEqCoercion` t2
967 cheapEqExpr _ _ = False
969 exprIsBig :: Expr b -> Bool
970 -- ^ Returns @True@ of expressions that are too big to be compared by 'cheapEqExpr'
971 exprIsBig (Lit _) = False
972 exprIsBig (Var _) = False
973 exprIsBig (Type _) = False
974 exprIsBig (App f a) = exprIsBig f || exprIsBig a
975 exprIsBig (Cast e _) = exprIsBig e -- Hopefully coercions are not too big!
981 %************************************************************************
983 \subsection{The size of an expression}
985 %************************************************************************
988 coreBindsSize :: [CoreBind] -> Int
989 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
991 exprSize :: CoreExpr -> Int
992 -- ^ A measure of the size of the expressions, strictly greater than 0
993 -- It also forces the expression pretty drastically as a side effect
994 exprSize (Var v) = v `seq` 1
995 exprSize (Lit lit) = lit `seq` 1
996 exprSize (App f a) = exprSize f + exprSize a
997 exprSize (Lam b e) = varSize b + exprSize e
998 exprSize (Let b e) = bindSize b + exprSize e
999 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
1000 exprSize (Cast e co) = (seqType co `seq` 1) + exprSize e
1001 exprSize (Note n e) = noteSize n + exprSize e
1002 exprSize (Type t) = seqType t `seq` 1
1004 noteSize :: Note -> Int
1005 noteSize (SCC cc) = cc `seq` 1
1006 noteSize InlineMe = 1
1007 noteSize (CoreNote s) = s `seq` 1 -- hdaume: core annotations
1009 varSize :: Var -> Int
1010 varSize b | isTyVar b = 1
1011 | otherwise = seqType (idType b) `seq`
1012 megaSeqIdInfo (idInfo b) `seq`
1015 varsSize :: [Var] -> Int
1016 varsSize = sum . map varSize
1018 bindSize :: CoreBind -> Int
1019 bindSize (NonRec b e) = varSize b + exprSize e
1020 bindSize (Rec prs) = foldr ((+) . pairSize) 0 prs
1022 pairSize :: (Var, CoreExpr) -> Int
1023 pairSize (b,e) = varSize b + exprSize e
1025 altSize :: CoreAlt -> Int
1026 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
1030 %************************************************************************
1032 \subsection{Hashing}
1034 %************************************************************************
1037 hashExpr :: CoreExpr -> Int
1038 -- ^ Two expressions that hash to the same @Int@ may be equal (but may not be)
1039 -- Two expressions that hash to the different Ints are definitely unequal.
1041 -- The emphasis is on a crude, fast hash, rather than on high precision.
1043 -- But unequal here means \"not identical\"; two alpha-equivalent
1044 -- expressions may hash to the different Ints.
1046 -- We must be careful that @\\x.x@ and @\\y.y@ map to the same hash code,
1047 -- (at least if we want the above invariant to be true).
1049 hashExpr e = fromIntegral (hash_expr (1,emptyVarEnv) e .&. 0x7fffffff)
1050 -- UniqFM doesn't like negative Ints
1052 type HashEnv = (Int, VarEnv Int) -- Hash code for bound variables
1054 hash_expr :: HashEnv -> CoreExpr -> Word32
1055 -- Word32, because we're expecting overflows here, and overflowing
1056 -- signed types just isn't cool. In C it's even undefined.
1057 hash_expr env (Note _ e) = hash_expr env e
1058 hash_expr env (Cast e _) = hash_expr env e
1059 hash_expr env (Var v) = hashVar env v
1060 hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
1061 hash_expr env (App f e) = hash_expr env f * fast_hash_expr env e
1062 hash_expr env (Let (NonRec b r) e) = hash_expr (extend_env env b) e * fast_hash_expr env r
1063 hash_expr env (Let (Rec ((b,_):_)) e) = hash_expr (extend_env env b) e
1064 hash_expr env (Case e _ _ _) = hash_expr env e
1065 hash_expr env (Lam b e) = hash_expr (extend_env env b) e
1066 hash_expr _ (Type _) = WARN(True, text "hash_expr: type") 1
1067 -- Shouldn't happen. Better to use WARN than trace, because trace
1068 -- prevents the CPR optimisation kicking in for hash_expr.
1070 fast_hash_expr :: HashEnv -> CoreExpr -> Word32
1071 fast_hash_expr env (Var v) = hashVar env v
1072 fast_hash_expr env (Type t) = fast_hash_type env t
1073 fast_hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
1074 fast_hash_expr env (Cast e _) = fast_hash_expr env e
1075 fast_hash_expr env (Note _ e) = fast_hash_expr env e
1076 fast_hash_expr env (App _ a) = fast_hash_expr env a -- A bit idiosyncratic ('a' not 'f')!
1077 fast_hash_expr _ _ = 1
1079 fast_hash_type :: HashEnv -> Type -> Word32
1080 fast_hash_type env ty
1081 | Just tv <- getTyVar_maybe ty = hashVar env tv
1082 | Just (tc,tys) <- splitTyConApp_maybe ty = let hash_tc = fromIntegral (hashName (tyConName tc))
1083 in foldr (\t n -> fast_hash_type env t + n) hash_tc tys
1086 extend_env :: HashEnv -> Var -> (Int, VarEnv Int)
1087 extend_env (n,env) b = (n+1, extendVarEnv env b n)
1089 hashVar :: HashEnv -> Var -> Word32
1091 = fromIntegral (lookupVarEnv env v `orElse` hashName (idName v))
1094 %************************************************************************
1096 \subsection{Determining non-updatable right-hand-sides}
1098 %************************************************************************
1100 Top-level constructor applications can usually be allocated
1101 statically, but they can't if the constructor, or any of the
1102 arguments, come from another DLL (because we can't refer to static
1103 labels in other DLLs).
1105 If this happens we simply make the RHS into an updatable thunk,
1106 and 'execute' it rather than allocating it statically.
1109 -- | This function is called only on *top-level* right-hand sides.
1110 -- Returns @True@ if the RHS can be allocated statically in the output,
1111 -- with no thunks involved at all.
1112 rhsIsStatic :: PackageId -> CoreExpr -> Bool
1113 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1114 -- refers to, CAFs; (ii) in CoreToStg to decide whether to put an
1115 -- update flag on it and (iii) in DsExpr to decide how to expand
1118 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1119 -- (a) a value lambda
1120 -- (b) a saturated constructor application with static args
1122 -- BUT watch out for
1123 -- (i) Any cross-DLL references kill static-ness completely
1124 -- because they must be 'executed' not statically allocated
1125 -- ("DLL" here really only refers to Windows DLLs, on other platforms,
1126 -- this is not necessary)
1128 -- (ii) We treat partial applications as redexes, because in fact we
1129 -- make a thunk for them that runs and builds a PAP
1130 -- at run-time. The only appliations that are treated as
1131 -- static are *saturated* applications of constructors.
1133 -- We used to try to be clever with nested structures like this:
1134 -- ys = (:) w ((:) w [])
1135 -- on the grounds that CorePrep will flatten ANF-ise it later.
1136 -- But supporting this special case made the function much more
1137 -- complicated, because the special case only applies if there are no
1138 -- enclosing type lambdas:
1139 -- ys = /\ a -> Foo (Baz ([] a))
1140 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1142 -- But in fact, even without -O, nested structures at top level are
1143 -- flattened by the simplifier, so we don't need to be super-clever here.
1147 -- f = \x::Int. x+7 TRUE
1148 -- p = (True,False) TRUE
1150 -- d = (fst p, False) FALSE because there's a redex inside
1151 -- (this particular one doesn't happen but...)
1153 -- h = D# (1.0## /## 2.0##) FALSE (redex again)
1154 -- n = /\a. Nil a TRUE
1156 -- t = /\a. (:) (case w a of ...) (Nil a) FALSE (redex)
1159 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1160 -- a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1162 -- b) (C x xs), where C is a contructors is updatable if the application is
1165 -- c) don't look through unfolding of f in (f x).
1167 rhsIsStatic _this_pkg rhs = is_static False rhs
1169 is_static :: Bool -- True <=> in a constructor argument; must be atomic
1172 is_static False (Lam b e) = isRuntimeVar b || is_static False e
1174 is_static _ (Note (SCC _) _) = False
1175 is_static in_arg (Note _ e) = is_static in_arg e
1176 is_static in_arg (Cast e _) = is_static in_arg e
1178 is_static _ (Lit lit)
1180 MachLabel _ _ _ -> False
1182 -- A MachLabel (foreign import "&foo") in an argument
1183 -- prevents a constructor application from being static. The
1184 -- reason is that it might give rise to unresolvable symbols
1185 -- in the object file: under Linux, references to "weak"
1186 -- symbols from the data segment give rise to "unresolvable
1187 -- relocation" errors at link time This might be due to a bug
1188 -- in the linker, but we'll work around it here anyway.
1191 is_static in_arg other_expr = go other_expr 0
1193 go (Var f) n_val_args
1194 #if mingw32_TARGET_OS
1195 | not (isDllName _this_pkg (idName f))
1197 = saturated_data_con f n_val_args
1198 || (in_arg && n_val_args == 0)
1199 -- A naked un-applied variable is *not* deemed a static RHS
1201 -- Reason: better to update so that the indirection gets shorted
1202 -- out, and the true value will be seen
1203 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1204 -- are always updatable. If you do so, make sure that non-updatable
1205 -- ones have enough space for their static link field!
1207 go (App f a) n_val_args
1208 | isTypeArg a = go f n_val_args
1209 | not in_arg && is_static True a = go f (n_val_args + 1)
1210 -- The (not in_arg) checks that we aren't in a constructor argument;
1211 -- if we are, we don't allow (value) applications of any sort
1213 -- NB. In case you wonder, args are sometimes not atomic. eg.
1214 -- x = D# (1.0## /## 2.0##)
1215 -- can't float because /## can fail.
1217 go (Note (SCC _) _) _ = False
1218 go (Note _ f) n_val_args = go f n_val_args
1219 go (Cast e _) n_val_args = go e n_val_args
1223 saturated_data_con f n_val_args
1224 = case isDataConWorkId_maybe f of
1225 Just dc -> n_val_args == dataConRepArity dc