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 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, exprIsConLike,
32 -- * Expression and bindings size
33 coreBindsSize, exprSize,
41 -- * Manipulating data constructors and types
42 applyTypeToArgs, applyTypeToArg,
43 dataConOrigInstPat, dataConRepInstPat, dataConRepFSInstPat
46 #include "HsVersions.h"
79 %************************************************************************
81 \subsection{Find the type of a Core atom/expression}
83 %************************************************************************
86 exprType :: CoreExpr -> Type
87 -- ^ Recover the type of a well-typed Core expression. Fails when
88 -- applied to the actual 'CoreSyn.Type' expression as it cannot
89 -- really be said to have a type
90 exprType (Var var) = idType var
91 exprType (Lit lit) = literalType lit
92 exprType (Let _ body) = exprType body
93 exprType (Case _ _ ty _) = ty
94 exprType (Cast _ co) = snd (coercionKind co)
95 exprType (Note _ e) = exprType e
96 exprType (Lam binder expr) = mkPiType binder (exprType expr)
98 = case collectArgs e of
99 (fun, args) -> applyTypeToArgs e (exprType fun) args
101 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
103 coreAltType :: CoreAlt -> Type
104 -- ^ Returns the type of the alternatives right hand side
105 coreAltType (_,bs,rhs)
106 | any bad_binder bs = expandTypeSynonyms ty
107 | otherwise = ty -- Note [Existential variables and silly type synonyms]
110 free_tvs = tyVarsOfType ty
111 bad_binder b = isTyVar b && b `elemVarSet` free_tvs
113 coreAltsType :: [CoreAlt] -> Type
114 -- ^ Returns the type of the first alternative, which should be the same as for all alternatives
115 coreAltsType (alt:_) = coreAltType alt
116 coreAltsType [] = panic "corAltsType"
119 Note [Existential variables and silly type synonyms]
120 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
122 data T = forall a. T (Funny a)
127 Now, the type of 'x' is (Funny a), where 'a' is existentially quantified.
128 That means that 'exprType' and 'coreAltsType' may give a result that *appears*
129 to mention an out-of-scope type variable. See Trac #3409 for a more real-world
132 Various possibilities suggest themselves:
134 - Ignore the problem, and make Lint not complain about such variables
136 - Expand all type synonyms (or at least all those that discard arguments)
137 This is tricky, because at least for top-level things we want to
138 retain the type the user originally specified.
140 - Expand synonyms on the fly, when the problem arises. That is what
141 we are doing here. It's not too expensive, I think.
144 mkPiType :: Var -> Type -> Type
145 -- ^ Makes a @(->)@ type or a forall type, depending
146 -- on whether it is given a type variable or a term variable.
147 mkPiTypes :: [Var] -> Type -> Type
148 -- ^ 'mkPiType' for multiple type or value arguments
151 | isId v = mkFunTy (idType v) ty
152 | otherwise = mkForAllTy v ty
154 mkPiTypes vs ty = foldr mkPiType ty vs
158 applyTypeToArg :: Type -> CoreExpr -> Type
159 -- ^ Determines the type resulting from applying an expression to a function with the given type
160 applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
161 applyTypeToArg fun_ty _ = funResultTy fun_ty
163 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
164 -- ^ A more efficient version of 'applyTypeToArg' when we have several arguments.
165 -- The first argument is just for debugging, and gives some context
166 applyTypeToArgs _ op_ty [] = op_ty
168 applyTypeToArgs e op_ty (Type ty : args)
169 = -- Accumulate type arguments so we can instantiate all at once
172 go rev_tys (Type ty : args) = go (ty:rev_tys) args
173 go rev_tys rest_args = applyTypeToArgs e op_ty' rest_args
175 op_ty' = applyTysD msg op_ty (reverse rev_tys)
176 msg = ptext (sLit "applyTypeToArgs") <+>
179 applyTypeToArgs e op_ty (_ : args)
180 = case (splitFunTy_maybe op_ty) of
181 Just (_, res_ty) -> applyTypeToArgs e res_ty args
182 Nothing -> pprPanic "applyTypeToArgs" (panic_msg e op_ty)
184 panic_msg :: CoreExpr -> Type -> SDoc
185 panic_msg e op_ty = pprCoreExpr e $$ ppr op_ty
188 %************************************************************************
190 \subsection{Attaching notes}
192 %************************************************************************
195 -- | Wrap the given expression in the coercion, dropping identity coercions and coalescing nested coercions
196 mkCoerceI :: CoercionI -> CoreExpr -> CoreExpr
198 mkCoerceI (ACo co) e = mkCoerce co e
200 -- | Wrap the given expression in the coercion safely, coalescing nested coercions
201 mkCoerce :: Coercion -> CoreExpr -> CoreExpr
202 mkCoerce co (Cast expr co2)
203 = ASSERT(let { (from_ty, _to_ty) = coercionKind co;
204 (_from_ty2, to_ty2) = coercionKind co2} in
205 from_ty `coreEqType` to_ty2 )
206 mkCoerce (mkTransCoercion co2 co) expr
209 = let (from_ty, _to_ty) = coercionKind co in
210 -- if to_ty `coreEqType` from_ty
213 WARN(not (from_ty `coreEqType` exprType expr), text "Trying to coerce" <+> text "(" <> ppr expr $$ text "::" <+> ppr (exprType expr) <> text ")" $$ ppr co $$ pprEqPred (coercionKind co))
218 -- | Wraps the given expression in the cost centre unless
219 -- in a way that maximises their utility to the user
220 mkSCC :: CostCentre -> Expr b -> Expr b
221 -- Note: Nested SCC's *are* preserved for the benefit of
222 -- cost centre stack profiling
223 mkSCC _ (Lit lit) = Lit lit
224 mkSCC cc (Lam x e) = Lam x (mkSCC cc e) -- Move _scc_ inside lambda
225 mkSCC cc (Note (SCC cc') e) = Note (SCC cc) (Note (SCC cc') e)
226 mkSCC cc (Note n e) = Note n (mkSCC cc e) -- Move _scc_ inside notes
227 mkSCC cc (Cast e co) = Cast (mkSCC cc e) co -- Move _scc_ inside cast
228 mkSCC cc expr = Note (SCC cc) expr
232 %************************************************************************
234 \subsection{Other expression construction}
236 %************************************************************************
239 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
240 -- ^ @bindNonRec x r b@ produces either:
246 -- > case r of x { _DEFAULT_ -> b }
248 -- depending on whether we have to use a @case@ or @let@
249 -- binding for the expression (see 'needsCaseBinding').
250 -- It's used by the desugarer to avoid building bindings
251 -- that give Core Lint a heart attack, although actually
252 -- the simplifier deals with them perfectly well. See
253 -- also 'MkCore.mkCoreLet'
254 bindNonRec bndr rhs body
255 | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
256 | otherwise = Let (NonRec bndr rhs) body
258 -- | Tests whether we have to use a @case@ rather than @let@ binding for this expression
259 -- as per the invariants of 'CoreExpr': see "CoreSyn#let_app_invariant"
260 needsCaseBinding :: Type -> CoreExpr -> Bool
261 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
262 -- Make a case expression instead of a let
263 -- These can arise either from the desugarer,
264 -- or from beta reductions: (\x.e) (x +# y)
268 mkAltExpr :: AltCon -- ^ Case alternative constructor
269 -> [CoreBndr] -- ^ Things bound by the pattern match
270 -> [Type] -- ^ The type arguments to the case alternative
272 -- ^ This guy constructs the value that the scrutinee must have
273 -- given that you are in one particular branch of a case
274 mkAltExpr (DataAlt con) args inst_tys
275 = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
276 mkAltExpr (LitAlt lit) [] []
278 mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
279 mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
283 %************************************************************************
285 \subsection{Taking expressions apart}
287 %************************************************************************
289 The default alternative must be first, if it exists at all.
290 This makes it easy to find, though it makes matching marginally harder.
293 -- | Extract the default case alternative
294 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
295 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
296 findDefault alts = (alts, Nothing)
298 isDefaultAlt :: CoreAlt -> Bool
299 isDefaultAlt (DEFAULT, _, _) = True
300 isDefaultAlt _ = False
303 -- | Find the case alternative corresponding to a particular
304 -- constructor: panics if no such constructor exists
305 findAlt :: AltCon -> [CoreAlt] -> Maybe CoreAlt
306 -- A "Nothing" result *is* legitmiate
307 -- See Note [Unreachable code]
310 (deflt@(DEFAULT,_,_):alts) -> go alts (Just deflt)
314 go (alt@(con1,_,_) : alts) deflt
315 = case con `cmpAltCon` con1 of
316 LT -> deflt -- Missed it already; the alts are in increasing order
318 GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
320 ---------------------------------
321 mergeAlts :: [CoreAlt] -> [CoreAlt] -> [CoreAlt]
322 -- ^ Merge alternatives preserving order; alternatives in
323 -- the first argument shadow ones in the second
324 mergeAlts [] as2 = as2
325 mergeAlts as1 [] = as1
326 mergeAlts (a1:as1) (a2:as2)
327 = case a1 `cmpAlt` a2 of
328 LT -> a1 : mergeAlts as1 (a2:as2)
329 EQ -> a1 : mergeAlts as1 as2 -- Discard a2
330 GT -> a2 : mergeAlts (a1:as1) as2
333 ---------------------------------
334 trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
337 -- > case (C a b x y) of
340 -- We want to drop the leading type argument of the scrutinee
341 -- leaving the arguments to match agains the pattern
343 trimConArgs DEFAULT args = ASSERT( null args ) []
344 trimConArgs (LitAlt _) args = ASSERT( null args ) []
345 trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
348 Note [Unreachable code]
349 ~~~~~~~~~~~~~~~~~~~~~~~
350 It is possible (although unusual) for GHC to find a case expression
351 that cannot match. For example:
353 data Col = Red | Green | Blue
357 _ -> ...(case x of { Green -> e1; Blue -> e2 })...
359 Suppose that for some silly reason, x isn't substituted in the case
360 expression. (Perhaps there's a NOINLINE on it, or profiling SCC stuff
361 gets in the way; cf Trac #3118.) Then the full-lazines pass might produce
365 lvl = case x of { Green -> e1; Blue -> e2 })
370 Now if x gets inlined, we won't be able to find a matching alternative
371 for 'Red'. That's because 'lvl' is unreachable. So rather than crashing
372 we generate (error "Inaccessible alternative").
374 Similar things can happen (augmented by GADTs) when the Simplifier
375 filters down the matching alternatives in Simplify.rebuildCase.
378 %************************************************************************
382 %************************************************************************
386 @exprIsTrivial@ is true of expressions we are unconditionally happy to
387 duplicate; simple variables and constants, and type
388 applications. Note that primop Ids aren't considered
391 Note [Variable are trivial]
392 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
393 There used to be a gruesome test for (hasNoBinding v) in the
395 exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
396 The idea here is that a constructor worker, like \$wJust, is
397 really short for (\x -> \$wJust x), becuase \$wJust has no binding.
398 So it should be treated like a lambda. Ditto unsaturated primops.
399 But now constructor workers are not "have-no-binding" Ids. And
400 completely un-applied primops and foreign-call Ids are sufficiently
401 rare that I plan to allow them to be duplicated and put up with
404 Note [SCCs are trivial]
405 ~~~~~~~~~~~~~~~~~~~~~~~
406 We used not to treat (_scc_ "foo" x) as trivial, because it really
407 generates code, (and a heap object when it's a function arg) to
408 capture the cost centre. However, the profiling system discounts the
409 allocation costs for such "boxing thunks" whereas the extra costs of
410 *not* inlining otherwise-trivial bindings can be high, and are hard to
414 exprIsTrivial :: CoreExpr -> Bool
415 exprIsTrivial (Var _) = True -- See Note [Variables are trivial]
416 exprIsTrivial (Type _) = True
417 exprIsTrivial (Lit lit) = litIsTrivial lit
418 exprIsTrivial (App e arg) = not (isRuntimeArg arg) && exprIsTrivial e
419 exprIsTrivial (Note _ e) = exprIsTrivial e -- See Note [SCCs are trivial]
420 exprIsTrivial (Cast e _) = exprIsTrivial e
421 exprIsTrivial (Lam b body) = not (isRuntimeVar b) && exprIsTrivial body
422 exprIsTrivial _ = False
426 %************************************************************************
430 %************************************************************************
434 @exprIsDupable@ is true of expressions that can be duplicated at a modest
435 cost in code size. This will only happen in different case
436 branches, so there's no issue about duplicating work.
438 That is, exprIsDupable returns True of (f x) even if
439 f is very very expensive to call.
441 Its only purpose is to avoid fruitless let-binding
442 and then inlining of case join points
446 exprIsDupable :: CoreExpr -> Bool
447 exprIsDupable (Type _) = True
448 exprIsDupable (Var _) = True
449 exprIsDupable (Lit lit) = litIsDupable lit
450 exprIsDupable (Note _ e) = exprIsDupable e
451 exprIsDupable (Cast e _) = exprIsDupable e
456 go (App f a) n_args = n_args < dupAppSize
462 dupAppSize = 4 -- Size of application we are prepared to duplicate
465 %************************************************************************
467 exprIsCheap, exprIsExpandable
469 %************************************************************************
473 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
474 it is obviously in weak head normal form, or is cheap to get to WHNF.
475 [Note that that's not the same as exprIsDupable; an expression might be
476 big, and hence not dupable, but still cheap.]
478 By ``cheap'' we mean a computation we're willing to:
479 push inside a lambda, or
480 inline at more than one place
481 That might mean it gets evaluated more than once, instead of being
482 shared. The main examples of things which aren't WHNF but are
487 (where e, and all the ei are cheap)
490 (where e and b are cheap)
493 (where op is a cheap primitive operator)
496 (because we are happy to substitute it inside a lambda)
498 Notice that a variable is considered 'cheap': we can push it inside a lambda,
499 because sharing will make sure it is only evaluated once.
502 exprIsCheap' :: (Id -> Bool) -> CoreExpr -> Bool
503 exprIsCheap' _ (Lit _) = True
504 exprIsCheap' _ (Type _) = True
505 exprIsCheap' _ (Var _) = True
506 exprIsCheap' is_conlike (Note _ e) = exprIsCheap' is_conlike e
507 exprIsCheap' is_conlike (Cast e _) = exprIsCheap' is_conlike e
508 exprIsCheap' is_conlike (Lam x e) = isRuntimeVar x
509 || exprIsCheap' is_conlike e
510 exprIsCheap' is_conlike (Case e _ _ alts) = exprIsCheap' is_conlike e &&
511 and [exprIsCheap' is_conlike rhs | (_,_,rhs) <- alts]
512 -- Experimentally, treat (case x of ...) as cheap
513 -- (and case __coerce x etc.)
514 -- This improves arities of overloaded functions where
515 -- there is only dictionary selection (no construction) involved
516 exprIsCheap' is_conlike (Let (NonRec x _) e)
517 | isUnLiftedType (idType x) = exprIsCheap' is_conlike e
519 -- strict lets always have cheap right hand sides,
520 -- and do no allocation.
522 exprIsCheap' is_conlike other_expr -- Applications and variables
525 -- Accumulate value arguments, then decide
526 go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
527 | otherwise = go f val_args
529 go (Var _) [] = True -- Just a type application of a variable
530 -- (f t1 t2 t3) counts as WHNF
532 = case idDetails f of
533 RecSelId {} -> go_sel args
534 ClassOpId {} -> go_sel args
535 PrimOpId op -> go_primop op args
537 _ | is_conlike f -> go_pap args
538 | length args < idArity f -> go_pap args
541 -- Application of a function which
542 -- always gives bottom; we treat this as cheap
543 -- because it certainly doesn't need to be shared!
548 go_pap args = all exprIsTrivial args
549 -- For constructor applications and primops, check that all
550 -- the args are trivial. We don't want to treat as cheap, say,
552 -- We'll put up with one constructor application, but not dozens
555 go_primop op args = primOpIsCheap op && all (exprIsCheap' is_conlike) args
556 -- In principle we should worry about primops
557 -- that return a type variable, since the result
558 -- might be applied to something, but I'm not going
559 -- to bother to check the number of args
562 go_sel [arg] = exprIsCheap' is_conlike arg -- I'm experimenting with making record selection
563 go_sel _ = False -- look cheap, so we will substitute it inside a
564 -- lambda. Particularly for dictionary field selection.
565 -- BUT: Take care with (sel d x)! The (sel d) might be cheap, but
566 -- there's no guarantee that (sel d x) will be too. Hence (n_val_args == 1)
568 exprIsCheap :: CoreExpr -> Bool
569 exprIsCheap = exprIsCheap' isDataConWorkId
571 exprIsExpandable :: CoreExpr -> Bool
572 exprIsExpandable = exprIsCheap' isConLikeId -- See Note [CONLIKE pragma] in BasicTypes
575 %************************************************************************
579 %************************************************************************
582 -- | 'exprOkForSpeculation' returns True of an expression that is:
584 -- * Safe to evaluate even if normal order eval might not
585 -- evaluate the expression at all, or
587 -- * Safe /not/ to evaluate even if normal order would do so
589 -- Precisely, it returns @True@ iff:
591 -- * The expression guarantees to terminate,
595 -- * without raising an exception,
597 -- * without causing a side effect (e.g. writing a mutable variable)
599 -- Note that if @exprIsHNF e@, then @exprOkForSpecuation e@.
600 -- As an example of the considerations in this test, consider:
602 -- > let x = case y# +# 1# of { r# -> I# r# }
605 -- being translated to:
607 -- > case y# +# 1# of { r# ->
612 -- We can only do this if the @y + 1@ is ok for speculation: it has no
613 -- side effects, and can't diverge or raise an exception.
614 exprOkForSpeculation :: CoreExpr -> Bool
615 exprOkForSpeculation (Lit _) = True
616 exprOkForSpeculation (Type _) = True
617 -- Tick boxes are *not* suitable for speculation
618 exprOkForSpeculation (Var v) = isUnLiftedType (idType v)
619 && not (isTickBoxOp v)
620 exprOkForSpeculation (Note _ e) = exprOkForSpeculation e
621 exprOkForSpeculation (Cast e _) = exprOkForSpeculation e
622 exprOkForSpeculation other_expr
623 = case collectArgs other_expr of
624 (Var f, args) -> spec_ok (idDetails f) args
628 spec_ok (DataConWorkId _) _
629 = True -- The strictness of the constructor has already
630 -- been expressed by its "wrapper", so we don't need
631 -- to take the arguments into account
633 spec_ok (PrimOpId op) args
634 | isDivOp op, -- Special case for dividing operations that fail
635 [arg1, Lit lit] <- args -- only if the divisor is zero
636 = not (isZeroLit lit) && exprOkForSpeculation arg1
637 -- Often there is a literal divisor, and this
638 -- can get rid of a thunk in an inner looop
641 = primOpOkForSpeculation op &&
642 all exprOkForSpeculation args
643 -- A bit conservative: we don't really need
644 -- to care about lazy arguments, but this is easy
646 spec_ok (DFunId new_type) _ = not new_type
647 -- DFuns terminate, unless the dict is implemented with a newtype
648 -- in which case they may not
652 -- | True of dyadic operators that can fail only if the second arg is zero!
653 isDivOp :: PrimOp -> Bool
654 -- This function probably belongs in PrimOp, or even in
655 -- an automagically generated file.. but it's such a
656 -- special case I thought I'd leave it here for now.
657 isDivOp IntQuotOp = True
658 isDivOp IntRemOp = True
659 isDivOp WordQuotOp = True
660 isDivOp WordRemOp = True
661 isDivOp FloatDivOp = True
662 isDivOp DoubleDivOp = True
666 %************************************************************************
668 exprIsHNF, exprIsConLike
670 %************************************************************************
675 -- | exprIsHNF returns true for expressions that are certainly /already/
676 -- evaluated to /head/ normal form. This is used to decide whether it's ok
679 -- > case x of _ -> e
685 -- and to decide whether it's safe to discard a 'seq'.
687 -- So, it does /not/ treat variables as evaluated, unless they say they are.
688 -- However, it /does/ treat partial applications and constructor applications
689 -- as values, even if their arguments are non-trivial, provided the argument
690 -- type is lifted. For example, both of these are values:
692 -- > (:) (f x) (map f xs)
693 -- > map (...redex...)
695 -- because 'seq' on such things completes immediately.
697 -- For unlifted argument types, we have to be careful:
701 -- Suppose @f x@ diverges; then @C (f x)@ is not a value. However this can't
702 -- happen: see "CoreSyn#let_app_invariant". This invariant states that arguments of
703 -- unboxed type must be ok-for-speculation (or trivial).
704 exprIsHNF :: CoreExpr -> Bool -- True => Value-lambda, constructor, PAP
705 exprIsHNF = exprIsHNFlike isDataConWorkId isEvaldUnfolding
709 -- | Similar to 'exprIsHNF' but includes CONLIKE functions as well as
710 -- data constructors. Conlike arguments are considered interesting by the
712 exprIsConLike :: CoreExpr -> Bool -- True => lambda, conlike, PAP
713 exprIsConLike = exprIsHNFlike isConLikeId isConLikeUnfolding
715 -- | Returns true for values or value-like expressions. These are lambdas,
716 -- constructors / CONLIKE functions (as determined by the function argument)
719 exprIsHNFlike :: (Var -> Bool) -> (Unfolding -> Bool) -> CoreExpr -> Bool
720 exprIsHNFlike is_con is_con_unf = is_hnf_like
722 is_hnf_like (Var v) -- NB: There are no value args at this point
723 = is_con v -- Catches nullary constructors,
724 -- so that [] and () are values, for example
725 || idArity v > 0 -- Catches (e.g.) primops that don't have unfoldings
726 || is_con_unf (idUnfolding v)
727 -- Check the thing's unfolding; it might be bound to a value
728 -- A worry: what if an Id's unfolding is just itself:
729 -- then we could get an infinite loop...
731 is_hnf_like (Lit _) = True
732 is_hnf_like (Type _) = True -- Types are honorary Values;
733 -- we don't mind copying them
734 is_hnf_like (Lam b e) = isRuntimeVar b || is_hnf_like e
735 is_hnf_like (Note _ e) = is_hnf_like e
736 is_hnf_like (Cast e _) = is_hnf_like e
737 is_hnf_like (App e (Type _)) = is_hnf_like e
738 is_hnf_like (App e a) = app_is_value e [a]
739 is_hnf_like (Let _ e) = is_hnf_like e -- Lazy let(rec)s don't affect us
740 is_hnf_like _ = False
742 -- There is at least one value argument
743 app_is_value :: CoreExpr -> [CoreArg] -> Bool
744 app_is_value (Var fun) args
745 = idArity fun > valArgCount args -- Under-applied function
746 || is_con fun -- or constructor-like
747 app_is_value (Note _ f) as = app_is_value f as
748 app_is_value (Cast f _) as = app_is_value f as
749 app_is_value (App f a) as = app_is_value f (a:as)
750 app_is_value _ _ = False
754 %************************************************************************
756 Instantiating data constructors
758 %************************************************************************
760 These InstPat functions go here to avoid circularity between DataCon and Id
763 dataConRepInstPat, dataConOrigInstPat :: [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
764 dataConRepFSInstPat :: [FastString] -> [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
766 dataConRepInstPat = dataConInstPat dataConRepArgTys (repeat ((fsLit "ipv")))
767 dataConRepFSInstPat = dataConInstPat dataConRepArgTys
768 dataConOrigInstPat = dataConInstPat dc_arg_tys (repeat ((fsLit "ipv")))
770 dc_arg_tys dc = map mkPredTy (dataConEqTheta dc) ++ map mkPredTy (dataConDictTheta dc) ++ dataConOrigArgTys dc
771 -- Remember to include the existential dictionaries
773 dataConInstPat :: (DataCon -> [Type]) -- function used to find arg tys
774 -> [FastString] -- A long enough list of FSs to use for names
775 -> [Unique] -- An equally long list of uniques, at least one for each binder
777 -> [Type] -- Types to instantiate the universally quantified tyvars
778 -> ([TyVar], [CoVar], [Id]) -- Return instantiated variables
779 -- dataConInstPat arg_fun fss us con inst_tys returns a triple
780 -- (ex_tvs, co_tvs, arg_ids),
782 -- ex_tvs are intended to be used as binders for existential type args
784 -- co_tvs are intended to be used as binders for coercion args and the kinds
785 -- of these vars have been instantiated by the inst_tys and the ex_tys
786 -- The co_tvs include both GADT equalities (dcEqSpec) and
787 -- programmer-specified equalities (dcEqTheta)
789 -- arg_ids are indended to be used as binders for value arguments,
790 -- and their types have been instantiated with inst_tys and ex_tys
791 -- The arg_ids include both dicts (dcDictTheta) and
792 -- programmer-specified arguments (after rep-ing) (deRepArgTys)
795 -- The following constructor T1
798 -- T1 :: forall b. Int -> b -> T(a,b)
801 -- has representation type
802 -- forall a. forall a1. forall b. (a ~ (a1,b)) =>
805 -- dataConInstPat fss us T1 (a1',b') will return
807 -- ([a1'', b''], [c :: (a1', b')~(a1'', b'')], [x :: Int, y :: b''])
809 -- where the double-primed variables are created with the FastStrings and
810 -- Uniques given as fss and us
811 dataConInstPat arg_fun fss uniqs con inst_tys
812 = (ex_bndrs, co_bndrs, arg_ids)
814 univ_tvs = dataConUnivTyVars con
815 ex_tvs = dataConExTyVars con
816 arg_tys = arg_fun con
817 eq_spec = dataConEqSpec con
818 eq_theta = dataConEqTheta con
819 eq_preds = eqSpecPreds eq_spec ++ eq_theta
822 n_co = length eq_preds
824 -- split the Uniques and FastStrings
825 (ex_uniqs, uniqs') = splitAt n_ex uniqs
826 (co_uniqs, id_uniqs) = splitAt n_co uniqs'
828 (ex_fss, fss') = splitAt n_ex fss
829 (co_fss, id_fss) = splitAt n_co fss'
831 -- Make existential type variables
832 ex_bndrs = zipWith3 mk_ex_var ex_uniqs ex_fss ex_tvs
833 mk_ex_var uniq fs var = mkTyVar new_name kind
835 new_name = mkSysTvName uniq fs
838 -- Make the instantiating substitution
839 subst = zipOpenTvSubst (univ_tvs ++ ex_tvs) (inst_tys ++ map mkTyVarTy ex_bndrs)
841 -- Make new coercion vars, instantiating kind
842 co_bndrs = zipWith3 mk_co_var co_uniqs co_fss eq_preds
843 mk_co_var uniq fs eq_pred = mkCoVar new_name co_kind
845 new_name = mkSysTvName uniq fs
846 co_kind = substTy subst (mkPredTy eq_pred)
848 -- make value vars, instantiating types
849 mk_id_var uniq fs ty = mkUserLocal (mkVarOccFS fs) uniq (substTy subst ty) noSrcSpan
850 arg_ids = zipWith3 mk_id_var id_uniqs id_fss arg_tys
854 %************************************************************************
858 %************************************************************************
861 -- | A cheap equality test which bales out fast!
862 -- If it returns @True@ the arguments are definitely equal,
863 -- otherwise, they may or may not be equal.
865 -- See also 'exprIsBig'
866 cheapEqExpr :: Expr b -> Expr b -> Bool
868 cheapEqExpr (Var v1) (Var v2) = v1==v2
869 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
870 cheapEqExpr (Type t1) (Type t2) = t1 `coreEqType` t2
872 cheapEqExpr (App f1 a1) (App f2 a2)
873 = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
875 cheapEqExpr (Cast e1 t1) (Cast e2 t2)
876 = e1 `cheapEqExpr` e2 && t1 `coreEqCoercion` t2
878 cheapEqExpr _ _ = False
880 exprIsBig :: Expr b -> Bool
881 -- ^ Returns @True@ of expressions that are too big to be compared by 'cheapEqExpr'
882 exprIsBig (Lit _) = False
883 exprIsBig (Var _) = False
884 exprIsBig (Type _) = False
885 exprIsBig (Lam _ e) = exprIsBig e
886 exprIsBig (App f a) = exprIsBig f || exprIsBig a
887 exprIsBig (Cast e _) = exprIsBig e -- Hopefully coercions are not too big!
893 %************************************************************************
895 \subsection{The size of an expression}
897 %************************************************************************
900 coreBindsSize :: [CoreBind] -> Int
901 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
903 exprSize :: CoreExpr -> Int
904 -- ^ A measure of the size of the expressions, strictly greater than 0
905 -- It also forces the expression pretty drastically as a side effect
906 exprSize (Var v) = v `seq` 1
907 exprSize (Lit lit) = lit `seq` 1
908 exprSize (App f a) = exprSize f + exprSize a
909 exprSize (Lam b e) = varSize b + exprSize e
910 exprSize (Let b e) = bindSize b + exprSize e
911 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
912 exprSize (Cast e co) = (seqType co `seq` 1) + exprSize e
913 exprSize (Note n e) = noteSize n + exprSize e
914 exprSize (Type t) = seqType t `seq` 1
916 noteSize :: Note -> Int
917 noteSize (SCC cc) = cc `seq` 1
918 noteSize (CoreNote s) = s `seq` 1 -- hdaume: core annotations
920 varSize :: Var -> Int
921 varSize b | isTyVar b = 1
922 | otherwise = seqType (idType b) `seq`
923 megaSeqIdInfo (idInfo b) `seq`
926 varsSize :: [Var] -> Int
927 varsSize = sum . map varSize
929 bindSize :: CoreBind -> Int
930 bindSize (NonRec b e) = varSize b + exprSize e
931 bindSize (Rec prs) = foldr ((+) . pairSize) 0 prs
933 pairSize :: (Var, CoreExpr) -> Int
934 pairSize (b,e) = varSize b + exprSize e
936 altSize :: CoreAlt -> Int
937 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
941 %************************************************************************
945 %************************************************************************
948 hashExpr :: CoreExpr -> Int
949 -- ^ Two expressions that hash to the same @Int@ may be equal (but may not be)
950 -- Two expressions that hash to the different Ints are definitely unequal.
952 -- The emphasis is on a crude, fast hash, rather than on high precision.
954 -- But unequal here means \"not identical\"; two alpha-equivalent
955 -- expressions may hash to the different Ints.
957 -- We must be careful that @\\x.x@ and @\\y.y@ map to the same hash code,
958 -- (at least if we want the above invariant to be true).
960 hashExpr e = fromIntegral (hash_expr (1,emptyVarEnv) e .&. 0x7fffffff)
961 -- UniqFM doesn't like negative Ints
963 type HashEnv = (Int, VarEnv Int) -- Hash code for bound variables
965 hash_expr :: HashEnv -> CoreExpr -> Word32
966 -- Word32, because we're expecting overflows here, and overflowing
967 -- signed types just isn't cool. In C it's even undefined.
968 hash_expr env (Note _ e) = hash_expr env e
969 hash_expr env (Cast e _) = hash_expr env e
970 hash_expr env (Var v) = hashVar env v
971 hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
972 hash_expr env (App f e) = hash_expr env f * fast_hash_expr env e
973 hash_expr env (Let (NonRec b r) e) = hash_expr (extend_env env b) e * fast_hash_expr env r
974 hash_expr env (Let (Rec ((b,_):_)) e) = hash_expr (extend_env env b) e
975 hash_expr env (Case e _ _ _) = hash_expr env e
976 hash_expr env (Lam b e) = hash_expr (extend_env env b) e
977 hash_expr _ (Type _) = WARN(True, text "hash_expr: type") 1
978 -- Shouldn't happen. Better to use WARN than trace, because trace
979 -- prevents the CPR optimisation kicking in for hash_expr.
981 fast_hash_expr :: HashEnv -> CoreExpr -> Word32
982 fast_hash_expr env (Var v) = hashVar env v
983 fast_hash_expr env (Type t) = fast_hash_type env t
984 fast_hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
985 fast_hash_expr env (Cast e _) = fast_hash_expr env e
986 fast_hash_expr env (Note _ e) = fast_hash_expr env e
987 fast_hash_expr env (App _ a) = fast_hash_expr env a -- A bit idiosyncratic ('a' not 'f')!
988 fast_hash_expr _ _ = 1
990 fast_hash_type :: HashEnv -> Type -> Word32
991 fast_hash_type env ty
992 | Just tv <- getTyVar_maybe ty = hashVar env tv
993 | Just (tc,tys) <- splitTyConApp_maybe ty = let hash_tc = fromIntegral (hashName (tyConName tc))
994 in foldr (\t n -> fast_hash_type env t + n) hash_tc tys
997 extend_env :: HashEnv -> Var -> (Int, VarEnv Int)
998 extend_env (n,env) b = (n+1, extendVarEnv env b n)
1000 hashVar :: HashEnv -> Var -> Word32
1002 = fromIntegral (lookupVarEnv env v `orElse` hashName (idName v))
1005 %************************************************************************
1007 \subsection{Determining non-updatable right-hand-sides}
1009 %************************************************************************
1011 Top-level constructor applications can usually be allocated
1012 statically, but they can't if the constructor, or any of the
1013 arguments, come from another DLL (because we can't refer to static
1014 labels in other DLLs).
1016 If this happens we simply make the RHS into an updatable thunk,
1017 and 'execute' it rather than allocating it statically.
1020 -- | This function is called only on *top-level* right-hand sides.
1021 -- Returns @True@ if the RHS can be allocated statically in the output,
1022 -- with no thunks involved at all.
1023 rhsIsStatic :: PackageId -> CoreExpr -> Bool
1024 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1025 -- refers to, CAFs; (ii) in CoreToStg to decide whether to put an
1026 -- update flag on it and (iii) in DsExpr to decide how to expand
1029 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1030 -- (a) a value lambda
1031 -- (b) a saturated constructor application with static args
1033 -- BUT watch out for
1034 -- (i) Any cross-DLL references kill static-ness completely
1035 -- because they must be 'executed' not statically allocated
1036 -- ("DLL" here really only refers to Windows DLLs, on other platforms,
1037 -- this is not necessary)
1039 -- (ii) We treat partial applications as redexes, because in fact we
1040 -- make a thunk for them that runs and builds a PAP
1041 -- at run-time. The only appliations that are treated as
1042 -- static are *saturated* applications of constructors.
1044 -- We used to try to be clever with nested structures like this:
1045 -- ys = (:) w ((:) w [])
1046 -- on the grounds that CorePrep will flatten ANF-ise it later.
1047 -- But supporting this special case made the function much more
1048 -- complicated, because the special case only applies if there are no
1049 -- enclosing type lambdas:
1050 -- ys = /\ a -> Foo (Baz ([] a))
1051 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1053 -- But in fact, even without -O, nested structures at top level are
1054 -- flattened by the simplifier, so we don't need to be super-clever here.
1058 -- f = \x::Int. x+7 TRUE
1059 -- p = (True,False) TRUE
1061 -- d = (fst p, False) FALSE because there's a redex inside
1062 -- (this particular one doesn't happen but...)
1064 -- h = D# (1.0## /## 2.0##) FALSE (redex again)
1065 -- n = /\a. Nil a TRUE
1067 -- t = /\a. (:) (case w a of ...) (Nil a) FALSE (redex)
1070 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1071 -- a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1073 -- b) (C x xs), where C is a contructor is updatable if the application is
1076 -- c) don't look through unfolding of f in (f x).
1078 rhsIsStatic _this_pkg rhs = is_static False rhs
1080 is_static :: Bool -- True <=> in a constructor argument; must be atomic
1083 is_static False (Lam b e) = isRuntimeVar b || is_static False e
1085 is_static _ (Note (SCC _) _) = False
1086 is_static in_arg (Note _ e) = is_static in_arg e
1087 is_static in_arg (Cast e _) = is_static in_arg e
1089 is_static _ (Lit lit)
1091 MachLabel _ _ _ -> False
1093 -- A MachLabel (foreign import "&foo") in an argument
1094 -- prevents a constructor application from being static. The
1095 -- reason is that it might give rise to unresolvable symbols
1096 -- in the object file: under Linux, references to "weak"
1097 -- symbols from the data segment give rise to "unresolvable
1098 -- relocation" errors at link time This might be due to a bug
1099 -- in the linker, but we'll work around it here anyway.
1102 is_static in_arg other_expr = go other_expr 0
1104 go (Var f) n_val_args
1105 #if mingw32_TARGET_OS
1106 | not (isDllName _this_pkg (idName f))
1108 = saturated_data_con f n_val_args
1109 || (in_arg && n_val_args == 0)
1110 -- A naked un-applied variable is *not* deemed a static RHS
1112 -- Reason: better to update so that the indirection gets shorted
1113 -- out, and the true value will be seen
1114 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1115 -- are always updatable. If you do so, make sure that non-updatable
1116 -- ones have enough space for their static link field!
1118 go (App f a) n_val_args
1119 | isTypeArg a = go f n_val_args
1120 | not in_arg && is_static True a = go f (n_val_args + 1)
1121 -- The (not in_arg) checks that we aren't in a constructor argument;
1122 -- if we are, we don't allow (value) applications of any sort
1124 -- NB. In case you wonder, args are sometimes not atomic. eg.
1125 -- x = D# (1.0## /## 2.0##)
1126 -- can't float because /## can fail.
1128 go (Note (SCC _) _) _ = False
1129 go (Note _ f) n_val_args = go f n_val_args
1130 go (Cast e _) n_val_args = go e n_val_args
1134 saturated_data_con f n_val_args
1135 = case isDataConWorkId_maybe f of
1136 Just dc -> n_val_args == dataConRepArity dc