2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
4 \section[SaAbsInt]{Abstract interpreter for strictness analysis}
7 #include "HsVersions.h"
21 import CoreUnfold ( Unfolding(..), UfExpr, RdrName, SimpleUnfolding(..), FormSummary )
22 import CoreUtils ( unTagBinders )
23 import Id ( idType, getIdStrictness, getIdUnfolding,
24 dataConTyCon, dataConArgTys
26 import IdInfo ( StrictnessInfo(..),
27 wwPrim, wwStrict, wwEnum, wwUnpack
29 import Demand ( Demand(..) )
30 import MagicUFs ( MagicUnfoldingFun )
31 import Maybes ( maybeToBool )
32 import Outputable ( Outputable(..){-instance * []-} )
33 import PprStyle ( PprStyle(..) )
34 import Pretty ( ppStr )
35 import PrimOp ( PrimOp(..) )
37 import TyCon ( maybeTyConSingleCon, isEnumerationTyCon,
40 import Type ( maybeAppDataTyConExpandingDicts, isPrimType )
41 import TysWiredIn ( intTyCon, integerTyCon, doubleTyCon,
42 floatTyCon, wordTyCon, addrTyCon
44 import Util ( isIn, isn'tIn, nOfThem, zipWithEqual,
45 pprTrace, panic, pprPanic, assertPanic
48 returnsRealWorld x = False -- ToDo: panic "SaAbsInt.returnsRealWorld (ToDo)"
51 %************************************************************************
53 \subsection[AbsVal-ops]{Operations on @AbsVals@}
55 %************************************************************************
57 Least upper bound, greatest lower bound.
60 lub, glb :: AbsVal -> AbsVal -> AbsVal
62 lub val1 val2 | isBot val1 = val2 -- The isBot test includes the case where
63 lub val1 val2 | isBot val2 = val1 -- one of the val's is a function which
64 -- always returns bottom, such as \y.x,
65 -- when x is bound to bottom.
67 lub (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual "lub" lub xs ys)
69 lub _ _ = AbsTop -- Crude, but conservative
70 -- The crudity only shows up if there
71 -- are functions involved
73 -- Slightly funny glb; for absence analysis only;
74 -- AbsBot is the safe answer.
76 -- Using anyBot rather than just testing for AbsBot is important.
81 -- g = \x y z -> case x of
85 -- Now, the abstract value of the branches of the case will be an
86 -- AbsFun, but when testing for z's absence we want to spot that it's
87 -- an AbsFun which can't possibly return AbsBot. So when glb'ing we
88 -- mustn't be too keen to bale out and return AbsBot; the anyBot test
89 -- spots that (f x) can't possibly return AbsBot.
91 -- We have also tripped over the following interesting case:
96 -- Now, suppose f is bound to AbsTop. Does this expression mention z?
97 -- Obviously not. But the case will take the glb of AbsTop (for f) and
98 -- an AbsFun (for \y->1). We should not bale out and give AbsBot, because
99 -- that would say that it *does* mention z (or anything else for that matter).
100 -- Nor can we always return AbsTop, because the AbsFun might be something
101 -- like (\y->z), which obviously does mention z. The point is that we're
102 -- glbing two functions, and AbsTop is not actually the top of the function
103 -- lattice. It is more like (\xyz -> x|y|z); that is, AbsTop returns
104 -- poison iff any of its arguments do.
106 -- Deal with functions specially, because AbsTop isn't the
107 -- top of their domain.
110 | is_fun v1 || is_fun v2
111 = if not (anyBot v1) && not (anyBot v2)
117 is_fun (AbsFun _ _ _) = True
118 is_fun (AbsApproxFun _ _) = True -- Not used, but the glb works ok
121 -- The non-functional cases are quite straightforward
123 glb (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual "glb" glb xs ys)
128 glb _ _ = AbsBot -- Be pessimistic
134 -> AbsVal -- Value of scrutinee
135 -> [AbsVal] -- Value of branches (at least one)
138 -- For strictness analysis, see if the scrutinee is bottom; if so
139 -- return bottom; otherwise, the lub of the branches.
141 combineCaseValues StrAnal AbsBot branches = AbsBot
142 combineCaseValues StrAnal other_scrutinee branches
143 -- Scrutinee can only be AbsBot, AbsProd or AbsTop
144 = ASSERT(ok_scrutinee)
148 = case other_scrutinee of {
149 AbsTop -> True; -- i.e., cool
150 AbsProd _ -> True; -- ditto
151 _ -> False -- party over
154 -- For absence analysis, check if the scrutinee is all poison (isBot)
155 -- If so, return poison (AbsBot); otherwise, any nested poison will come
156 -- out from looking at the branches, so just glb together the branches
157 -- to get the worst one.
159 combineCaseValues AbsAnal AbsBot branches = AbsBot
160 combineCaseValues AbsAnal other_scrutinee branches
161 -- Scrutinee can only be AbsBot, AbsProd or AbsTop
162 = ASSERT(ok_scrutinee)
164 result = foldr1 glb branches
166 tracer = if at_least_one_AbsFun && at_least_one_AbsTop
168 pprTrace "combineCase:" (ppr PprDebug branches)
177 = case other_scrutinee of {
178 AbsTop -> True; -- i.e., cool
179 AbsProd _ -> True; -- ditto
180 _ -> False -- party over
183 at_least_one_AbsFun = foldr ((||) . is_AbsFun) False branches
184 at_least_one_AbsTop = foldr ((||) . is_AbsTop) False branches
185 no_AbsBots = foldr ((&&) . is_not_AbsBot) True branches
187 is_AbsFun x = case x of { AbsFun _ _ _ -> True; _ -> False }
188 is_AbsTop x = case x of { AbsTop -> True; _ -> False }
189 is_not_AbsBot x = case x of { AbsBot -> False; _ -> True }
192 @isBot@ returns True if its argument is (a representation of) bottom. The
193 ``representation'' part is because we need to detect the bottom {\em function}
194 too. To detect the bottom function, bind its args to top, and see if it
197 Used only in strictness analysis:
199 isBot :: AbsVal -> Bool
202 isBot (AbsFun arg body env) = isBot (absEval StrAnal body env)
203 -- Don't bother to extend the envt because
204 -- unbound variables default to AbsTop anyway
208 Used only in absence analysis:
210 anyBot :: AbsVal -> Bool
212 anyBot AbsBot = True -- poisoned!
213 anyBot AbsTop = False
214 anyBot (AbsProd vals) = any anyBot vals
215 anyBot (AbsFun arg body env) = anyBot (absEval AbsAnal body env)
216 anyBot (AbsApproxFun _ _) = False
218 -- AbsApproxFun can only arise in absence analysis from the Demand
219 -- info of an imported value; whatever it is we're looking for is
220 -- certainly not present over in the imported value.
223 @widen@ takes an @AbsVal@, $val$, and returns and @AbsVal@ which is
224 approximated by $val$. Furthermore, the result has no @AbsFun@s in
225 it, so it can be compared for equality by @sameVal@.
228 widen :: AnalysisKind -> AbsVal -> AbsVal
230 widen StrAnal (AbsFun arg body env)
231 = AbsApproxFun (findDemandStrOnly env body arg)
232 (widen StrAnal abs_body)
234 abs_body = absEval StrAnal body env
237 This stuff is now instead handled neatly by the fact that AbsApproxFun
238 contains an AbsVal inside it. SLPJ Jan 97
240 | isBot abs_body = AbsBot
241 -- It's worth checking for a function which is unconditionally
244 -- f x y = let g y = case x of ...
245 -- in (g ..) + (g ..)
247 -- Here, when we are considering strictness of f in x, we'll
248 -- evaluate the body of f with x bound to bottom. The current
249 -- strategy is to bind g to its *widened* value; without the isBot
250 -- (...) test above, we'd bind g to an AbsApproxFun, and deliver
251 -- Top, not Bot as the value of f's rhs. The test spots the
252 -- unconditional bottom-ness of g when x is bottom. (Another
253 -- alternative here would be to bind g to its exact abstract
254 -- value, but that entails lots of potential re-computation, at
255 -- every application of g.)
258 widen StrAnal (AbsProd vals) = AbsProd (map (widen StrAnal) vals)
259 widen StrAnal other_val = other_val
262 widen AbsAnal (AbsFun arg body env)
263 | anyBot abs_body = AbsBot
264 -- In the absence-analysis case it's *essential* to check
265 -- that the function has no poison in its body. If it does,
266 -- anywhere, then the whole function is poisonous.
269 = AbsApproxFun (findDemandAbsOnly env body arg)
270 (widen AbsAnal abs_body)
272 abs_body = absEval AbsAnal body env
274 widen AbsAnal (AbsProd vals) = AbsProd (map (widen AbsAnal) vals)
276 -- It's desirable to do a good job of widening for product
280 -- in ...(case p of (x,y) -> x)...
282 -- Now, is y absent in this expression? Currently the
283 -- analyser widens p before looking at p's scope, to avoid
284 -- lots of recomputation in the case where p is a function.
285 -- So if widening doesn't have a case for products, we'll
286 -- widen p to AbsBot (since when searching for absence in y we
287 -- bind y to poison ie AbsBot), and now we are lost.
289 widen AbsAnal other_val = other_val
291 -- WAS: if anyBot val then AbsBot else AbsTop
292 -- Nowadays widen is doing a better job on functions for absence analysis.
295 @crudeAbsWiden@ is used just for absence analysis, and always
296 returns AbsTop or AbsBot, so it widens to a two-point domain
299 crudeAbsWiden :: AbsVal -> AbsVal
300 crudeAbsWiden val = if anyBot val then AbsBot else AbsTop
303 @sameVal@ compares two abstract values for equality. It can't deal with
304 @AbsFun@, but that should have been removed earlier in the day by @widen@.
307 sameVal :: AbsVal -> AbsVal -> Bool -- Can't handle AbsFun!
310 sameVal (AbsFun _ _ _) _ = panic "sameVal: AbsFun: arg1"
311 sameVal _ (AbsFun _ _ _) = panic "sameVal: AbsFun: arg2"
314 sameVal AbsBot AbsBot = True
315 sameVal AbsBot other = False -- widen has reduced AbsFun bots to AbsBot
317 sameVal AbsTop AbsTop = True
318 sameVal AbsTop other = False -- Right?
320 sameVal (AbsProd vals1) (AbsProd vals2) = and (zipWithEqual "sameVal" sameVal vals1 vals2)
321 sameVal (AbsProd _) AbsTop = False
322 sameVal (AbsProd _) AbsBot = False
324 sameVal (AbsApproxFun str1 v1) (AbsApproxFun str2 v2) = str1 == str2 && sameVal v1 v1
325 sameVal (AbsApproxFun _ _) AbsTop = False
326 sameVal (AbsApproxFun _ _) AbsBot = False
328 sameVal val1 val2 = panic "sameVal: type mismatch or AbsFun encountered"
332 @evalStrictness@ compares a @Demand@ with an abstract value, returning
333 @True@ iff the abstract value is {\em less defined} than the demand.
334 (@True@ is the exciting answer; @False@ is always safe.)
337 evalStrictness :: Demand
339 -> Bool -- True iff the value is sure
340 -- to be less defined than the Demand
342 evalStrictness (WwLazy _) _ = False
343 evalStrictness WwStrict val = isBot val
344 evalStrictness WwEnum val = isBot val
346 evalStrictness (WwUnpack _ demand_info) val
350 AbsProd vals -> or (zipWithEqual "evalStrictness" evalStrictness demand_info vals)
351 _ -> trace "evalStrictness?" False
353 evalStrictness WwPrim val
357 other -> -- A primitive value should be defined, never bottom;
358 -- hence this paranoia check
359 pprPanic "evalStrictness: WwPrim:" (ppr PprDebug other)
362 For absence analysis, we're interested in whether "poison" in the
363 argument (ie a bottom therein) can propagate to the result of the
364 function call; that is, whether the specified demand can {\em
365 possibly} hit poison.
368 evalAbsence (WwLazy True) _ = False -- Can't possibly hit poison
369 -- with Absent demand
371 evalAbsence (WwUnpack _ demand_info) val
373 AbsTop -> False -- No poison in here
374 AbsBot -> True -- Pure poison
375 AbsProd vals -> or (zipWithEqual "evalAbsence" evalAbsence demand_info vals)
376 _ -> panic "evalAbsence: other"
378 evalAbsence other val = anyBot val
379 -- The demand is conservative; even "Lazy" *might* evaluate the
380 -- argument arbitrarily so we have to look everywhere for poison
383 %************************************************************************
385 \subsection[absEval]{Evaluate an expression in the abstract domain}
387 %************************************************************************
390 -- The isBottomingId stuf is now dealt with via the Id's strictness info
391 -- absId anal var env | isBottomingId var
393 -- StrAnal -> AbsBot -- See discussion below
394 -- AbsAnal -> AbsTop -- Just want to see if there's any poison in
400 case (lookupAbsValEnv env var, getIdStrictness var, getIdUnfolding var) of
402 (Just abs_val, _, _) ->
403 abs_val -- Bound in the environment
405 (Nothing, NoStrictnessInfo, CoreUnfolding (SimpleUnfolding _ _ unfolding)) ->
406 -- We have an unfolding for the expr
407 -- Assume the unfolding has no free variables since it
408 -- came from inside the Id
409 absEval anal (unTagBinders unfolding) env
410 -- Notice here that we only look in the unfolding if we don't
411 -- have strictness info (an unusual situation).
412 -- We could have chosen to look in the unfolding if it exists,
413 -- and only try the strictness info if it doesn't, and that would
414 -- give more accurate results, at the cost of re-abstract-interpreting
415 -- the unfolding every time.
416 -- We found only one place where the look-at-unfolding-first
417 -- method gave better results, which is in the definition of
418 -- showInt in the Prelude. In its defintion, fromIntegral is
419 -- not inlined (it's big) but ab-interp-ing its unfolding gave
420 -- a better result than looking at its strictness only.
421 -- showInt :: Integral a => a -> [Char] -> [Char]
422 -- ! {-# GHC_PRAGMA _A_ 1 _U_ 122 _S_
423 -- "U(U(U(U(SA)AAAAAAAAL)AA)AAAAASAAASA)" {...} _N_ _N_ #-}
425 -- showInt :: Integral a => a -> [Char] -> [Char]
426 -- ! {-# GHC_PRAGMA _A_ 1 _U_ 122 _S_
427 -- "U(U(U(U(SL)LLLLLLLLL)LL)LLLLLSLLLLL)" _N_ _N_ #-}
430 (Nothing, strictness_info, _) ->
431 -- Includes MagicUnfolding, NoUnfolding
432 -- Try the strictness info
433 absValFromStrictness anal strictness_info
435 -- pprTrace "absId:" (ppBesides [ppr PprDebug var, ppStr "=:", pp_anal anal, ppStr ":=",ppr PprDebug result]) $
438 pp_anal StrAnal = ppStr "STR"
439 pp_anal AbsAnal = ppStr "ABS"
441 absEvalAtom anal (VarArg v) env = absId anal v env
442 absEvalAtom anal (LitArg _) env = AbsTop
446 absEval :: AnalysisKind -> CoreExpr -> AbsValEnv -> AbsVal
448 absEval anal (Var var) env = absId anal var env
450 absEval anal (Lit _) env = AbsTop
451 -- What if an unboxed literal? That's OK: it terminates, so its
452 -- abstract value is AbsTop.
454 -- For absence analysis, a literal certainly isn't the "poison" variable
457 Discussion about \tr{error} (following/quoting Lennart): Any expression
458 \tr{error e} is regarded as bottom (with HBC, with the
459 \tr{-ffail-strict} flag, on with \tr{-O}).
461 Regarding it as bottom gives much better strictness properties for
465 f (x:xs) y = f xs (x+y)
467 f [] _ = error "no match"
469 f (x:xs) y = f xs (x+y)
471 is strict in \tr{y}, which you really want. But, it may lead to
472 transformations that turn a call to \tr{error} into non-termination.
473 (The odds of this happening aren't good.)
476 Things are a little different for absence analysis, because we want
477 to make sure that any poison (?????)
480 absEval StrAnal (Prim SeqOp [TyArg _, e]) env
482 if isBot (absEvalAtom StrAnal e env) then AbsBot else AbsTop
483 -- This is a special case to ensure that seq# is strict in its argument.
484 -- The comments below (for most normal PrimOps) do not apply.
486 absEval StrAnal (Prim op es) env = AbsTop
487 -- The arguments are all of unboxed type, so they will already
488 -- have been eval'd. If the boxed version was bottom, we'll
489 -- already have returned bottom.
491 -- Actually, I believe we are saying that either (1) the
492 -- primOp uses unboxed args and they've been eval'ed, so
493 -- there's no need to force strictness here, _or_ the primOp
494 -- uses boxed args and we don't know whether or not it's
495 -- strict, so we assume laziness. (JSM)
497 absEval AbsAnal (Prim op as) env
498 = if any anyBot [absEvalAtom AbsAnal a env | a <- as, isValArg a]
501 -- For absence analysis, we want to see if the poison shows up...
503 absEval anal (Con con as) env
505 = AbsProd [absEvalAtom anal a env | a <- as, isValArg a]
507 | otherwise -- Not single-constructor
509 StrAnal -> -- Strictness case: it's easy: it certainly terminates
511 AbsAnal -> -- In the absence case we need to be more
512 -- careful: look to see if there's any
513 -- poison in the components
514 if any anyBot [absEvalAtom AbsAnal a env | a <- as, isValArg a]
518 has_single_con = maybeToBool (maybeTyConSingleCon (dataConTyCon con))
522 absEval anal (Lam (ValBinder binder) body) env
523 = AbsFun binder body env
524 absEval anal (Lam other_binder expr) env
525 = absEval anal expr env
526 absEval anal (App f a) env | isValArg a
527 = absApply anal (absEval anal f env) (absEvalAtom anal a env)
528 absEval anal (App expr _) env
529 = absEval anal expr env
532 For primitive cases, just GLB the branches, then LUB with the expr part.
535 absEval anal (Case expr (PrimAlts alts deflt)) env
537 expr_val = absEval anal expr env
538 abs_alts = [ absEval anal rhs env | (_, rhs) <- alts ]
539 -- Don't bother to extend envt, because unbound vars
540 -- default to the conservative AbsTop
542 abs_deflt = absEvalDefault anal expr_val deflt env
544 combineCaseValues anal expr_val
545 (abs_deflt ++ abs_alts)
547 absEval anal (Case expr (AlgAlts alts deflt)) env
549 expr_val = absEval anal expr env
550 abs_alts = [ absEvalAlgAlt anal expr_val alt env | alt <- alts ]
551 abs_deflt = absEvalDefault anal expr_val deflt env
555 combineCaseValues anal expr_val
556 (abs_deflt ++ abs_alts)
561 _ -> pprTrace "absCase:ABS:" (ppAbove (ppCat [ppr PprDebug expr, ppr PprDebug result, ppr PprDebug expr_val, ppr PprDebug abs_deflt, ppr PprDebug abs_alts]) (ppr PprDebug (keysFM env `zip` eltsFM env)))
567 For @Lets@ we widen the value we get. This is nothing to
568 do with fixpointing. The reason is so that we don't get an explosion
569 in the amount of computation. For example, consider:
581 If we bind @f@ and @g@ to their exact abstract value, then we'll
582 ``execute'' one call to @f@ and {\em two} calls to @g@. This can blow
583 up exponentially. Widening cuts it off by making a fixed
584 approximation to @f@ and @g@, so that the bodies of @f@ and @g@ are
585 not evaluated again at all when they are called.
587 Of course, this can lose useful joint strictness, which is sad. An
588 alternative approach would be to try with a certain amount of ``fuel''
589 and be prepared to bale out.
592 absEval anal (Let (NonRec binder e1) e2) env
594 new_env = addOneToAbsValEnv env binder (widen anal (absEval anal e1 env))
596 -- The binder of a NonRec should *not* be of unboxed type,
597 -- hence no need to strictly evaluate the Rhs.
598 absEval anal e2 new_env
600 absEval anal (Let (Rec pairs) body) env
602 (binders,rhss) = unzip pairs
603 rhs_vals = cheapFixpoint anal binders rhss env -- Returns widened values
604 new_env = growAbsValEnvList env (binders `zip` rhs_vals)
606 absEval anal body new_env
608 absEval anal (SCC cc expr) env = absEval anal expr env
609 absEval anal (Coerce c ty expr) env = absEval anal expr env
613 absEvalAlgAlt :: AnalysisKind -> AbsVal -> (Id,[Id],CoreExpr) -> AbsValEnv -> AbsVal
615 absEvalAlgAlt anal (AbsProd arg_vals) (con, args, rhs) env
616 = -- The scrutinee is a product value, so it must be of a single-constr
617 -- type; so the constructor in this alternative must be the right one
618 -- so we can go ahead and bind the constructor args to the components
619 -- of the product value.
620 ASSERT(length arg_vals == length args)
622 new_env = growAbsValEnvList env (args `zip` arg_vals)
624 absEval anal rhs new_env
626 absEvalAlgAlt anal other_scrutinee (con, args, rhs) env
627 = -- Scrutinised value is Top or Bot (it can't be a function!)
628 -- So just evaluate the rhs with all constr args bound to Top.
629 -- (If the scrutinee is Top we'll never evaluated this function
635 = case other_scrutinee of {
636 AbsTop -> True; -- i.e., OK
637 AbsBot -> True; -- ditto
638 _ -> False -- party over
642 absEvalDefault :: AnalysisKind
643 -> AbsVal -- Value of scrutinee
646 -> [AbsVal] -- Empty or singleton
648 absEvalDefault anal scrut_val NoDefault env = []
649 absEvalDefault anal scrut_val (BindDefault binder expr) env
650 = [absEval anal expr (addOneToAbsValEnv env binder scrut_val)]
653 %************************************************************************
655 \subsection[absApply]{Apply an abstract function to an abstract argument}
657 %************************************************************************
662 absApply :: AnalysisKind -> AbsVal -> AbsVal -> AbsVal
664 absApply anal AbsBot arg = AbsBot
665 -- AbsBot represents the abstract bottom *function* too
667 absApply StrAnal AbsTop arg = AbsTop
668 absApply AbsAnal AbsTop arg = if anyBot arg
671 -- To be conservative, we have to assume that a function about
672 -- which we know nothing (AbsTop) might look at some part of
676 An @AbsFun@ with only one more argument needed---bind it and eval the
677 result. A @Lam@ with two or more args: return another @AbsFun@ with
678 an augmented environment.
681 absApply anal (AbsFun binder body env) arg
682 = absEval anal body (addOneToAbsValEnv env binder arg)
686 absApply StrAnal (AbsApproxFun demand val) arg
687 = if evalStrictness demand arg
691 absApply AbsAnal (AbsApproxFun demand val) arg
692 = if evalAbsence demand arg
697 absApply anal (AbsProd _) arg = panic ("absApply: Duff function: AbsProd." ++ show anal)
704 %************************************************************************
706 \subsection[findStrictness]{Determine some binders' strictness}
708 %************************************************************************
710 @findStrictness@ applies the function \tr{\ ids -> expr} to
711 \tr{[bot,top,top,...]}, \tr{[top,bot,top,top,...]}, etc., (i.e., once
712 with @AbsBot@ in each argument position), and evaluates the resulting
713 abstract value; it returns a vector of @Demand@s saying whether the
714 result of doing this is guaranteed to be bottom. This tells the
715 strictness of the function in each of the arguments.
717 If an argument is of unboxed type, then we declare that function to be
718 strict in that argument.
720 We don't really have to make up all those lists of mostly-@AbsTops@;
721 unbound variables in an @AbsValEnv@ are implicitly mapped to that.
723 See notes on @addStrictnessInfoToId@.
726 findStrictness :: StrAnalFlags
727 -> [Type] -- Types of args in which strictness is wanted
728 -> AbsVal -- Abstract strictness value of function
729 -> AbsVal -- Abstract absence value of function
730 -> [Demand] -- Resulting strictness annotation
732 findStrictness strflags [] str_val abs_val = []
734 findStrictness strflags (ty:tys) str_val abs_val
736 demand = findRecDemand strflags [] str_fn abs_fn ty
737 str_fn val = absApply StrAnal str_val val
738 abs_fn val = absApply AbsAnal abs_val val
740 demands = findStrictness strflags tys
741 (absApply StrAnal str_val AbsTop)
742 (absApply AbsAnal abs_val AbsTop)
749 findDemandStrOnly str_env expr binder -- Only strictness environment available
750 = findRecDemand strflags [] str_fn abs_fn (idType binder)
752 str_fn val = absEval StrAnal expr (addOneToAbsValEnv str_env binder val)
753 abs_fn val = AbsBot -- Always says poison; so it looks as if
754 -- nothing is absent; safe
755 strflags = getStrAnalFlags str_env
757 findDemandAbsOnly abs_env expr binder -- Only absence environment available
758 = findRecDemand strflags [] str_fn abs_fn (idType binder)
760 str_fn val = AbsBot -- Always says non-termination;
761 -- that'll make findRecDemand peer into the
762 -- structure of the value.
763 abs_fn val = absEval AbsAnal expr (addOneToAbsValEnv abs_env binder val)
764 strflags = getStrAnalFlags abs_env
767 findDemand str_env abs_env expr binder
768 = findRecDemand strflags [] str_fn abs_fn (idType binder)
770 str_fn val = absEval StrAnal expr (addOneToAbsValEnv str_env binder val)
771 abs_fn val = absEval AbsAnal expr (addOneToAbsValEnv abs_env binder val)
772 strflags = getStrAnalFlags str_env
775 @findRecDemand@ is where we finally convert strictness/absence info
776 into ``Demands'' which we can pin on Ids (etc.).
778 NOTE: What do we do if something is {\em both} strict and absent?
779 Should \tr{f x y z = error "foo"} says that \tr{f}'s arguments are all
780 strict (because of bottoming effect of \tr{error}) or all absent
781 (because they're not used)?
783 Well, for practical reasons, we prefer absence over strictness. In
784 particular, it makes the ``default defaults'' for class methods (the
785 ones that say \tr{defm.foo dict = error "I don't exist"}) come out
786 nicely [saying ``the dict isn't used''], rather than saying it is
787 strict in every component of the dictionary [massive gratuitious
788 casing to take the dict apart].
790 But you could have examples where going for strictness would be better
791 than absence. Consider:
793 let x = something big
798 If \tr{x} is marked absent in \tr{f}, but not strict, and \tr{g} is
799 lazy, then the thunk for \tr{x} will be built. If \tr{f} was strict,
800 then we'd let-to-case it:
802 case something big of
808 findRecDemand :: StrAnalFlags
809 -> [TyCon] -- TyCons already seen; used to avoid
810 -- zooming into recursive types
811 -> (AbsVal -> AbsVal) -- The strictness function
812 -> (AbsVal -> AbsVal) -- The absence function
813 -> Type -- The type of the argument
816 findRecDemand strflags seen str_fn abs_fn ty
817 = if isPrimType ty then -- It's a primitive type!
820 else if not (anyBot (abs_fn AbsBot)) then -- It's absent
821 -- We prefer absence over strictness: see NOTE above.
824 else if not (all_strict ||
825 (num_strict && is_numeric_type ty) ||
826 (isBot (str_fn AbsBot))) then
827 WwLazy False -- It's not strict and we're not pretending
829 else -- It's strict (or we're pretending it is)!
831 case (maybeAppDataTyConExpandingDicts ty) of
835 Just (tycon,tycon_arg_tys,[data_con]) | tycon `not_elem` seen ->
836 -- Single constructor case, tycon not already seen higher up
838 cmpnt_tys = dataConArgTys data_con tycon_arg_tys
839 prod_len = length cmpnt_tys
842 = [ findRecDemand strflags (tycon:seen)
844 str_fn (mkMainlyTopProd prod_len i cmpnt_val)
847 abs_fn (mkMainlyTopProd prod_len i cmpnt_val)
850 | (cmpnt_ty, i) <- cmpnt_tys `zip` [1..] ]
852 if null compt_strict_infos then
853 if isEnumerationTyCon tycon then wwEnum else wwStrict
855 wwUnpack compt_strict_infos
857 not_elem = isn'tIn "findRecDemand"
860 -- Multi-constr data types, *or* an abstract data
861 -- types, *or* things we don't have a way of conveying
862 -- the info over module boundaries (class ops,
863 -- superdict sels, dfns).
864 if isEnumerationTyCon tycon then
869 (all_strict, num_strict) = strflags
872 = case (maybeAppDataTyConExpandingDicts ty) of -- NB: duplicates stuff done above
876 [intTyCon, integerTyCon,
877 doubleTyCon, floatTyCon,
878 wordTyCon, addrTyCon]
880 _{-something else-} -> False
882 is_elem = isIn "is_numeric_type"
884 -- mkMainlyTopProd: make an AbsProd that is all AbsTops ("n"-1 of
885 -- them) except for a given value in the "i"th position.
887 mkMainlyTopProd :: Int -> Int -> AbsVal -> AbsVal
889 mkMainlyTopProd n i val
891 befores = nOfThem (i-1) AbsTop
892 afters = nOfThem (n-i) AbsTop
894 AbsProd (befores ++ (val : afters))
897 %************************************************************************
899 \subsection[fixpoint]{Fixpointer for the strictness analyser}
901 %************************************************************************
903 The @fixpoint@ functions take a list of \tr{(binder, expr)} pairs, an
904 environment, and returns the abstract value of each binder.
906 The @cheapFixpoint@ function makes a conservative approximation,
907 by binding each of the variables to Top in their own right hand sides.
908 That allows us to make rapid progress, at the cost of a less-than-wonderful
912 cheapFixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
914 cheapFixpoint AbsAnal [id] [rhs] env
915 = [crudeAbsWiden (absEval AbsAnal rhs new_env)]
917 new_env = addOneToAbsValEnv env id AbsTop -- Unsafe starting point!
918 -- In the just-one-binding case, we guarantee to
919 -- find a fixed point in just one iteration,
920 -- because we are using only a two-point domain.
921 -- This improves matters in cases like:
923 -- f x y = letrec g = ...g...
926 -- Here, y isn't used at all, but if g is bound to
927 -- AbsBot we simply get AbsBot as the next
930 cheapFixpoint anal ids rhss env
931 = [widen anal (absEval anal rhs new_env) | rhs <- rhss]
932 -- We do just one iteration, starting from a safe
933 -- approximation. This won't do a good job in situations
935 -- \x -> letrec f = ...g...
939 -- Here, f will end up bound to Top after one iteration,
940 -- and hence we won't spot the strictness in x.
941 -- (A second iteration would solve this. ToDo: try the effect of
942 -- really searching for a fixed point.)
944 new_env = growAbsValEnvList env [(id,safe_val) | id <- ids]
947 = case anal of -- The safe starting point
953 mkLookupFun :: (key -> key -> Bool) -- Equality predicate
954 -> (key -> key -> Bool) -- Less-than predicate
955 -> [(key,val)] -- The assoc list
957 -> Maybe val -- The corresponding value
959 mkLookupFun eq lt alist s
960 = case [a | (s',a) <- alist, s' `eq` s] of
966 fixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
968 fixpoint anal [] _ env = []
970 fixpoint anal ids rhss env
971 = fix_loop initial_vals
974 = case anal of -- The (unsafe) starting point
975 StrAnal -> if (returnsRealWorld (idType id))
976 then AbsTop -- this is a massively horrible hack (SLPJ 95/05)
980 initial_vals = [ initial_val id | id <- ids ]
982 fix_loop :: [AbsVal] -> [AbsVal]
984 fix_loop current_widened_vals
986 new_env = growAbsValEnvList env (ids `zip` current_widened_vals)
987 new_vals = [ absEval anal rhs new_env | rhs <- rhss ]
988 new_widened_vals = map (widen anal) new_vals
990 if (and (zipWith sameVal current_widened_vals new_widened_vals)) then
993 -- NB: I was too chicken to make that a zipWithEqual,
994 -- lest I jump into a black hole. WDP 96/02
996 -- Return the widened values. We might get a slightly
997 -- better value by returning new_vals (which we used to
998 -- do, see below), but alas that means that whenever the
999 -- function is called we have to re-execute it, which is
1004 -- Return the un-widened values which may be a bit better
1005 -- than the widened ones, and are guaranteed safe, since
1006 -- they are one iteration beyond current_widened_vals,
1007 -- which itself is a fixed point.
1009 fix_loop new_widened_vals
1012 For absence analysis, we make do with a very very simple approach:
1013 look for convergence in a two-point domain.
1015 We used to use just one iteration, starting with the variables bound
1016 to @AbsBot@, which is safe.
1018 Prior to that, we used one iteration starting from @AbsTop@ (which
1019 isn't safe). Why isn't @AbsTop@ safe? Consider:
1027 Here, if p is @AbsBot@, then we'd better {\em not} end up with a ``fixed
1028 point'' of @d@ being @(AbsTop, AbsTop)@! An @AbsBot@ initial value is
1029 safe because it gives poison more often than really necessary, and
1030 thus may miss some absence, but will never claim absence when it ain't
1033 Anyway, one iteration starting with everything bound to @AbsBot@ give
1038 Here, f would always end up bound to @AbsBot@, which ain't very
1039 clever, because then it would introduce poison whenever it was
1040 applied. Much better to start with f bound to @AbsTop@, and widen it
1041 to @AbsBot@ if any poison shows up. In effect we look for convergence
1042 in the two-point @AbsTop@/@AbsBot@ domain.
1044 What we miss (compared with the cleverer strictness analysis) is
1045 spotting that in this case
1047 f = \ x y -> ...y...(f x y')...
1049 \tr{x} is actually absent, since it is only passed round the loop, never
1050 used. But who cares about missing that?
1052 NB: despite only having a two-point domain, we may still have many
1053 iterations, because there are several variables involved at once.