2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
10 module DmdAnal ( dmdAnalPgm ) where
12 #include "HsVersions.h"
14 import CmdLineOpts ( DynFlags, DynFlag(..), opt_MaxWorkerArgs )
15 import NewDemand -- All of it
17 import CoreUtils ( exprIsValue, exprArity )
18 import DataCon ( dataConTyCon )
19 import TyCon ( isProductTyCon, isRecursiveTyCon )
20 import Id ( Id, idType, idDemandInfo,
21 isDataConId, isImplicitId, isGlobalId,
22 idNewStrictness, idNewStrictness_maybe, getNewStrictness, setIdNewStrictness,
23 idNewDemandInfo, setIdNewDemandInfo, newStrictnessFromOld )
24 import IdInfo ( newDemand )
27 import UniqFM ( plusUFM_C, addToUFM_Directly, lookupUFM_Directly,
28 keysUFM, minusUFM, ufmToList, filterUFM )
29 import Type ( isUnLiftedType )
30 import CoreLint ( showPass, endPass )
31 import Util ( mapAndUnzip, mapAccumL, mapAccumR )
32 import BasicTypes ( Arity, TopLevelFlag(..), isTopLevel )
33 import Maybes ( orElse, expectJust )
39 * set a noinline pragma on bottoming Ids
41 * Consider f x = x+1 `fatbar` error (show x)
42 We'd like to unbox x, even if that means reboxing it in the error case.
45 instance Outputable TopLevelFlag where
49 %************************************************************************
51 \subsection{Top level stuff}
53 %************************************************************************
56 dmdAnalPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
57 dmdAnalPgm dflags binds
59 showPass dflags "Demand analysis" ;
60 let { binds_plus_dmds = do_prog binds ;
61 dmd_changes = get_changes binds_plus_dmds } ;
62 endPass dflags "Demand analysis"
63 Opt_D_dump_stranal binds_plus_dmds ;
65 -- Only if DEBUG is on, because only then is the old strictness analyser run
66 printDump (text "Changes in demands" $$ dmd_changes) ;
68 return binds_plus_dmds
71 do_prog :: [CoreBind] -> [CoreBind]
72 do_prog binds = snd $ mapAccumL dmdAnalTopBind emptySigEnv binds
74 dmdAnalTopBind :: SigEnv
77 dmdAnalTopBind sigs (NonRec id rhs)
78 | isImplicitId id -- Don't touch the info on constructors, selectors etc
79 = (sigs, NonRec id rhs) -- It's pre-computed in MkId.lhs
82 (sigs', _, (id', rhs')) = downRhs TopLevel sigs (id, rhs)
84 (sigs', NonRec id' rhs')
86 dmdAnalTopBind sigs (Rec pairs)
88 (sigs', _, pairs') = dmdFix TopLevel sigs pairs
94 %************************************************************************
96 \subsection{The analyser itself}
98 %************************************************************************
101 dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
103 dmdAnal sigs Abs e = (topDmdType, e)
105 dmdAnal sigs Lazy e = let
106 (res_ty, e') = dmdAnal sigs Eval e
108 (deferType res_ty, e')
109 -- It's important not to analyse e with a lazy demand because
110 -- a) When we encounter case s of (a,b) ->
111 -- we demand s with U(d1d2)... but if the overall demand is lazy
112 -- that is wrong, and we'd need to reduce the demand on s,
113 -- which is inconvenient
114 -- b) More important, consider
115 -- f (let x = R in x+x), where f is lazy
116 -- We still want to mark x as demanded, because it will be when we
117 -- enter the let. If we analyse f's arg with a Lazy demand, we'll
118 -- just mark x as Lazy
121 dmdAnal sigs dmd (Lit lit)
122 = (topDmdType, Lit lit)
124 dmdAnal sigs dmd (Var var)
125 = (dmdTransform sigs var dmd, Var var)
127 dmdAnal sigs dmd (Note n e)
128 = (dmd_ty, Note n e')
130 (dmd_ty, e') = dmdAnal sigs dmd' e
132 Coerce _ _ -> Eval -- This coerce usually arises from a recursive
133 other -> dmd -- newtype, and we don't want to look inside them
134 -- for exactly the same reason that we don't look
135 -- inside recursive products -- we might not reach
136 -- a fixpoint. So revert to a vanilla Eval demand
138 dmdAnal sigs dmd (App fun (Type ty))
139 = (fun_ty, App fun' (Type ty))
141 (fun_ty, fun') = dmdAnal sigs dmd fun
143 dmdAnal sigs dmd (App fun arg) -- Non-type arguments
144 = let -- [Type arg handled above]
145 (fun_ty, fun') = dmdAnal sigs (Call dmd) fun
146 (arg_ty, arg') = dmdAnal sigs arg_dmd arg
147 (arg_dmd, res_ty) = splitDmdTy fun_ty
149 (res_ty `bothType` arg_ty, App fun' arg')
151 dmdAnal sigs dmd (Lam var body)
154 (body_ty, body') = dmdAnal sigs dmd body
156 (body_ty, Lam var body')
158 | Call body_dmd <- dmd -- A call demand: good!
160 (body_ty, body') = dmdAnal sigs body_dmd body
161 (lam_ty, var') = annotateLamIdBndr body_ty var
163 (lam_ty, Lam var' body')
165 | otherwise -- Not enough demand on the lambda; but do the body
166 = let -- anyway to annotate it and gather free var info
167 (body_ty, body') = dmdAnal sigs Eval body
168 (lam_ty, var') = annotateLamIdBndr body_ty var
170 (deferType lam_ty, Lam var' body')
172 dmdAnal sigs dmd (Case scrut case_bndr [alt@(DataAlt dc,bndrs,rhs)])
173 | let tycon = dataConTyCon dc,
174 isProductTyCon tycon,
175 not (isRecursiveTyCon tycon)
177 bndr_ids = filter isId bndrs
178 (alt_ty, alt') = dmdAnalAlt sigs dmd alt
179 (alt_ty1, case_bndr') = annotateBndr alt_ty case_bndr
180 (_, bndrs', _) = alt'
182 -- Figure out whether the demand on the case binder is used, and use
183 -- that to set the scrut_dmd. This is utterly essential.
184 -- Consider f x = case x of y { (a,b) -> k y a }
185 -- If we just take scrut_demand = U(L,A), then we won't pass x to the
186 -- worker, so the worker will rebuild
187 -- x = (a, absent-error)
188 -- and that'll crash.
189 -- So at one stage I had:
190 -- dead_case_bndr = isAbsentDmd (idNewDemandInfo case_bndr')
191 -- keepity | dead_case_bndr = Drop
192 -- | otherwise = Keep
195 -- case x of y { (a,b) -> h y + a }
196 -- where h : U(LL) -> T
197 -- The above code would compute a Keep for x, since y is not Abs, which is silly
198 -- The insight is, of course, that a demand on y is a demand on the
199 -- scrutinee, so we need to `both` it with the scrut demand
201 scrut_dmd = Seq Drop Now [idNewDemandInfo b | b <- bndrs', isId b]
203 idNewDemandInfo case_bndr'
205 (scrut_ty, scrut') = dmdAnal sigs scrut_dmd scrut
207 (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' [alt'])
209 dmdAnal sigs dmd (Case scrut case_bndr alts)
211 (alt_tys, alts') = mapAndUnzip (dmdAnalAlt sigs dmd) alts
212 (scrut_ty, scrut') = dmdAnal sigs Eval scrut
213 (alt_ty, case_bndr') = annotateBndr (foldr1 lubType alt_tys) case_bndr
215 -- pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
216 (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' alts')
218 dmdAnal sigs dmd (Let (NonRec id rhs) body)
220 (sigs', lazy_fv, (id1, rhs')) = downRhs NotTopLevel sigs (id, rhs)
221 (body_ty, body') = dmdAnal sigs' dmd body
222 (body_ty1, id2) = annotateBndr body_ty id1
223 body_ty2 = addLazyFVs body_ty1 lazy_fv
225 -- pprTrace "dmdLet" (ppr id <+> ppr (sig,rhs_env))
226 (body_ty2, Let (NonRec id2 rhs') body')
228 dmdAnal sigs dmd (Let (Rec pairs) body)
230 bndrs = map fst pairs
231 (sigs', lazy_fv, pairs') = dmdFix NotTopLevel sigs pairs
232 (body_ty, body') = dmdAnal sigs' dmd body
233 body_ty1 = addLazyFVs body_ty lazy_fv
235 sigs' `seq` body_ty `seq`
237 (body_ty2, _) = annotateBndrs body_ty1 bndrs
238 -- Don't bother to add demand info to recursive
239 -- binders as annotateBndr does;
240 -- being recursive, we can't treat them strictly.
241 -- But we do need to remove the binders from the result demand env
243 (body_ty2, Let (Rec pairs') body')
246 dmdAnalAlt sigs dmd (con,bndrs,rhs)
248 (rhs_ty, rhs') = dmdAnal sigs dmd rhs
249 (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs
251 (alt_ty, (con, bndrs', rhs'))
254 %************************************************************************
256 \subsection{Bindings}
258 %************************************************************************
261 dmdFix :: TopLevelFlag
262 -> SigEnv -- Does not include bindings for this binding
265 [(Id,CoreExpr)]) -- Binders annotated with stricness info
267 dmdFix top_lvl sigs pairs
268 = loop 1 initial_sigs pairs
270 bndrs = map fst pairs
271 initial_sigs = extendSigEnvList sigs [(id, (initial_sig id, top_lvl)) | id <- bndrs]
274 -> SigEnv -- Already contains the current sigs
276 -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
278 | all (same_sig sigs sigs') bndrs = (sigs', lazy_fv, pairs')
279 -- Note: use pairs', not pairs. pairs' is the result of
280 -- processing the RHSs with sigs (= sigs'), whereas pairs
281 -- is the result of processing the RHSs with the *previous*
282 -- iteration of sigs.
283 | n >= 5 = pprTrace "dmdFix" (ppr n <+> (vcat
284 [ text "Sigs:" <+> ppr [(id,lookup sigs id, lookup sigs' id) | (id,_) <- pairs],
285 text "env:" <+> ppr (ufmToList sigs),
286 text "binds:" <+> ppr pairs]))
287 (loop (n+1) sigs' pairs')
288 | otherwise = {- pprTrace "dmdFixLoop" (ppr id_sigs) -} (loop (n+1) sigs' pairs')
290 -- Use the new signature to do the next pair
291 -- The occurrence analyser has arranged them in a good order
292 -- so this can significantly reduce the number of iterations needed
293 ((sigs',lazy_fv), pairs') = mapAccumL (my_downRhs top_lvl) (sigs, emptyDmdEnv) pairs
295 my_downRhs top_lvl (sigs,lazy_fv) (id,rhs)
296 = -- pprTrace "downRhs {" (ppr id <+> (ppr old_sig))
298 -- pprTrace "downRhsEnd" (ppr id <+> ppr new_sig <+> char '}' )
299 ((sigs', lazy_fv'), pair')
302 (sigs', lazy_fv1, pair') = downRhs top_lvl sigs (id,rhs)
303 lazy_fv' = plusUFM_C both lazy_fv lazy_fv1
304 old_sig = lookup sigs id
305 new_sig = lookup sigs' id
307 -- Get an initial strictness signature from the Id
308 -- itself. That way we make use of earlier iterations
309 -- of the fixpoint algorithm. (Cunning plan.)
310 -- Note that the cunning plan extends to the DmdEnv too,
311 -- since it is part of the strictness signature
312 initial_sig id = idNewStrictness_maybe id `orElse` botSig
314 same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
315 lookup sigs var = case lookupVarEnv sigs var of
318 downRhs :: TopLevelFlag
319 -> SigEnv -> (Id, CoreExpr)
320 -> (SigEnv, DmdEnv, (Id, CoreExpr))
321 -- Process the RHS of the binding, add the strictness signature
322 -- to the Id, and augment the environment with the signature as well.
324 downRhs top_lvl sigs (id, rhs)
325 = (sigs', lazy_fv, (id', rhs'))
327 arity = exprArity rhs -- The idArity may not be up to date
328 (rhs_ty, rhs') = dmdAnal sigs (vanillaCall arity) rhs
329 (lazy_fv, sig_ty) = mkSigTy id arity rhs rhs_ty
330 id' = id `setIdNewStrictness` sig_ty
331 sigs' = extendSigEnv top_lvl sigs id sig_ty
334 %************************************************************************
336 \subsection{Strictness signatures and types}
338 %************************************************************************
341 mkSigTy :: Id -> Arity -> CoreExpr -> DmdType -> (DmdEnv, StrictSig)
342 -- Take a DmdType and turn it into a StrictSig
343 mkSigTy id arity rhs (DmdType fv dmds res)
344 = (lazy_fv, mkStrictSig id arity dmd_ty)
346 dmd_ty = DmdType strict_fv final_dmds res'
348 lazy_fv = filterUFM (not . isStrictDmd) fv
349 strict_fv = filterUFM isStrictDmd fv
350 -- We put the strict FVs in the DmdType of the Id, so
351 -- that at its call sites we unleash demands on its strict fvs.
352 -- An example is 'roll' in imaginary/wheel-sieve2
353 -- Something like this:
355 -- go y = if ... then roll (x-1) else x+1
358 -- We want to see that roll is strict in x, which is because
359 -- go is called. So we put the DmdEnv for x in go's DmdType.
362 -- f :: Int -> Int -> Int
363 -- f x y = let t = x+1
364 -- h z = if z==0 then t else
365 -- if z==1 then x+1 else
369 -- Calling h does indeed evaluate x, but we can only see
370 -- that if we unleash a demand on x at the call site for t.
372 -- Incidentally, here's a place where lambda-lifting h would
373 -- lose the cigar --- we couldn't see the joint strictness in t/x
376 -- We don't want to put *all* the fv's from the RHS into the
377 -- DmdType, because that makes fixpointing very slow --- the
378 -- DmdType gets full of lazy demands that are slow to converge.
380 lazified_dmds = map lazify dmds
381 -- Get rid of defers in the arguments
382 final_dmds = setUnpackStrategy lazified_dmds
383 -- Set the unpacking strategy
385 res' = case (dmds, res) of
386 ([], RetCPR) | not (exprIsValue rhs) -> TopRes
388 -- If the rhs is a thunk, we forget the CPR info, because
389 -- it is presumably shared (else it would have been inlined, and
390 -- so we'd lose sharing if w/w'd it into a function.
392 -- DONE IN OLD CPR ANALYSER, BUT NOT YET HERE
393 -- Also, if the strictness analyser has figured out that it's strict,
394 -- the let-to-case transformation will happen, so again it's good.
395 -- (CPR analysis runs before the simplifier has had a chance to do
396 -- the let-to-case transform.)
397 -- This made a big difference to PrelBase.modInt, which had something like
398 -- modInt = \ x -> let r = ... -> I# v in
399 -- ...body strict in r...
400 -- r's RHS isn't a value yet; but modInt returns r in various branches, so
401 -- if r doesn't have the CPR property then neither does modInt
404 The unpack strategy determines whether we'll *really* unpack the argument,
405 or whether we'll just remember its strictness. If unpacking would give
406 rise to a *lot* of worker args, we may decide not to unpack after all.
409 setUnpackStrategy :: [Demand] -> [Demand]
411 = snd (go (opt_MaxWorkerArgs - nonAbsentArgs ds) ds)
413 go :: Int -- Max number of args available for sub-components of [Demand]
415 -> (Int, [Demand]) -- Args remaining after subcomponents of [Demand] are unpacked
417 go n (Seq keep _ cs : ds)
418 | n' >= 0 = Seq keep Now cs' `cons` go n'' ds
419 | otherwise = Eval `cons` go n ds
422 n' = n + box - non_abs_args
425 Drop -> 1 -- Add one to the budget if we drop the top-level arg
426 non_abs_args = nonAbsentArgs cs
427 -- Delete # of non-absent args to which we'll now be committed
429 go n (d:ds) = d `cons` go n ds
432 cons d (n,ds) = (n, d:ds)
434 nonAbsentArgs :: [Demand] -> Int
436 nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
437 nonAbsentArgs (d : ds) = 1 + nonAbsentArgs ds
441 %************************************************************************
443 \subsection{Strictness signatures and types}
445 %************************************************************************
448 splitDmdTy :: DmdType -> (Demand, DmdType)
449 -- Split off one function argument
450 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
451 splitDmdTy ty@(DmdType fv [] TopRes) = (topDmd, ty)
452 splitDmdTy ty@(DmdType fv [] BotRes) = (Abs, ty)
453 -- We already have a suitable demand on all
454 -- free vars, so no need to add more!
455 splitDmdTy (DmdType fv [] RetCPR) = panic "splitDmdTy"
459 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
461 addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd
462 | isTopLevel top_lvl = dmd_ty -- Don't record top level things
463 | otherwise = DmdType (extendVarEnv fv var dmd) ds res
465 addLazyFVs (DmdType fv ds res) lazy_fvs
466 = DmdType (plusUFM_C both fv lazy_fvs) ds res
468 annotateBndr :: DmdType -> Var -> (DmdType, Var)
469 -- The returned env has the var deleted
470 -- The returned var is annotated with demand info
471 -- No effect on the argument demands
472 annotateBndr dmd_ty@(DmdType fv ds res) var
473 | isTyVar var = (dmd_ty, var)
474 | otherwise = (DmdType fv' ds res, setIdNewDemandInfo var dmd)
476 (fv', dmd) = removeFV fv var res
478 annotateBndrs = mapAccumR annotateBndr
480 annotateLamIdBndr dmd_ty@(DmdType fv ds res) id
481 -- For lambdas we add the demand to the argument demands
482 -- Only called for Ids
484 (DmdType fv' (hacked_dmd:ds) res, setIdNewDemandInfo id hacked_dmd)
486 (fv', dmd) = removeFV fv id res
487 hacked_dmd = case dmd of
491 -- This gross hack is needed because otherwise we label
492 -- a lambda binder with demand 'B'. But in terms of calling
493 -- conventions that's Abs, because we don't pass it. But
494 -- when we do a w/w split we get
495 -- fw x = (\x y:B -> ...) x (error "oops")
496 -- And then the simplifier things the 'B' is a strict demand
497 -- and evaluates the (error "oops"). Sigh
499 removeFV fv var res = (fv', dmd)
501 fv' = fv `delVarEnv` var
502 dmd = lookupVarEnv fv var `orElse` deflt
503 deflt | isBotRes res = Bot
507 %************************************************************************
509 \subsection{Strictness signatures}
511 %************************************************************************
514 type SigEnv = VarEnv (StrictSig, TopLevelFlag)
515 -- We use the SigEnv to tell us whether to
516 -- record info about a variable in the DmdEnv
517 -- We do so if it's a LocalId, but not top-level
519 -- The DmdEnv gives the demand on the free vars of the function
520 -- when it is given enough args to satisfy the strictness signature
522 emptySigEnv = emptyVarEnv
524 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
525 extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl)
527 extendSigEnvList = extendVarEnvList
529 dmdTransform :: SigEnv -- The strictness environment
530 -> Id -- The function
531 -> Demand -- The demand on the function
532 -> DmdType -- The demand type of the function in this context
533 -- Returned DmdEnv includes the demand on
534 -- this function plus demand on its free variables
536 dmdTransform sigs var dmd
538 ------ DATA CONSTRUCTOR
539 | isDataConId var, -- Data constructor
540 Seq k Now ds <- res_dmd, -- and the demand looks inside its fields
541 let StrictSig dmd_ty = idNewStrictness var, -- It must have a strictness sig
542 let DmdType _ con_ds con_res = dmd_ty
543 = if length con_ds == length ds then -- Saturated, so unleash the demand
544 -- ds can be empty, when we are just seq'ing the thing
547 Keep -> zipWith lub ds con_ds
549 -- Important! If we Keep the constructor application, then
550 -- we need the demands the constructor places (usually lazy)
551 -- If not, we don't need to. For example:
552 -- f p@(x,y) = (p,y) -- S(AL)
554 -- It's vital that we don't calculate Absent for a!
556 mkDmdType emptyDmdEnv arg_ds con_res
557 -- Must remember whether it's a product, hence con_res, not TopRes
561 ------ IMPORTED FUNCTION
562 | isGlobalId var, -- Imported function
563 let StrictSig dmd_ty = getNewStrictness var
564 = if dmdTypeDepth dmd_ty <= call_depth then -- Saturated, so unleash the demand
569 ------ LOCAL LET/REC BOUND THING
570 | Just (StrictSig dmd_ty, top_lvl) <- lookupVarEnv sigs var
572 fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty
573 | otherwise = deferType dmd_ty
574 -- NB: it's important to use deferType, and not just return topDmdType
575 -- Consider let { f x y = p + x } in f 1
576 -- The application isn't saturated, but we must nevertheless propagate
577 -- a lazy demand for p!
579 addVarDmd top_lvl fn_ty var dmd
581 ------ LOCAL NON-LET/REC BOUND THING
582 | otherwise -- Default case
586 (call_depth, res_dmd) = splitCallDmd dmd
590 %************************************************************************
594 %************************************************************************
597 splitCallDmd :: Demand -> (Int, Demand)
598 splitCallDmd (Call d) = case splitCallDmd d of
600 splitCallDmd d = (0, d)
602 vanillaCall :: Arity -> Demand
604 vanillaCall n = Call (vanillaCall (n-1))
606 deferType :: DmdType -> DmdType
607 deferType (DmdType fv _ _) = DmdType (mapVarEnv defer fv) [] TopRes
608 -- Notice that we throw away info about both arguments and results
609 -- For example, f = let ... in \x -> x
610 -- We don't want to get a stricness type V->T for f.
612 defer :: Demand -> Demand
615 lazify :: Demand -> Demand
616 -- The 'Defer' demands are just Lazy at function boundaries
617 -- Ugly! Ask John how to improve it.
618 lazify (Seq k Defer ds) = Lazy
619 lazify (Seq k Now ds) = Seq k Now (map lazify ds)
620 lazify Bot = Abs -- Don't pass args that are consumed by bottom/err
626 betterStrictness :: StrictSig -> StrictSig -> Bool
627 betterStrictness (StrictSig t1) (StrictSig t2) = betterDmdType t1 t2
629 betterDmdType t1 t2 = (t1 `lubType` t2) == t2
631 betterDemand :: Demand -> Demand -> Bool
632 -- If d1 `better` d2, and d2 `better` d2, then d1==d2
633 betterDemand d1 d2 = (d1 `lub` d2) == d2
635 squashDmdEnv (StrictSig (DmdType fv ds res)) = StrictSig (DmdType emptyDmdEnv ds res)
639 %************************************************************************
641 \subsection{LUB and BOTH}
643 %************************************************************************
646 lub :: Demand -> Demand -> Demand
655 lub Abs Bot = Abs -- E.g f x y = if ... then x else error x
656 -- Then for y we get Abs `lub` Bot, and we really
660 lub Abs (Seq k _ ds) = Seq k Defer ds -- Very important ('radicals' example)
666 lub Eval (Seq k Now ds) = Eval -- Urk! Is this monotonic?
667 -- Was (incorrectly):
668 -- lub Eval (Seq k Now ds) = Seq Keep Now ds
670 -- Eval `lub` U(VV) is not S(VV)
671 -- (because the components aren't necessarily evaluated)
673 -- Was (correctly, but pessimistically):
674 -- lub Eval (Seq k Now ds) = Eval
675 -- Pessimistic because
677 -- f n (x:xs) = f (n+x) xs
678 -- Here we want to do better than just V for n. It's
679 -- unboxed in the (x:xs) case, and we might be prepared to
680 -- rebox it in the [] case.
681 -- To achieve this we could perhaps consider Eval to be equivalent to
684 lub Eval (Seq k Defer ds) = Lazy
687 lub (Call d1) (Call d2) = Call (lub d1 d2)
689 lub (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) (l1 `or_defer` l2) (lubs ds1 ds2)
691 -- The last clauses deal with the remaining cases for Call and Seq
692 lub d1@(Call _) d2@(Seq _ _ _) = pprPanic "lub" (ppr d1 $$ ppr d2)
693 lub d1 d2 = lub d2 d1
695 -- A Seq can have an empty list of demands, in the polymorphic case.
698 lubs ds1 ds2 = ASSERT( length ds1 == length ds2 ) zipWith lub ds1 ds2
700 or_defer Now Now = Now
703 -------------------------
704 -- Consider (if x then y else []) with demand V
705 -- Then the first branch gives {y->V} and the second
706 -- *implicitly* has {y->A}. So we must put {y->(V `lub` A)}
707 -- in the result env.
708 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
709 = DmdType lub_fv2 (zipWith lub ds1 ds2) (r1 `lubRes` r2)
711 lub_fv = plusUFM_C lub fv1 fv2
712 lub_fv1 = modifyEnv (not (isBotRes r1)) (Abs `lub`) fv2 fv1 lub_fv
713 lub_fv2 = modifyEnv (not (isBotRes r2)) (Abs `lub`) fv1 fv2 lub_fv1
714 -- lub is the identity for Bot
716 -------------------------
719 lubRes RetCPR RetCPR = RetCPR
720 lubRes r1 r2 = TopRes
722 -----------------------------------
723 vee :: Keepity -> Keepity -> Keepity
727 -----------------------------------
728 both :: Demand -> Demand -> Demand
733 -- The experimental one
734 -- The idea is that (error x) places on x
735 -- both demand Bot (like on all free vars)
736 -- and demand Eval (for the arg to error)
737 -- and we want the result to be Eval.
751 both Lazy (Seq k l ds) = Seq Keep l ds
753 -- Notice that the Seq case ensures that we have the
754 -- boxed value. The equation originally said
755 -- both (Seq k Now ds) = Seq Keep Now ds
756 -- but it's important that the Keep is switched on even
757 -- for a deferred demand. Otherwise a (Seq Drop Now [])
758 -- might both'd with the result, and then we won't pass
759 -- the boxed value. Here's an example:
760 -- (x-1) `seq` (x+1, x)
761 -- From the (x+1, x) we get (U*(V) `both` L), which must give S*(V)
762 -- From (x-1) we get U(V). Combining, we must get S(V).
763 -- If we got U*(V) from the pair, we'd end up with U(V), and that
764 -- can be a disaster if a component of the data structure is absent.
765 -- [Disaster = enter an absent argument.]
767 both Eval (Seq k l ds) = Seq Keep Now ds
768 both Eval (Call d) = Call d
771 both (Seq k1 Defer ds1) (Seq k2 Defer ds2) = Seq (k1 `vee` k2) Defer (boths ds1 ds2)
772 both (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) Now (boths ds1' ds2')
774 ds1' = case l1 of { Now -> ds1; Defer -> map defer ds1 }
775 ds2' = case l2 of { Now -> ds2; Defer -> map defer ds2 }
777 both (Call d1) (Call d2) = Call (d1 `both` d2)
779 -- The last clauses deal with the remaining cases for Call and Seq
780 both d1@(Call _) d2@(Seq _ _ _) = pprPanic "both" (ppr d1 $$ ppr d2)
781 both d1 d2 = both d2 d1
783 -----------------------------------
784 -- A Seq can have an empty list of demands, in the polymorphic case.
787 boths ds1 ds2 = ASSERT( length ds1 == length ds2 ) zipWith both ds1 ds2
789 -----------------------------------
790 bothRes :: DmdResult -> DmdResult -> DmdResult
791 -- Left-biased for CPR info
792 bothRes BotRes _ = BotRes
793 bothRes _ BotRes = BotRes
796 -----------------------------------
797 -- (t1 `bothType` t2) takes the argument/result info from t1,
798 -- using t2 just for its free-var info
799 bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
800 = DmdType both_fv2 ds1 r1
802 both_fv = plusUFM_C both fv1 fv2
803 both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
804 both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
805 -- both is the identity for Abs
809 modifyEnv :: Bool -- No-op if False
810 -> (Demand -> Demand) -- The zapper
811 -> DmdEnv -> DmdEnv -- Env1 and Env2
812 -> DmdEnv -> DmdEnv -- Transform this env
813 -- Zap anything in Env1 but not in Env2
814 -- Assume: dom(env) includes dom(Env1) and dom(Env2)
816 modifyEnv need_to_modify zapper env1 env2 env
817 | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2))
820 zap uniq env = addToUFM_Directly env uniq (zapper current_val)
822 current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
826 %************************************************************************
828 \subsection{Miscellaneous
830 %************************************************************************
834 get_changes binds = vcat (map get_changes_bind binds)
836 get_changes_bind (Rec pairs) = vcat (map get_changes_pr pairs)
837 get_changes_bind (NonRec id rhs) = get_changes_pr (id,rhs)
839 get_changes_pr (id,rhs)
840 | isImplicitId id = empty -- We don't look inside these
841 | otherwise = get_changes_var id $$ get_changes_expr rhs
844 | isId var = get_changes_str var $$ get_changes_dmd var
847 get_changes_expr (Type t) = empty
848 get_changes_expr (Var v) = empty
849 get_changes_expr (Lit l) = empty
850 get_changes_expr (Note n e) = get_changes_expr e
851 get_changes_expr (App e1 e2) = get_changes_expr e1 $$ get_changes_expr e2
852 get_changes_expr (Lam b e) = {- get_changes_var b $$ -} get_changes_expr e
853 get_changes_expr (Let b e) = get_changes_bind b $$ get_changes_expr e
854 get_changes_expr (Case e b a) = get_changes_expr e $$ {- get_changes_var b $$ -} vcat (map get_changes_alt a)
856 get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs
859 | new_better && old_better = empty
860 | new_better = message "BETTER"
861 | old_better = message "WORSE"
862 | otherwise = message "INCOMPARABLE"
864 message word = text word <+> text "strictness for" <+> ppr id <+> info
865 info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
866 new = squashDmdEnv (idNewStrictness id) -- Don't report diffs in the env
867 old = newStrictnessFromOld id
868 old_better = old `betterStrictness` new
869 new_better = new `betterStrictness` old
872 | isUnLiftedType (idType id) = empty -- Not useful
873 | new_better && old_better = empty
874 | new_better = message "BETTER"
875 | old_better = message "WORSE"
876 | otherwise = message "INCOMPARABLE"
878 message word = text word <+> text "demand for" <+> ppr id <+> info
879 info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
880 new = lazify (idNewDemandInfo id) -- Lazify to avoid spurious improvements
881 old = newDemand (idDemandInfo id)
882 new_better = new `betterDemand` old
883 old_better = old `betterDemand` new