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
18 mkInlineMe, mkSCC, mkCoerce, mkCoerceI,
19 bindNonRec, needsCaseBinding,
20 mkIfThenElse, mkAltExpr, mkPiType, mkPiTypes,
22 -- Taking expressions apart
23 findDefault, findAlt, isDefaultAlt, mergeAlts, trimConArgs,
25 -- Properties of expressions
26 exprType, coreAltType, coreAltsType,
27 exprIsDupable, exprIsTrivial, exprIsCheap,
28 exprIsHNF,exprOkForSpeculation, exprIsBig,
29 exprIsConApp_maybe, exprIsBottom,
32 -- Arity and eta expansion
33 manifestArity, exprArity,
34 exprEtaExpandArity, etaExpand,
37 coreBindsSize, exprSize,
43 cheapEqExpr, tcEqExpr, tcEqExprX, applyTypeToArgs, applyTypeToArg,
45 dataConOrigInstPat, dataConRepInstPat, dataConRepFSInstPat
48 #include "HsVersions.h"
84 import GHC.Exts -- For `xori`
88 %************************************************************************
90 \subsection{Find the type of a Core atom/expression}
92 %************************************************************************
95 exprType :: CoreExpr -> Type
97 exprType (Var var) = idType var
98 exprType (Lit lit) = literalType lit
99 exprType (Let _ body) = exprType body
100 exprType (Case _ _ ty _) = ty
101 exprType (Cast _ co) = snd (coercionKind co)
102 exprType (Note _ e) = exprType e
103 exprType (Lam binder expr) = mkPiType binder (exprType expr)
105 = case collectArgs e of
106 (fun, args) -> applyTypeToArgs e (exprType fun) args
108 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
110 coreAltType :: CoreAlt -> Type
111 coreAltType (_,_,rhs) = exprType rhs
113 coreAltsType :: [CoreAlt] -> Type
114 coreAltsType (alt:_) = coreAltType alt
115 coreAltsType [] = panic "corAltsType"
118 @mkPiType@ makes a (->) type or a forall type, depending on whether
119 it is given a type variable or a term variable. We cleverly use the
120 lbvarinfo field to figure out the right annotation for the arrove in
121 case of a term variable.
124 mkPiType :: Var -> Type -> Type -- The more polymorphic version
125 mkPiTypes :: [Var] -> Type -> Type -- doesn't work...
127 mkPiTypes vs ty = foldr mkPiType ty vs
130 | isId v = mkFunTy (idType v) ty
131 | otherwise = mkForAllTy v ty
135 applyTypeToArg :: Type -> CoreExpr -> Type
136 applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
137 applyTypeToArg fun_ty _ = funResultTy fun_ty
139 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
140 -- A more efficient version of applyTypeToArg
141 -- when we have several args
142 -- The first argument is just for debugging
143 applyTypeToArgs _ op_ty [] = op_ty
145 applyTypeToArgs e op_ty (Type ty : args)
146 = -- Accumulate type arguments so we can instantiate all at once
149 go rev_tys (Type ty : args) = go (ty:rev_tys) args
150 go rev_tys rest_args = applyTypeToArgs e op_ty' rest_args
152 op_ty' = applyTys op_ty (reverse rev_tys)
154 applyTypeToArgs e op_ty (_ : args)
155 = case (splitFunTy_maybe op_ty) of
156 Just (_, res_ty) -> applyTypeToArgs e res_ty args
157 Nothing -> pprPanic "applyTypeToArgs" (pprCoreExpr e $$ ppr op_ty)
162 %************************************************************************
164 \subsection{Attaching notes}
166 %************************************************************************
168 mkNote removes redundant coercions, and SCCs where possible
172 mkNote :: Note -> CoreExpr -> CoreExpr
173 mkNote (SCC cc) expr = mkSCC cc expr
174 mkNote InlineMe expr = mkInlineMe expr
175 mkNote note expr = Note note expr
179 Drop trivial InlineMe's. This is somewhat important, because if we have an unfolding
180 that looks like (Note InlineMe (Var v)), the InlineMe doesn't go away because it may
181 not be *applied* to anything.
183 We don't use exprIsTrivial here, though, because we sometimes generate worker/wrapper
186 f = inline_me (coerce t fw)
187 As usual, the inline_me prevents the worker from getting inlined back into the wrapper.
188 We want the split, so that the coerces can cancel at the call site.
190 However, we can get left with tiresome type applications. Notably, consider
191 f = /\ a -> let t = e in (t, w)
192 Then lifting the let out of the big lambda gives
194 f = /\ a -> let t = inline_me (t' a) in (t, w)
195 The inline_me is to stop the simplifier inlining t' right back
196 into t's RHS. In the next phase we'll substitute for t (since
197 its rhs is trivial) and *then* we could get rid of the inline_me.
198 But it hardly seems worth it, so I don't bother.
201 mkInlineMe :: CoreExpr -> CoreExpr
202 mkInlineMe (Var v) = Var v
203 mkInlineMe e = Note InlineMe e
209 mkCoerceI :: CoercionI -> CoreExpr -> CoreExpr
211 mkCoerceI (ACo co) e = mkCoerce co e
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 mkSCC :: CostCentre -> Expr b -> Expr b
231 -- Note: Nested SCC's *are* preserved for the benefit of
232 -- cost centre stack profiling
233 mkSCC _ (Lit lit) = Lit lit
234 mkSCC cc (Lam x e) = Lam x (mkSCC cc e) -- Move _scc_ inside lambda
235 mkSCC cc (Note (SCC cc') e) = Note (SCC cc) (Note (SCC cc') e)
236 mkSCC cc (Note n e) = Note n (mkSCC cc e) -- Move _scc_ inside notes
237 mkSCC cc (Cast e co) = Cast (mkSCC cc e) co -- Move _scc_ inside cast
238 mkSCC cc expr = Note (SCC cc) expr
242 %************************************************************************
244 \subsection{Other expression construction}
246 %************************************************************************
249 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
250 -- (bindNonRec x r b) produces either
253 -- case r of x { _DEFAULT_ -> b }
255 -- depending on whether x is unlifted or not
256 -- It's used by the desugarer to avoid building bindings
257 -- that give Core Lint a heart attack. Actually the simplifier
258 -- deals with them perfectly well.
260 bindNonRec bndr rhs body
261 | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT,[],body)]
262 | otherwise = Let (NonRec bndr rhs) body
264 needsCaseBinding :: Type -> CoreExpr -> Bool
265 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
266 -- Make a case expression instead of a let
267 -- These can arise either from the desugarer,
268 -- or from beta reductions: (\x.e) (x +# y)
272 mkAltExpr :: AltCon -> [CoreBndr] -> [Type] -> CoreExpr
273 -- This guy constructs the value that the scrutinee must have
274 -- when you are in one particular branch of a case
275 mkAltExpr (DataAlt con) args inst_tys
276 = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
277 mkAltExpr (LitAlt lit) [] []
279 mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
280 mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
282 mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
283 mkIfThenElse guard then_expr else_expr
284 -- Not going to be refining, so okay to take the type of the "then" clause
285 = Case guard (mkWildId boolTy) (exprType then_expr)
286 [ (DataAlt falseDataCon, [], else_expr), -- Increasing order of tag!
287 (DataAlt trueDataCon, [], then_expr) ]
291 %************************************************************************
293 \subsection{Taking expressions apart}
295 %************************************************************************
297 The default alternative must be first, if it exists at all.
298 This makes it easy to find, though it makes matching marginally harder.
301 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
302 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
303 findDefault alts = (alts, Nothing)
305 findAlt :: AltCon -> [CoreAlt] -> CoreAlt
308 (deflt@(DEFAULT,_,_):alts) -> go alts deflt
309 _ -> go alts panic_deflt
311 panic_deflt = pprPanic "Missing alternative" (ppr con $$ vcat (map ppr alts))
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 isDefaultAlt :: CoreAlt -> Bool
321 isDefaultAlt (DEFAULT, _, _) = True
322 isDefaultAlt _ = False
324 ---------------------------------
325 mergeAlts :: [CoreAlt] -> [CoreAlt] -> [CoreAlt]
326 -- Merge preserving order; alternatives in the first arg
327 -- shadow ones in the second
328 mergeAlts [] as2 = as2
329 mergeAlts as1 [] = as1
330 mergeAlts (a1:as1) (a2:as2)
331 = case a1 `cmpAlt` a2 of
332 LT -> a1 : mergeAlts as1 (a2:as2)
333 EQ -> a1 : mergeAlts as1 as2 -- Discard a2
334 GT -> a2 : mergeAlts (a1:as1) as2
337 ---------------------------------
338 trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
339 -- Given case (C a b x y) of
341 -- we want to drop the leading type argument of the scrutinee
342 -- leaving the arguments to match agains the pattern
344 trimConArgs DEFAULT args = ASSERT( null args ) []
345 trimConArgs (LitAlt _) args = ASSERT( null args ) []
346 trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
350 %************************************************************************
352 \subsection{Figuring out things about expressions}
354 %************************************************************************
356 @exprIsTrivial@ is true of expressions we are unconditionally happy to
357 duplicate; simple variables and constants, and type
358 applications. Note that primop Ids aren't considered
361 @exprIsBottom@ is true of expressions that are guaranteed to diverge
364 There used to be a gruesome test for (hasNoBinding v) in the
366 exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
367 The idea here is that a constructor worker, like $wJust, is
368 really short for (\x -> $wJust x), becuase $wJust has no binding.
369 So it should be treated like a lambda. Ditto unsaturated primops.
370 But now constructor workers are not "have-no-binding" Ids. And
371 completely un-applied primops and foreign-call Ids are sufficiently
372 rare that I plan to allow them to be duplicated and put up with
375 SCC notes. We do not treat (_scc_ "foo" x) as trivial, because
376 a) it really generates code, (and a heap object when it's
377 a function arg) to capture the cost centre
378 b) see the note [SCC-and-exprIsTrivial] in Simplify.simplLazyBind
381 exprIsTrivial :: CoreExpr -> Bool
382 exprIsTrivial (Var _) = True -- See notes above
383 exprIsTrivial (Type _) = True
384 exprIsTrivial (Lit lit) = litIsTrivial lit
385 exprIsTrivial (App e arg) = not (isRuntimeArg arg) && exprIsTrivial e
386 exprIsTrivial (Note (SCC _) _) = False -- See notes above
387 exprIsTrivial (Note _ e) = exprIsTrivial e
388 exprIsTrivial (Cast e _) = exprIsTrivial e
389 exprIsTrivial (Lam b body) = not (isRuntimeVar b) && exprIsTrivial body
390 exprIsTrivial _ = False
394 @exprIsDupable@ is true of expressions that can be duplicated at a modest
395 cost in code size. This will only happen in different case
396 branches, so there's no issue about duplicating work.
398 That is, exprIsDupable returns True of (f x) even if
399 f is very very expensive to call.
401 Its only purpose is to avoid fruitless let-binding
402 and then inlining of case join points
406 exprIsDupable :: CoreExpr -> Bool
407 exprIsDupable (Type _) = True
408 exprIsDupable (Var _) = True
409 exprIsDupable (Lit lit) = litIsDupable lit
410 exprIsDupable (Note InlineMe _) = True
411 exprIsDupable (Note _ e) = exprIsDupable e
412 exprIsDupable (Cast e _) = exprIsDupable e
417 go (App f a) n_args = n_args < dupAppSize
423 dupAppSize = 4 -- Size of application we are prepared to duplicate
426 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
427 it is obviously in weak head normal form, or is cheap to get to WHNF.
428 [Note that that's not the same as exprIsDupable; an expression might be
429 big, and hence not dupable, but still cheap.]
431 By ``cheap'' we mean a computation we're willing to:
432 push inside a lambda, or
433 inline at more than one place
434 That might mean it gets evaluated more than once, instead of being
435 shared. The main examples of things which aren't WHNF but are
440 (where e, and all the ei are cheap)
443 (where e and b are cheap)
446 (where op is a cheap primitive operator)
449 (because we are happy to substitute it inside a lambda)
451 Notice that a variable is considered 'cheap': we can push it inside a lambda,
452 because sharing will make sure it is only evaluated once.
455 exprIsCheap :: CoreExpr -> Bool
456 exprIsCheap (Lit _) = True
457 exprIsCheap (Type _) = True
458 exprIsCheap (Var _) = True
459 exprIsCheap (Note InlineMe _) = True
460 exprIsCheap (Note _ e) = exprIsCheap e
461 exprIsCheap (Cast e _) = exprIsCheap e
462 exprIsCheap (Lam x e) = isRuntimeVar x || exprIsCheap e
463 exprIsCheap (Case e _ _ alts) = exprIsCheap e &&
464 and [exprIsCheap rhs | (_,_,rhs) <- alts]
465 -- Experimentally, treat (case x of ...) as cheap
466 -- (and case __coerce x etc.)
467 -- This improves arities of overloaded functions where
468 -- there is only dictionary selection (no construction) involved
469 exprIsCheap (Let (NonRec x _) e)
470 | isUnLiftedType (idType x) = exprIsCheap e
472 -- strict lets always have cheap right hand sides,
473 -- and do no allocation.
475 exprIsCheap other_expr -- Applications and variables
478 -- Accumulate value arguments, then decide
479 go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
480 | otherwise = go f val_args
482 go (Var _) [] = True -- Just a type application of a variable
483 -- (f t1 t2 t3) counts as WHNF
485 = case globalIdDetails f of
486 RecordSelId {} -> go_sel args
487 ClassOpId _ -> go_sel args
488 PrimOpId op -> go_primop op args
490 DataConWorkId _ -> go_pap args
491 _ | length args < idArity f -> go_pap args
494 -- Application of a function which
495 -- always gives bottom; we treat this as cheap
496 -- because it certainly doesn't need to be shared!
501 go_pap args = all exprIsTrivial args
502 -- For constructor applications and primops, check that all
503 -- the args are trivial. We don't want to treat as cheap, say,
505 -- We'll put up with one constructor application, but not dozens
508 go_primop op args = primOpIsCheap op && all exprIsCheap args
509 -- In principle we should worry about primops
510 -- that return a type variable, since the result
511 -- might be applied to something, but I'm not going
512 -- to bother to check the number of args
515 go_sel [arg] = exprIsCheap arg -- I'm experimenting with making record selection
516 go_sel _ = False -- look cheap, so we will substitute it inside a
517 -- lambda. Particularly for dictionary field selection.
518 -- BUT: Take care with (sel d x)! The (sel d) might be cheap, but
519 -- there's no guarantee that (sel d x) will be too. Hence (n_val_args == 1)
522 exprOkForSpeculation returns True of an expression that it is
524 * safe to evaluate even if normal order eval might not
525 evaluate the expression at all, or
527 * safe *not* to evaluate even if normal order would do so
531 the expression guarantees to terminate,
533 without raising an exception,
534 without causing a side effect (e.g. writing a mutable variable)
536 NB: if exprIsHNF e, then exprOkForSpecuation e
539 let x = case y# +# 1# of { r# -> I# r# }
542 case y# +# 1# of { r# ->
547 We can only do this if the (y+1) is ok for speculation: it has no
548 side effects, and can't diverge or raise an exception.
551 exprOkForSpeculation :: CoreExpr -> Bool
552 exprOkForSpeculation (Lit _) = True
553 exprOkForSpeculation (Type _) = True
554 -- Tick boxes are *not* suitable for speculation
555 exprOkForSpeculation (Var v) = isUnLiftedType (idType v)
556 && not (isTickBoxOp v)
557 exprOkForSpeculation (Note _ e) = exprOkForSpeculation e
558 exprOkForSpeculation (Cast e _) = exprOkForSpeculation e
559 exprOkForSpeculation other_expr
560 = case collectArgs other_expr of
561 (Var f, args) -> spec_ok (globalIdDetails f) args
565 spec_ok (DataConWorkId _) _
566 = True -- The strictness of the constructor has already
567 -- been expressed by its "wrapper", so we don't need
568 -- to take the arguments into account
570 spec_ok (PrimOpId op) args
571 | isDivOp op, -- Special case for dividing operations that fail
572 [arg1, Lit lit] <- args -- only if the divisor is zero
573 = not (isZeroLit lit) && exprOkForSpeculation arg1
574 -- Often there is a literal divisor, and this
575 -- can get rid of a thunk in an inner looop
578 = primOpOkForSpeculation op &&
579 all exprOkForSpeculation args
580 -- A bit conservative: we don't really need
581 -- to care about lazy arguments, but this is easy
585 isDivOp :: PrimOp -> Bool
586 -- True of dyadic operators that can fail
587 -- only if the second arg is zero
588 -- This function probably belongs in PrimOp, or even in
589 -- an automagically generated file.. but it's such a
590 -- special case I thought I'd leave it here for now.
591 isDivOp IntQuotOp = True
592 isDivOp IntRemOp = True
593 isDivOp WordQuotOp = True
594 isDivOp WordRemOp = True
595 isDivOp IntegerQuotRemOp = True
596 isDivOp IntegerDivModOp = True
597 isDivOp FloatDivOp = True
598 isDivOp DoubleDivOp = True
604 exprIsBottom :: CoreExpr -> Bool -- True => definitely bottom
605 exprIsBottom e = go 0 e
607 -- n is the number of args
608 go n (Note _ e) = go n e
609 go n (Cast e _) = go n e
610 go n (Let _ e) = go n e
611 go _ (Case e _ _ _) = go 0 e -- Just check the scrut
612 go n (App e _) = go (n+1) e
613 go n (Var v) = idAppIsBottom v n
615 go _ (Lam _ _) = False
616 go _ (Type _) = False
618 idAppIsBottom :: Id -> Int -> Bool
619 idAppIsBottom id n_val_args = appIsBottom (idNewStrictness id) n_val_args
622 @exprIsHNF@ returns true for expressions that are certainly *already*
623 evaluated to *head* normal form. This is used to decide whether it's ok
626 case x of _ -> e ===> e
628 and to decide whether it's safe to discard a `seq`
630 So, it does *not* treat variables as evaluated, unless they say they are.
632 But it *does* treat partial applications and constructor applications
633 as values, even if their arguments are non-trivial, provided the argument
635 e.g. (:) (f x) (map f xs) is a value
636 map (...redex...) is a value
637 Because `seq` on such things completes immediately
639 For unlifted argument types, we have to be careful:
641 Suppose (f x) diverges; then C (f x) is not a value. However this can't
642 happen: see CoreSyn Note [CoreSyn let/app invariant]. Args of unboxed
643 type must be ok-for-speculation (or trivial).
646 exprIsHNF :: CoreExpr -> Bool -- True => Value-lambda, constructor, PAP
647 exprIsHNF (Var v) -- NB: There are no value args at this point
648 = isDataConWorkId v -- Catches nullary constructors,
649 -- so that [] and () are values, for example
650 || idArity v > 0 -- Catches (e.g.) primops that don't have unfoldings
651 || isEvaldUnfolding (idUnfolding v)
652 -- Check the thing's unfolding; it might be bound to a value
653 -- A worry: what if an Id's unfolding is just itself:
654 -- then we could get an infinite loop...
656 exprIsHNF (Lit _) = True
657 exprIsHNF (Type _) = True -- Types are honorary Values;
658 -- we don't mind copying them
659 exprIsHNF (Lam b e) = isRuntimeVar b || exprIsHNF e
660 exprIsHNF (Note _ e) = exprIsHNF e
661 exprIsHNF (Cast e _) = exprIsHNF e
662 exprIsHNF (App e (Type _)) = exprIsHNF e
663 exprIsHNF (App e a) = app_is_value e [a]
666 -- There is at least one value argument
667 app_is_value :: CoreExpr -> [CoreArg] -> Bool
668 app_is_value (Var fun) args
669 = idArity fun > valArgCount args -- Under-applied function
670 || isDataConWorkId fun -- or data constructor
671 app_is_value (Note _ f) as = app_is_value f as
672 app_is_value (Cast f _) as = app_is_value f as
673 app_is_value (App f a) as = app_is_value f (a:as)
674 app_is_value _ _ = False
678 dataConRepInstPat, dataConOrigInstPat :: [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
679 dataConRepFSInstPat :: [FastString] -> [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
680 -- These InstPat functions go here to avoid circularity between DataCon and Id
681 dataConRepInstPat = dataConInstPat dataConRepArgTys (repeat ((fsLit "ipv")))
682 dataConRepFSInstPat = dataConInstPat dataConRepArgTys
683 dataConOrigInstPat = dataConInstPat dc_arg_tys (repeat ((fsLit "ipv")))
685 dc_arg_tys dc = map mkPredTy (dataConEqTheta dc) ++ map mkPredTy (dataConDictTheta dc) ++ dataConOrigArgTys dc
686 -- Remember to include the existential dictionaries
688 dataConInstPat :: (DataCon -> [Type]) -- function used to find arg tys
689 -> [FastString] -- A long enough list of FSs to use for names
690 -> [Unique] -- An equally long list of uniques, at least one for each binder
692 -> [Type] -- Types to instantiate the universally quantified tyvars
693 -> ([TyVar], [CoVar], [Id]) -- Return instantiated variables
694 -- dataConInstPat arg_fun fss us con inst_tys returns a triple
695 -- (ex_tvs, co_tvs, arg_ids),
697 -- ex_tvs are intended to be used as binders for existential type args
699 -- co_tvs are intended to be used as binders for coercion args and the kinds
700 -- of these vars have been instantiated by the inst_tys and the ex_tys
701 -- The co_tvs include both GADT equalities (dcEqSpec) and
702 -- programmer-specified equalities (dcEqTheta)
704 -- arg_ids are indended to be used as binders for value arguments,
705 -- and their types have been instantiated with inst_tys and ex_tys
706 -- The arg_ids include both dicts (dcDictTheta) and
707 -- programmer-specified arguments (after rep-ing) (deRepArgTys)
710 -- The following constructor T1
713 -- T1 :: forall b. Int -> b -> T(a,b)
716 -- has representation type
717 -- forall a. forall a1. forall b. (a :=: (a1,b)) =>
720 -- dataConInstPat fss us T1 (a1',b') will return
722 -- ([a1'', b''], [c :: (a1', b'):=:(a1'', b'')], [x :: Int, y :: b''])
724 -- where the double-primed variables are created with the FastStrings and
725 -- Uniques given as fss and us
726 dataConInstPat arg_fun fss uniqs con inst_tys
727 = (ex_bndrs, co_bndrs, arg_ids)
729 univ_tvs = dataConUnivTyVars con
730 ex_tvs = dataConExTyVars con
731 arg_tys = arg_fun con
732 eq_spec = dataConEqSpec con
733 eq_theta = dataConEqTheta con
734 eq_preds = eqSpecPreds eq_spec ++ eq_theta
737 n_co = length eq_preds
739 -- split the Uniques and FastStrings
740 (ex_uniqs, uniqs') = splitAt n_ex uniqs
741 (co_uniqs, id_uniqs) = splitAt n_co uniqs'
743 (ex_fss, fss') = splitAt n_ex fss
744 (co_fss, id_fss) = splitAt n_co fss'
746 -- Make existential type variables
747 ex_bndrs = zipWith3 mk_ex_var ex_uniqs ex_fss ex_tvs
748 mk_ex_var uniq fs var = mkTyVar new_name kind
750 new_name = mkSysTvName uniq fs
753 -- Make the instantiating substitution
754 subst = zipOpenTvSubst (univ_tvs ++ ex_tvs) (inst_tys ++ map mkTyVarTy ex_bndrs)
756 -- Make new coercion vars, instantiating kind
757 co_bndrs = zipWith3 mk_co_var co_uniqs co_fss eq_preds
758 mk_co_var uniq fs eq_pred = mkCoVar new_name co_kind
760 new_name = mkSysTvName uniq fs
761 co_kind = substTy subst (mkPredTy eq_pred)
763 -- make value vars, instantiating types
764 mk_id_var uniq fs ty = mkUserLocal (mkVarOccFS fs) uniq (substTy subst ty) noSrcSpan
765 arg_ids = zipWith3 mk_id_var id_uniqs id_fss arg_tys
767 exprIsConApp_maybe :: CoreExpr -> Maybe (DataCon, [CoreExpr])
768 -- Returns (Just (dc, [x1..xn])) if the argument expression is
769 -- a constructor application of the form (dc x1 .. xn)
770 exprIsConApp_maybe (Cast expr co)
771 = -- Here we do the KPush reduction rule as described in the FC paper
772 case exprIsConApp_maybe expr of {
774 Just (dc, dc_args) ->
776 -- The transformation applies iff we have
777 -- (C e1 ... en) `cast` co
778 -- where co :: (T t1 .. tn) :=: (T s1 ..sn)
779 -- That is, with a T at the top of both sides
780 -- The left-hand one must be a T, because exprIsConApp returned True
781 -- but the right-hand one might not be. (Though it usually will.)
783 let (from_ty, to_ty) = coercionKind co
784 (from_tc, from_tc_arg_tys) = splitTyConApp from_ty
785 -- The inner one must be a TyConApp
787 case splitTyConApp_maybe to_ty of {
789 Just (to_tc, to_tc_arg_tys)
790 | from_tc /= to_tc -> Nothing
791 -- These two Nothing cases are possible; we might see
792 -- (C x y) `cast` (g :: T a ~ S [a]),
793 -- where S is a type function. In fact, exprIsConApp
794 -- will probably not be called in such circumstances,
795 -- but there't nothing wrong with it
799 tc_arity = tyConArity from_tc
801 (univ_args, rest1) = splitAt tc_arity dc_args
802 (ex_args, rest2) = splitAt n_ex_tvs rest1
803 (co_args_spec, rest3) = splitAt n_cos_spec rest2
804 (co_args_theta, val_args) = splitAt n_cos_theta rest3
806 arg_tys = dataConRepArgTys dc
807 dc_univ_tyvars = dataConUnivTyVars dc
808 dc_ex_tyvars = dataConExTyVars dc
809 dc_eq_spec = dataConEqSpec dc
810 dc_eq_theta = dataConEqTheta dc
811 dc_tyvars = dc_univ_tyvars ++ dc_ex_tyvars
812 n_ex_tvs = length dc_ex_tyvars
813 n_cos_spec = length dc_eq_spec
814 n_cos_theta = length dc_eq_theta
816 -- Make the "theta" from Fig 3 of the paper
817 gammas = decomposeCo tc_arity co
818 new_tys = gammas ++ map (\ (Type t) -> t) ex_args
819 theta = zipOpenTvSubst dc_tyvars new_tys
821 -- First we cast the existential coercion arguments
822 cast_co_spec (tv, ty) co
823 = cast_co_theta (mkEqPred (mkTyVarTy tv, ty)) co
824 cast_co_theta eqPred (Type co)
825 | (ty1, ty2) <- getEqPredTys eqPred
826 = Type $ mkSymCoercion (substTy theta ty1)
828 `mkTransCoercion` (substTy theta ty2)
829 new_co_args = zipWith cast_co_spec dc_eq_spec co_args_spec ++
830 zipWith cast_co_theta dc_eq_theta co_args_theta
832 -- ...and now value arguments
833 new_val_args = zipWith cast_arg arg_tys val_args
834 cast_arg arg_ty arg = mkCoerce (substTy theta arg_ty) arg
837 ASSERT( length univ_args == tc_arity )
838 ASSERT( from_tc == dataConTyCon dc )
839 ASSERT( and (zipWith coreEqType [t | Type t <- univ_args] from_tc_arg_tys) )
840 ASSERT( all isTypeArg (univ_args ++ ex_args) )
841 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 )
843 Just (dc, map Type to_tc_arg_tys ++ ex_args ++ new_co_args ++ new_val_args)
847 -- We do not want to tell the world that we have a
848 -- Cons, to *stop* Case of Known Cons, which removes
850 exprIsConApp_maybe (Note (TickBox {}) expr)
852 exprIsConApp_maybe (Note (BinaryTickBox {}) expr)
856 exprIsConApp_maybe (Note _ expr)
857 = exprIsConApp_maybe expr
858 -- We ignore InlineMe notes in case we have
859 -- x = __inline_me__ (a,b)
860 -- All part of making sure that INLINE pragmas never hurt
861 -- Marcin tripped on this one when making dictionaries more inlinable
863 -- In fact, we ignore all notes. For example,
864 -- case _scc_ "foo" (C a b) of
866 -- should be optimised away, but it will be only if we look
867 -- through the SCC note.
869 exprIsConApp_maybe expr = analyse (collectArgs expr)
871 analyse (Var fun, args)
872 | Just con <- isDataConWorkId_maybe fun,
873 args `lengthAtLeast` dataConRepArity con
874 -- Might be > because the arity excludes type args
877 -- Look through unfoldings, but only cheap ones, because
878 -- we are effectively duplicating the unfolding
879 analyse (Var fun, [])
880 | let unf = idUnfolding fun,
882 = exprIsConApp_maybe (unfoldingTemplate unf)
889 %************************************************************************
891 \subsection{Eta reduction and expansion}
893 %************************************************************************
896 exprEtaExpandArity :: DynFlags -> CoreExpr -> Arity
897 {- The Arity returned is the number of value args the
898 thing can be applied to without doing much work
900 exprEtaExpandArity is used when eta expanding
903 It returns 1 (or more) to:
904 case x of p -> \s -> ...
905 because for I/O ish things we really want to get that \s to the top.
906 We are prepared to evaluate x each time round the loop in order to get that
908 It's all a bit more subtle than it looks:
912 Consider one-shot lambdas
913 let x = expensive in \y z -> E
914 We want this to have arity 2 if the \y-abstraction is a 1-shot lambda
915 Hence the ArityType returned by arityType
917 2. The state-transformer hack
919 The one-shot lambda special cause is particularly important/useful for
920 IO state transformers, where we often get
921 let x = E in \ s -> ...
923 and the \s is a real-world state token abstraction. Such abstractions
924 are almost invariably 1-shot, so we want to pull the \s out, past the
925 let x=E, even if E is expensive. So we treat state-token lambdas as
926 one-shot even if they aren't really. The hack is in Id.isOneShotBndr.
928 3. Dealing with bottom
931 f = \x -> error "foo"
932 Here, arity 1 is fine. But if it is
936 then we want to get arity 2. Tecnically, this isn't quite right, because
938 should diverge, but it'll converge if we eta-expand f. Nevertheless, we
939 do so; it improves some programs significantly, and increasing convergence
940 isn't a bad thing. Hence the ABot/ATop in ArityType.
942 Actually, the situation is worse. Consider
946 Can we eta-expand here? At first the answer looks like "yes of course", but
949 This should diverge! But if we eta-expand, it won't. Again, we ignore this
950 "problem", because being scrupulous would lose an important transformation for
956 Non-recursive newtypes are transparent, and should not get in the way.
957 We do (currently) eta-expand recursive newtypes too. So if we have, say
959 newtype T = MkT ([T] -> Int)
963 where f has arity 1. Then: etaExpandArity e = 1;
964 that is, etaExpandArity looks through the coerce.
966 When we eta-expand e to arity 1: eta_expand 1 e T
967 we want to get: coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
969 HOWEVER, note that if you use coerce bogusly you can ge
971 And since negate has arity 2, you might try to eta expand. But you can't
972 decopose Int to a function type. Hence the final case in eta_expand.
976 exprEtaExpandArity dflags e = arityDepth (arityType dflags e)
978 -- A limited sort of function type
979 data ArityType = AFun Bool ArityType -- True <=> one-shot
980 | ATop -- Know nothing
983 arityDepth :: ArityType -> Arity
984 arityDepth (AFun _ ty) = 1 + arityDepth ty
987 andArityType :: ArityType -> ArityType -> ArityType
988 andArityType ABot at2 = at2
989 andArityType ATop _ = ATop
990 andArityType (AFun t1 at1) (AFun t2 at2) = AFun (t1 && t2) (andArityType at1 at2)
991 andArityType at1 at2 = andArityType at2 at1
993 arityType :: DynFlags -> CoreExpr -> ArityType
994 -- (go1 e) = [b1,..,bn]
995 -- means expression can be rewritten \x_b1 -> ... \x_bn -> body
996 -- where bi is True <=> the lambda is one-shot
998 arityType dflags (Note _ e) = arityType dflags e
999 -- Not needed any more: etaExpand is cleverer
1000 -- | ok_note n = arityType dflags e
1001 -- | otherwise = ATop
1003 arityType dflags (Cast e _) = arityType dflags e
1006 = mk (idArity v) (arg_tys (idType v))
1008 mk :: Arity -> [Type] -> ArityType
1009 -- The argument types are only to steer the "state hack"
1010 -- Consider case x of
1012 -- False -> \(s:RealWorld) -> e
1013 -- where foo has arity 1. Then we want the state hack to
1014 -- apply to foo too, so we can eta expand the case.
1015 mk 0 tys | isBottomingId v = ABot
1016 | (ty:_) <- tys, isStateHackType ty = AFun True ATop
1018 mk n (ty:tys) = AFun (isStateHackType ty) (mk (n-1) tys)
1019 mk n [] = AFun False (mk (n-1) [])
1021 arg_tys :: Type -> [Type] -- Ignore for-alls
1023 | Just (_, ty') <- splitForAllTy_maybe ty = arg_tys ty'
1024 | Just (arg,res) <- splitFunTy_maybe ty = arg : arg_tys res
1027 -- Lambdas; increase arity
1028 arityType dflags (Lam x e)
1029 | isId x = AFun (isOneShotBndr x) (arityType dflags e)
1030 | otherwise = arityType dflags e
1032 -- Applications; decrease arity
1033 arityType dflags (App f (Type _)) = arityType dflags f
1034 arityType dflags (App f a)
1035 = case arityType dflags f of
1036 ABot -> ABot -- If function diverges, ignore argument
1037 ATop -> ATop -- No no info about function
1039 | exprIsCheap a -> xs
1042 -- Case/Let; keep arity if either the expression is cheap
1043 -- or it's a 1-shot lambda
1044 -- The former is not really right for Haskell
1045 -- f x = case x of { (a,b) -> \y. e }
1047 -- f x y = case x of { (a,b) -> e }
1048 -- The difference is observable using 'seq'
1049 arityType dflags (Case scrut _ _ alts)
1050 = case foldr1 andArityType [arityType dflags rhs | (_,_,rhs) <- alts] of
1051 xs | exprIsCheap scrut -> xs
1052 AFun one_shot _ | one_shot -> AFun True ATop
1055 arityType dflags (Let b e)
1056 = case arityType dflags e of
1057 xs | cheap_bind b -> xs
1058 AFun one_shot _ | one_shot -> AFun True ATop
1061 cheap_bind (NonRec b e) = is_cheap (b,e)
1062 cheap_bind (Rec prs) = all is_cheap prs
1063 is_cheap (b,e) = (dopt Opt_DictsCheap dflags && isDictId b)
1065 -- If the experimental -fdicts-cheap flag is on, we eta-expand through
1066 -- dictionary bindings. This improves arities. Thereby, it also
1067 -- means that full laziness is less prone to floating out the
1068 -- application of a function to its dictionary arguments, which
1069 -- can thereby lose opportunities for fusion. Example:
1070 -- foo :: Ord a => a -> ...
1071 -- foo = /\a \(d:Ord a). let d' = ...d... in \(x:a). ....
1072 -- -- So foo has arity 1
1074 -- f = \x. foo dInt $ bar x
1076 -- The (foo DInt) is floated out, and makes ineffective a RULE
1077 -- foo (bar x) = ...
1079 -- One could go further and make exprIsCheap reply True to any
1080 -- dictionary-typed expression, but that's more work.
1082 arityType _ _ = ATop
1084 {- NOT NEEDED ANY MORE: etaExpand is cleverer
1085 ok_note InlineMe = False
1086 ok_note other = True
1087 -- Notice that we do not look through __inline_me__
1088 -- This may seem surprising, but consider
1089 -- f = _inline_me (\x -> e)
1090 -- We DO NOT want to eta expand this to
1091 -- f = \x -> (_inline_me (\x -> e)) x
1092 -- because the _inline_me gets dropped now it is applied,
1101 etaExpand :: Arity -- Result should have this number of value args
1103 -> CoreExpr -> Type -- Expression and its type
1105 -- (etaExpand n us e ty) returns an expression with
1106 -- the same meaning as 'e', but with arity 'n'.
1108 -- Given e' = etaExpand n us e ty
1110 -- ty = exprType e = exprType e'
1112 -- Note that SCCs are not treated specially. If we have
1113 -- etaExpand 2 (\x -> scc "foo" e)
1114 -- = (\xy -> (scc "foo" e) y)
1115 -- So the costs of evaluating 'e' (not 'e y') are attributed to "foo"
1117 etaExpand n us expr ty
1118 | manifestArity expr >= n = expr -- The no-op case
1120 = eta_expand n us expr ty
1123 -- manifestArity sees how many leading value lambdas there are
1124 manifestArity :: CoreExpr -> Arity
1125 manifestArity (Lam v e) | isId v = 1 + manifestArity e
1126 | otherwise = manifestArity e
1127 manifestArity (Note _ e) = manifestArity e
1128 manifestArity (Cast e _) = manifestArity e
1131 -- etaExpand deals with for-alls. For example:
1133 -- where E :: forall a. a -> a
1135 -- (/\b. \y::a -> E b y)
1137 -- It deals with coerces too, though they are now rare
1138 -- so perhaps the extra code isn't worth it
1139 eta_expand :: Int -> [Unique] -> CoreExpr -> Type -> CoreExpr
1141 eta_expand n _ expr ty
1143 -- The ILX code generator requires eta expansion for type arguments
1144 -- too, but alas the 'n' doesn't tell us how many of them there
1145 -- may be. So we eagerly eta expand any big lambdas, and just
1146 -- cross our fingers about possible loss of sharing in the ILX case.
1147 -- The Right Thing is probably to make 'arity' include
1148 -- type variables throughout the compiler. (ToDo.)
1150 -- Saturated, so nothing to do
1153 -- Short cut for the case where there already
1154 -- is a lambda; no point in gratuitously adding more
1155 eta_expand n us (Lam v body) ty
1157 = Lam v (eta_expand n us body (applyTy ty (mkTyVarTy v)))
1160 = Lam v (eta_expand (n-1) us body (funResultTy ty))
1162 -- We used to have a special case that stepped inside Coerces here,
1163 -- thus: eta_expand n us (Note note@(Coerce _ ty) e) _
1164 -- = Note note (eta_expand n us e ty)
1165 -- BUT this led to an infinite loop
1166 -- Example: newtype T = MkT (Int -> Int)
1167 -- eta_expand 1 (coerce (Int->Int) e)
1168 -- --> coerce (Int->Int) (eta_expand 1 T e)
1170 -- --> coerce (Int->Int) (coerce T
1171 -- (\x::Int -> eta_expand 1 (coerce (Int->Int) e)))
1172 -- by the splitNewType_maybe case below
1175 eta_expand n us expr ty
1176 = ASSERT2 (exprType expr `coreEqType` ty, ppr (exprType expr) $$ ppr ty)
1177 case splitForAllTy_maybe ty of {
1180 Lam lam_tv (eta_expand n us2 (App expr (Type (mkTyVarTy lam_tv))) (substTyWith [tv] [mkTyVarTy lam_tv] ty'))
1182 lam_tv = setVarName tv (mkSysTvName uniq (fsLit "etaT"))
1183 -- Using tv as a base retains its tyvar/covar-ness
1187 case splitFunTy_maybe ty of {
1188 Just (arg_ty, res_ty) -> Lam arg1 (eta_expand (n-1) us2 (App expr (Var arg1)) res_ty)
1190 arg1 = mkSysLocal (fsLit "eta") uniq arg_ty
1196 -- newtype T = MkT ([T] -> Int)
1197 -- Consider eta-expanding this
1200 -- coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
1202 case splitNewTypeRepCo_maybe ty of {
1203 Just(ty1,co) -> mkCoerce (mkSymCoercion co)
1204 (eta_expand n us (mkCoerce co expr) ty1) ;
1207 -- We have an expression of arity > 0, but its type isn't a function
1208 -- This *can* legitmately happen: e.g. coerce Int (\x. x)
1209 -- Essentially the programmer is playing fast and loose with types
1210 -- (Happy does this a lot). So we simply decline to eta-expand.
1211 -- Otherwise we'd end up with an explicit lambda having a non-function type
1216 exprArity is a cheap-and-cheerful version of exprEtaExpandArity.
1217 It tells how many things the expression can be applied to before doing
1218 any work. It doesn't look inside cases, lets, etc. The idea is that
1219 exprEtaExpandArity will do the hard work, leaving something that's easy
1220 for exprArity to grapple with. In particular, Simplify uses exprArity to
1221 compute the ArityInfo for the Id.
1223 Originally I thought that it was enough just to look for top-level lambdas, but
1224 it isn't. I've seen this
1226 foo = PrelBase.timesInt
1228 We want foo to get arity 2 even though the eta-expander will leave it
1229 unchanged, in the expectation that it'll be inlined. But occasionally it
1230 isn't, because foo is blacklisted (used in a rule).
1232 Similarly, see the ok_note check in exprEtaExpandArity. So
1233 f = __inline_me (\x -> e)
1234 won't be eta-expanded.
1236 And in any case it seems more robust to have exprArity be a bit more intelligent.
1237 But note that (\x y z -> f x y z)
1238 should have arity 3, regardless of f's arity.
1240 Note [exprArity invariant]
1241 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1242 exprArity has the following invariant:
1243 (exprArity e) = n, then manifestArity (etaExpand e n) = n
1245 That is, if exprArity says "the arity is n" then etaExpand really can get
1246 "n" manifest lambdas to the top.
1248 Why is this important? Because
1249 - In TidyPgm we use exprArity to fix the *final arity* of
1250 each top-level Id, and in
1251 - In CorePrep we use etaExpand on each rhs, so that the visible lambdas
1252 actually match that arity, which in turn means
1253 that the StgRhs has the right number of lambdas
1255 An alternative would be to do the eta-expansion in TidyPgm, at least
1256 for top-level bindings, in which case we would not need the trim_arity
1257 in exprArity. That is a less local change, so I'm going to leave it for today!
1261 exprArity :: CoreExpr -> Arity
1264 go (Var v) = idArity v
1265 go (Lam x e) | isId x = go e + 1
1267 go (Note _ e) = go e
1268 go (Cast e co) = trim_arity (go e) 0 (snd (coercionKind co))
1269 go (App e (Type _)) = go e
1270 go (App f a) | exprIsCheap a = (go f - 1) `max` 0
1271 -- NB: exprIsCheap a!
1272 -- f (fac x) does not have arity 2,
1273 -- even if f has arity 3!
1274 -- NB: `max 0`! (\x y -> f x) has arity 2, even if f is
1275 -- unknown, hence arity 0
1278 -- Note [exprArity invariant]
1281 | Just (_, ty') <- splitForAllTy_maybe ty = trim_arity n a ty'
1282 | Just (_, ty') <- splitFunTy_maybe ty = trim_arity n (a+1) ty'
1283 | Just (ty',_) <- splitNewTypeRepCo_maybe ty = trim_arity n a ty'
1287 %************************************************************************
1289 \subsection{Equality}
1291 %************************************************************************
1293 @cheapEqExpr@ is a cheap equality test which bales out fast!
1294 True => definitely equal
1295 False => may or may not be equal
1298 cheapEqExpr :: Expr b -> Expr b -> Bool
1300 cheapEqExpr (Var v1) (Var v2) = v1==v2
1301 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
1302 cheapEqExpr (Type t1) (Type t2) = t1 `coreEqType` t2
1304 cheapEqExpr (App f1 a1) (App f2 a2)
1305 = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
1307 cheapEqExpr (Cast e1 t1) (Cast e2 t2)
1308 = e1 `cheapEqExpr` e2 && t1 `coreEqCoercion` t2
1310 cheapEqExpr _ _ = False
1312 exprIsBig :: Expr b -> Bool
1313 -- Returns True of expressions that are too big to be compared by cheapEqExpr
1314 exprIsBig (Lit _) = False
1315 exprIsBig (Var _) = False
1316 exprIsBig (Type _) = False
1317 exprIsBig (App f a) = exprIsBig f || exprIsBig a
1318 exprIsBig (Cast e _) = exprIsBig e -- Hopefully coercions are not too big!
1324 tcEqExpr :: CoreExpr -> CoreExpr -> Bool
1325 -- Used in rule matching, so does *not* look through
1326 -- newtypes, predicate types; hence tcEqExpr
1328 tcEqExpr e1 e2 = tcEqExprX rn_env e1 e2
1330 rn_env = mkRnEnv2 (mkInScopeSet (exprFreeVars e1 `unionVarSet` exprFreeVars e2))
1332 tcEqExprX :: RnEnv2 -> CoreExpr -> CoreExpr -> Bool
1333 tcEqExprX env (Var v1) (Var v2) = rnOccL env v1 == rnOccR env v2
1334 tcEqExprX _ (Lit lit1) (Lit lit2) = lit1 == lit2
1335 tcEqExprX env (App f1 a1) (App f2 a2) = tcEqExprX env f1 f2 && tcEqExprX env a1 a2
1336 tcEqExprX env (Lam v1 e1) (Lam v2 e2) = tcEqExprX (rnBndr2 env v1 v2) e1 e2
1337 tcEqExprX env (Let (NonRec v1 r1) e1)
1338 (Let (NonRec v2 r2) e2) = tcEqExprX env r1 r2
1339 && tcEqExprX (rnBndr2 env v1 v2) e1 e2
1340 tcEqExprX env (Let (Rec ps1) e1)
1341 (Let (Rec ps2) e2) = equalLength ps1 ps2
1342 && and (zipWith eq_rhs ps1 ps2)
1343 && tcEqExprX env' e1 e2
1345 env' = foldl2 rn_bndr2 env ps2 ps2
1346 rn_bndr2 env (b1,_) (b2,_) = rnBndr2 env b1 b2
1347 eq_rhs (_,r1) (_,r2) = tcEqExprX env' r1 r2
1348 tcEqExprX env (Case e1 v1 t1 a1)
1349 (Case e2 v2 t2 a2) = tcEqExprX env e1 e2
1350 && tcEqTypeX env t1 t2
1351 && equalLength a1 a2
1352 && and (zipWith (eq_alt env') a1 a2)
1354 env' = rnBndr2 env v1 v2
1356 tcEqExprX env (Note n1 e1) (Note n2 e2) = eq_note env n1 n2 && tcEqExprX env e1 e2
1357 tcEqExprX env (Cast e1 co1) (Cast e2 co2) = tcEqTypeX env co1 co2 && tcEqExprX env e1 e2
1358 tcEqExprX env (Type t1) (Type t2) = tcEqTypeX env t1 t2
1359 tcEqExprX _ _ _ = False
1361 eq_alt :: RnEnv2 -> CoreAlt -> CoreAlt -> Bool
1362 eq_alt env (c1,vs1,r1) (c2,vs2,r2) = c1==c2 && tcEqExprX (rnBndrs2 env vs1 vs2) r1 r2
1364 eq_note :: RnEnv2 -> Note -> Note -> Bool
1365 eq_note _ (SCC cc1) (SCC cc2) = cc1 == cc2
1366 eq_note _ (CoreNote s1) (CoreNote s2) = s1 == s2
1367 eq_note _ _ _ = False
1371 %************************************************************************
1373 \subsection{The size of an expression}
1375 %************************************************************************
1378 coreBindsSize :: [CoreBind] -> Int
1379 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
1381 exprSize :: CoreExpr -> Int
1382 -- A measure of the size of the expressions
1383 -- It also forces the expression pretty drastically as a side effect
1384 exprSize (Var v) = v `seq` 1
1385 exprSize (Lit lit) = lit `seq` 1
1386 exprSize (App f a) = exprSize f + exprSize a
1387 exprSize (Lam b e) = varSize b + exprSize e
1388 exprSize (Let b e) = bindSize b + exprSize e
1389 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
1390 exprSize (Cast e co) = (seqType co `seq` 1) + exprSize e
1391 exprSize (Note n e) = noteSize n + exprSize e
1392 exprSize (Type t) = seqType t `seq` 1
1394 noteSize :: Note -> Int
1395 noteSize (SCC cc) = cc `seq` 1
1396 noteSize InlineMe = 1
1397 noteSize (CoreNote s) = s `seq` 1 -- hdaume: core annotations
1399 varSize :: Var -> Int
1400 varSize b | isTyVar b = 1
1401 | otherwise = seqType (idType b) `seq`
1402 megaSeqIdInfo (idInfo b) `seq`
1405 varsSize :: [Var] -> Int
1406 varsSize = sum . map varSize
1408 bindSize :: CoreBind -> Int
1409 bindSize (NonRec b e) = varSize b + exprSize e
1410 bindSize (Rec prs) = foldr ((+) . pairSize) 0 prs
1412 pairSize :: (Var, CoreExpr) -> Int
1413 pairSize (b,e) = varSize b + exprSize e
1415 altSize :: CoreAlt -> Int
1416 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
1420 %************************************************************************
1422 \subsection{Hashing}
1424 %************************************************************************
1427 hashExpr :: CoreExpr -> Int
1428 -- Two expressions that hash to the same Int may be equal (but may not be)
1429 -- Two expressions that hash to the different Ints are definitely unequal
1431 -- But "unequal" here means "not identical"; two alpha-equivalent
1432 -- expressions may hash to the different Ints
1434 -- The emphasis is on a crude, fast hash, rather than on high precision
1436 -- We must be careful that \x.x and \y.y map to the same hash code,
1437 -- (at least if we want the above invariant to be true)
1439 hashExpr e = fromIntegral (hash_expr (1,emptyVarEnv) e .&. 0x7fffffff)
1440 -- UniqFM doesn't like negative Ints
1442 type HashEnv = (Int, VarEnv Int) -- Hash code for bound variables
1444 hash_expr :: HashEnv -> CoreExpr -> Word32
1445 -- Word32, because we're expecting overflows here, and overflowing
1446 -- signed types just isn't cool. In C it's even undefined.
1447 hash_expr env (Note _ e) = hash_expr env e
1448 hash_expr env (Cast e _) = hash_expr env e
1449 hash_expr env (Var v) = hashVar env v
1450 hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
1451 hash_expr env (App f e) = hash_expr env f * fast_hash_expr env e
1452 hash_expr env (Let (NonRec b r) e) = hash_expr (extend_env env b) e * fast_hash_expr env r
1453 hash_expr env (Let (Rec ((b,_):_)) e) = hash_expr (extend_env env b) e
1454 hash_expr env (Case e _ _ _) = hash_expr env e
1455 hash_expr env (Lam b e) = hash_expr (extend_env env b) e
1456 hash_expr _ (Type _) = WARN(True, text "hash_expr: type") 1
1457 -- Shouldn't happen. Better to use WARN than trace, because trace
1458 -- prevents the CPR optimisation kicking in for hash_expr.
1460 fast_hash_expr :: HashEnv -> CoreExpr -> Word32
1461 fast_hash_expr env (Var v) = hashVar env v
1462 fast_hash_expr env (Type t) = fast_hash_type env t
1463 fast_hash_expr _ (Lit lit) = fromIntegral (hashLiteral lit)
1464 fast_hash_expr env (Cast e _) = fast_hash_expr env e
1465 fast_hash_expr env (Note _ e) = fast_hash_expr env e
1466 fast_hash_expr env (App _ a) = fast_hash_expr env a -- A bit idiosyncratic ('a' not 'f')!
1467 fast_hash_expr _ _ = 1
1469 fast_hash_type :: HashEnv -> Type -> Word32
1470 fast_hash_type env ty
1471 | Just tv <- getTyVar_maybe ty = hashVar env tv
1472 | Just (tc,tys) <- splitTyConApp_maybe ty = let hash_tc = fromIntegral (hashName (tyConName tc))
1473 in foldr (\t n -> fast_hash_type env t + n) hash_tc tys
1476 extend_env :: HashEnv -> Var -> (Int, VarEnv Int)
1477 extend_env (n,env) b = (n+1, extendVarEnv env b n)
1479 hashVar :: HashEnv -> Var -> Word32
1481 = fromIntegral (lookupVarEnv env v `orElse` hashName (idName v))
1484 %************************************************************************
1486 \subsection{Determining non-updatable right-hand-sides}
1488 %************************************************************************
1490 Top-level constructor applications can usually be allocated
1491 statically, but they can't if the constructor, or any of the
1492 arguments, come from another DLL (because we can't refer to static
1493 labels in other DLLs).
1495 If this happens we simply make the RHS into an updatable thunk,
1496 and 'exectute' it rather than allocating it statically.
1499 rhsIsStatic :: PackageId -> CoreExpr -> Bool
1500 -- This function is called only on *top-level* right-hand sides
1501 -- Returns True if the RHS can be allocated statically, with
1502 -- no thunks involved at all.
1504 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1505 -- refers to, CAFs; (ii) in CoreToStg to decide whether to put an
1506 -- update flag on it and (iii) in DsExpr to decide how to expand
1509 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1510 -- (a) a value lambda
1511 -- (b) a saturated constructor application with static args
1513 -- BUT watch out for
1514 -- (i) Any cross-DLL references kill static-ness completely
1515 -- because they must be 'executed' not statically allocated
1516 -- ("DLL" here really only refers to Windows DLLs, on other platforms,
1517 -- this is not necessary)
1519 -- (ii) We treat partial applications as redexes, because in fact we
1520 -- make a thunk for them that runs and builds a PAP
1521 -- at run-time. The only appliations that are treated as
1522 -- static are *saturated* applications of constructors.
1524 -- We used to try to be clever with nested structures like this:
1525 -- ys = (:) w ((:) w [])
1526 -- on the grounds that CorePrep will flatten ANF-ise it later.
1527 -- But supporting this special case made the function much more
1528 -- complicated, because the special case only applies if there are no
1529 -- enclosing type lambdas:
1530 -- ys = /\ a -> Foo (Baz ([] a))
1531 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1533 -- But in fact, even without -O, nested structures at top level are
1534 -- flattened by the simplifier, so we don't need to be super-clever here.
1538 -- f = \x::Int. x+7 TRUE
1539 -- p = (True,False) TRUE
1541 -- d = (fst p, False) FALSE because there's a redex inside
1542 -- (this particular one doesn't happen but...)
1544 -- h = D# (1.0## /## 2.0##) FALSE (redex again)
1545 -- n = /\a. Nil a TRUE
1547 -- t = /\a. (:) (case w a of ...) (Nil a) FALSE (redex)
1550 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1551 -- a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1553 -- b) (C x xs), where C is a contructors is updatable if the application is
1556 -- c) don't look through unfolding of f in (f x).
1558 rhsIsStatic _this_pkg rhs = is_static False rhs
1560 is_static :: Bool -- True <=> in a constructor argument; must be atomic
1563 is_static False (Lam b e) = isRuntimeVar b || is_static False e
1565 is_static _ (Note (SCC _) _) = False
1566 is_static in_arg (Note _ e) = is_static in_arg e
1567 is_static in_arg (Cast e _) = is_static in_arg e
1569 is_static _ (Lit lit)
1571 MachLabel _ _ -> False
1573 -- A MachLabel (foreign import "&foo") in an argument
1574 -- prevents a constructor application from being static. The
1575 -- reason is that it might give rise to unresolvable symbols
1576 -- in the object file: under Linux, references to "weak"
1577 -- symbols from the data segment give rise to "unresolvable
1578 -- relocation" errors at link time This might be due to a bug
1579 -- in the linker, but we'll work around it here anyway.
1582 is_static in_arg other_expr = go other_expr 0
1584 go (Var f) n_val_args
1585 #if mingw32_TARGET_OS
1586 | not (isDllName _this_pkg (idName f))
1588 = saturated_data_con f n_val_args
1589 || (in_arg && n_val_args == 0)
1590 -- A naked un-applied variable is *not* deemed a static RHS
1592 -- Reason: better to update so that the indirection gets shorted
1593 -- out, and the true value will be seen
1594 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1595 -- are always updatable. If you do so, make sure that non-updatable
1596 -- ones have enough space for their static link field!
1598 go (App f a) n_val_args
1599 | isTypeArg a = go f n_val_args
1600 | not in_arg && is_static True a = go f (n_val_args + 1)
1601 -- The (not in_arg) checks that we aren't in a constructor argument;
1602 -- if we are, we don't allow (value) applications of any sort
1604 -- NB. In case you wonder, args are sometimes not atomic. eg.
1605 -- x = D# (1.0## /## 2.0##)
1606 -- can't float because /## can fail.
1608 go (Note (SCC _) _) _ = False
1609 go (Note _ f) n_val_args = go f n_val_args
1610 go (Cast e _) n_val_args = go e n_val_args
1614 saturated_data_con f n_val_args
1615 = case isDataConWorkId_maybe f of
1616 Just dc -> n_val_args == dataConRepArity dc