2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
10 module DmdAnal ( dmdAnalPgm, dmdAnalTopRhs,
11 both {- needed by WwLib -}
14 #include "HsVersions.h"
16 import CmdLineOpts ( DynFlags, DynFlag(..), opt_MaxWorkerArgs )
17 import NewDemand -- All of it
20 import CoreUtils ( exprIsValue, exprIsTrivial, exprArity )
21 import DataCon ( dataConTyCon )
22 import TyCon ( isProductTyCon, isRecursiveTyCon )
23 import Id ( Id, idType, idInlinePragma,
24 isDataConWorkId, isGlobalId, idArity,
26 idDemandInfo, idStrictness, idCprInfo, idName,
28 idNewStrictness, idNewStrictness_maybe,
29 setIdNewStrictness, idNewDemandInfo,
30 idNewDemandInfo_maybe,
34 import IdInfo ( newStrictnessFromOld, newDemand )
38 import TysWiredIn ( unboxedPairDataCon )
39 import TysPrim ( realWorldStatePrimTy )
40 import UniqFM ( plusUFM_C, addToUFM_Directly, lookupUFM_Directly,
41 keysUFM, minusUFM, ufmToList, filterUFM )
42 import Type ( isUnLiftedType, coreEqType )
43 import CoreLint ( showPass, endPass )
44 import Util ( mapAndUnzip, mapAccumL, mapAccumR, lengthIs )
45 import BasicTypes ( Arity, TopLevelFlag(..), isTopLevel, isNeverActive,
47 import Maybes ( orElse, expectJust )
53 * set a noinline pragma on bottoming Ids
55 * Consider f x = x+1 `fatbar` error (show x)
56 We'd like to unbox x, even if that means reboxing it in the error case.
59 %************************************************************************
61 \subsection{Top level stuff}
63 %************************************************************************
66 dmdAnalPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
67 dmdAnalPgm dflags binds
69 showPass dflags "Demand analysis" ;
70 let { binds_plus_dmds = do_prog binds } ;
72 endPass dflags "Demand analysis"
73 Opt_D_dump_stranal binds_plus_dmds ;
75 -- Only if OLD_STRICTNESS is on, because only then is the old
76 -- strictness analyser run
77 let { dmd_changes = get_changes binds_plus_dmds } ;
78 printDump (text "Changes in demands" $$ dmd_changes) ;
80 return binds_plus_dmds
83 do_prog :: [CoreBind] -> [CoreBind]
84 do_prog binds = snd $ mapAccumL dmdAnalTopBind emptySigEnv binds
86 dmdAnalTopBind :: SigEnv
89 dmdAnalTopBind sigs (NonRec id rhs)
91 ( _, _, (_, rhs1)) = dmdAnalRhs TopLevel NonRecursive sigs (id, rhs)
92 (sigs2, _, (id2, rhs2)) = dmdAnalRhs TopLevel NonRecursive sigs (id, rhs1)
93 -- Do two passes to improve CPR information
94 -- See comments with ignore_cpr_info in mk_sig_ty
95 -- and with extendSigsWithLam
97 (sigs2, NonRec id2 rhs2)
99 dmdAnalTopBind sigs (Rec pairs)
101 (sigs', _, pairs') = dmdFix TopLevel sigs pairs
102 -- We get two iterations automatically
103 -- c.f. the NonRec case above
109 dmdAnalTopRhs :: CoreExpr -> (StrictSig, CoreExpr)
110 -- Analyse the RHS and return
111 -- a) appropriate strictness info
112 -- b) the unfolding (decorated with stricntess info)
116 arity = exprArity rhs
117 (rhs_ty, rhs') = dmdAnal emptySigEnv (vanillaCall arity) rhs
118 sig = mkTopSigTy rhs rhs_ty
121 %************************************************************************
123 \subsection{The analyser itself}
125 %************************************************************************
128 dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
130 dmdAnal sigs Abs e = (topDmdType, e)
133 | not (isStrictDmd dmd)
135 (res_ty, e') = dmdAnal sigs evalDmd e
137 (deferType res_ty, e')
138 -- It's important not to analyse e with a lazy demand because
139 -- a) When we encounter case s of (a,b) ->
140 -- we demand s with U(d1d2)... but if the overall demand is lazy
141 -- that is wrong, and we'd need to reduce the demand on s,
142 -- which is inconvenient
143 -- b) More important, consider
144 -- f (let x = R in x+x), where f is lazy
145 -- We still want to mark x as demanded, because it will be when we
146 -- enter the let. If we analyse f's arg with a Lazy demand, we'll
147 -- just mark x as Lazy
148 -- c) The application rule wouldn't be right either
149 -- Evaluating (f x) in a L demand does *not* cause
150 -- evaluation of f in a C(L) demand!
153 dmdAnal sigs dmd (Lit lit)
154 = (topDmdType, Lit lit)
156 dmdAnal sigs dmd (Var var)
157 = (dmdTransform sigs var dmd, Var var)
159 dmdAnal sigs dmd (Note n e)
160 = (dmd_ty, Note n e')
162 (dmd_ty, e') = dmdAnal sigs dmd' e
164 Coerce _ _ -> evalDmd -- This coerce usually arises from a recursive
165 other -> dmd -- newtype, and we don't want to look inside them
166 -- for exactly the same reason that we don't look
167 -- inside recursive products -- we might not reach
168 -- a fixpoint. So revert to a vanilla Eval demand
170 dmdAnal sigs dmd (App fun (Type ty))
171 = (fun_ty, App fun' (Type ty))
173 (fun_ty, fun') = dmdAnal sigs dmd fun
175 -- Lots of the other code is there to make this
176 -- beautiful, compositional, application rule :-)
177 dmdAnal sigs dmd e@(App fun arg) -- Non-type arguments
178 = let -- [Type arg handled above]
179 (fun_ty, fun') = dmdAnal sigs (Call dmd) fun
180 (arg_ty, arg') = dmdAnal sigs arg_dmd arg
181 (arg_dmd, res_ty) = splitDmdTy fun_ty
183 (res_ty `bothType` arg_ty, App fun' arg')
185 dmdAnal sigs dmd (Lam var body)
188 (body_ty, body') = dmdAnal sigs dmd body
190 (body_ty, Lam var body')
192 | Call body_dmd <- dmd -- A call demand: good!
194 sigs' = extendSigsWithLam sigs var
195 (body_ty, body') = dmdAnal sigs' body_dmd body
196 (lam_ty, var') = annotateLamIdBndr body_ty var
198 (lam_ty, Lam var' body')
200 | otherwise -- Not enough demand on the lambda; but do the body
201 = let -- anyway to annotate it and gather free var info
202 (body_ty, body') = dmdAnal sigs evalDmd body
203 (lam_ty, var') = annotateLamIdBndr body_ty var
205 (deferType lam_ty, Lam var' body')
207 dmdAnal sigs dmd (Case scrut case_bndr ty [alt@(DataAlt dc,bndrs,rhs)])
208 | let tycon = dataConTyCon dc,
209 isProductTyCon tycon,
210 not (isRecursiveTyCon tycon)
212 sigs_alt = extendSigEnv NotTopLevel sigs case_bndr case_bndr_sig
213 (alt_ty, alt') = dmdAnalAlt sigs_alt dmd alt
214 (alt_ty1, case_bndr') = annotateBndr alt_ty case_bndr
215 (_, bndrs', _) = alt'
216 case_bndr_sig = cprSig
217 -- Inside the alternative, the case binder has the CPR property.
218 -- Meaning that a case on it will successfully cancel.
220 -- f True x = case x of y { I# x' -> if x' ==# 3 then y else I# 8 }
223 -- We want f to have the CPR property:
224 -- f b x = case fw b x of { r -> I# r }
225 -- fw True x = case x of y { I# x' -> if x' ==# 3 then x' else 8 }
228 -- Figure out whether the demand on the case binder is used, and use
229 -- that to set the scrut_dmd. This is utterly essential.
230 -- Consider f x = case x of y { (a,b) -> k y a }
231 -- If we just take scrut_demand = U(L,A), then we won't pass x to the
232 -- worker, so the worker will rebuild
233 -- x = (a, absent-error)
234 -- and that'll crash.
235 -- So at one stage I had:
236 -- dead_case_bndr = isAbsentDmd (idNewDemandInfo case_bndr')
237 -- keepity | dead_case_bndr = Drop
238 -- | otherwise = Keep
241 -- case x of y { (a,b) -> h y + a }
242 -- where h : U(LL) -> T
243 -- The above code would compute a Keep for x, since y is not Abs, which is silly
244 -- The insight is, of course, that a demand on y is a demand on the
245 -- scrutinee, so we need to `both` it with the scrut demand
247 scrut_dmd = Eval (Prod [idNewDemandInfo b | b <- bndrs', isId b])
249 idNewDemandInfo case_bndr'
251 (scrut_ty, scrut') = dmdAnal sigs scrut_dmd scrut
253 (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' ty [alt'])
255 dmdAnal sigs dmd (Case scrut case_bndr ty alts)
257 (alt_tys, alts') = mapAndUnzip (dmdAnalAlt sigs dmd) alts
258 (scrut_ty, scrut') = dmdAnal sigs evalDmd scrut
259 (alt_ty, case_bndr') = annotateBndr (foldr1 lubType alt_tys) case_bndr
261 -- pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
262 (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' ty alts')
264 dmdAnal sigs dmd (Let (NonRec id rhs) body)
266 (sigs', lazy_fv, (id1, rhs')) = dmdAnalRhs NotTopLevel NonRecursive sigs (id, rhs)
267 (body_ty, body') = dmdAnal sigs' dmd body
268 (body_ty1, id2) = annotateBndr body_ty id1
269 body_ty2 = addLazyFVs body_ty1 lazy_fv
271 -- If the actual demand is better than the vanilla call
272 -- demand, you might think that we might do better to re-analyse
273 -- the RHS with the stronger demand.
274 -- But (a) That seldom happens, because it means that *every* path in
275 -- the body of the let has to use that stronger demand
276 -- (b) It often happens temporarily in when fixpointing, because
277 -- the recursive function at first seems to place a massive demand.
278 -- But we don't want to go to extra work when the function will
279 -- probably iterate to something less demanding.
280 -- In practice, all the times the actual demand on id2 is more than
281 -- the vanilla call demand seem to be due to (b). So we don't
282 -- bother to re-analyse the RHS.
283 (body_ty2, Let (NonRec id2 rhs') body')
285 dmdAnal sigs dmd (Let (Rec pairs) body)
287 bndrs = map fst pairs
288 (sigs', lazy_fv, pairs') = dmdFix NotTopLevel sigs pairs
289 (body_ty, body') = dmdAnal sigs' dmd body
290 body_ty1 = addLazyFVs body_ty lazy_fv
292 sigs' `seq` body_ty `seq`
294 (body_ty2, _) = annotateBndrs body_ty1 bndrs
295 -- Don't bother to add demand info to recursive
296 -- binders as annotateBndr does;
297 -- being recursive, we can't treat them strictly.
298 -- But we do need to remove the binders from the result demand env
300 (body_ty2, Let (Rec pairs') body')
303 dmdAnalAlt sigs dmd (con,bndrs,rhs)
305 (rhs_ty, rhs') = dmdAnal sigs dmd rhs
306 (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs
307 final_alt_ty | io_hack_reqd = alt_ty `lubType` topDmdType
310 -- There's a hack here for I/O operations. Consider
311 -- case foo x s of { (# s, r #) -> y }
312 -- Is this strict in 'y'. Normally yes, but what if 'foo' is an I/O
313 -- operation that simply terminates the program (not in an erroneous way)?
314 -- In that case we should not evaluate y before the call to 'foo'.
315 -- Hackish solution: spot the IO-like situation and add a virtual branch,
319 -- other -> return ()
320 -- So the 'y' isn't necessarily going to be evaluated
322 -- A more complete example where this shows up is:
323 -- do { let len = <expensive> ;
324 -- ; when (...) (exitWith ExitSuccess)
327 io_hack_reqd = con == DataAlt unboxedPairDataCon &&
328 idType (head bndrs) `coreEqType` realWorldStatePrimTy
330 (final_alt_ty, (con, bndrs', rhs'))
333 %************************************************************************
335 \subsection{Bindings}
337 %************************************************************************
340 dmdFix :: TopLevelFlag
341 -> SigEnv -- Does not include bindings for this binding
344 [(Id,CoreExpr)]) -- Binders annotated with stricness info
346 dmdFix top_lvl sigs orig_pairs
347 = loop 1 initial_sigs orig_pairs
349 bndrs = map fst orig_pairs
350 initial_sigs = extendSigEnvList sigs [(id, (initialSig id, top_lvl)) | id <- bndrs]
353 -> SigEnv -- Already contains the current sigs
355 -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
358 = (sigs', lazy_fv, pairs')
359 -- Note: use pairs', not pairs. pairs' is the result of
360 -- processing the RHSs with sigs (= sigs'), whereas pairs
361 -- is the result of processing the RHSs with the *previous*
362 -- iteration of sigs.
364 | n >= 10 = pprTrace "dmdFix loop" (ppr n <+> (vcat
365 [ text "Sigs:" <+> ppr [(id,lookup sigs id, lookup sigs' id) | (id,_) <- pairs],
366 text "env:" <+> ppr (ufmToList sigs),
367 text "binds:" <+> pprCoreBinding (Rec pairs)]))
368 (emptySigEnv, lazy_fv, orig_pairs) -- Safe output
369 -- The lazy_fv part is really important! orig_pairs has no strictness
370 -- info, including nothing about free vars. But if we have
371 -- letrec f = ....y..... in ...f...
372 -- where 'y' is free in f, we must record that y is mentioned,
373 -- otherwise y will get recorded as absent altogether
375 | otherwise = loop (n+1) sigs' pairs'
377 found_fixpoint = all (same_sig sigs sigs') bndrs
378 -- Use the new signature to do the next pair
379 -- The occurrence analyser has arranged them in a good order
380 -- so this can significantly reduce the number of iterations needed
381 ((sigs',lazy_fv), pairs') = mapAccumL (my_downRhs top_lvl) (sigs, emptyDmdEnv) pairs
383 my_downRhs top_lvl (sigs,lazy_fv) (id,rhs)
384 = -- pprTrace "downRhs {" (ppr id <+> (ppr old_sig))
386 -- pprTrace "downRhsEnd" (ppr id <+> ppr new_sig <+> char '}' )
387 ((sigs', lazy_fv'), pair')
390 (sigs', lazy_fv1, pair') = dmdAnalRhs top_lvl Recursive sigs (id,rhs)
391 lazy_fv' = plusUFM_C both lazy_fv lazy_fv1
392 -- old_sig = lookup sigs id
393 -- new_sig = lookup sigs' id
395 same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
396 lookup sigs var = case lookupVarEnv sigs var of
399 -- Get an initial strictness signature from the Id
400 -- itself. That way we make use of earlier iterations
401 -- of the fixpoint algorithm. (Cunning plan.)
402 -- Note that the cunning plan extends to the DmdEnv too,
403 -- since it is part of the strictness signature
404 initialSig id = idNewStrictness_maybe id `orElse` botSig
406 dmdAnalRhs :: TopLevelFlag -> RecFlag
407 -> SigEnv -> (Id, CoreExpr)
408 -> (SigEnv, DmdEnv, (Id, CoreExpr))
409 -- Process the RHS of the binding, add the strictness signature
410 -- to the Id, and augment the environment with the signature as well.
412 dmdAnalRhs top_lvl rec_flag sigs (id, rhs)
413 = (sigs', lazy_fv, (id', rhs'))
415 arity = idArity id -- The idArity should be up to date
416 -- The simplifier was run just beforehand
417 (rhs_dmd_ty, rhs') = dmdAnal sigs (vanillaCall arity) rhs
418 (lazy_fv, sig_ty) = WARN( arity /= dmdTypeDepth rhs_dmd_ty && not (exprIsTrivial rhs), ppr id )
419 -- The RHS can be eta-reduced to just a variable,
420 -- in which case we should not complain.
421 mkSigTy top_lvl rec_flag id rhs rhs_dmd_ty
422 id' = id `setIdNewStrictness` sig_ty
423 sigs' = extendSigEnv top_lvl sigs id sig_ty
426 %************************************************************************
428 \subsection{Strictness signatures and types}
430 %************************************************************************
433 mkTopSigTy :: CoreExpr -> DmdType -> StrictSig
434 -- Take a DmdType and turn it into a StrictSig
435 -- NB: not used for never-inline things; hence False
436 mkTopSigTy rhs dmd_ty = snd (mk_sig_ty False False rhs dmd_ty)
438 mkSigTy :: TopLevelFlag -> RecFlag -> Id -> CoreExpr -> DmdType -> (DmdEnv, StrictSig)
439 mkSigTy top_lvl rec_flag id rhs dmd_ty
440 = mk_sig_ty never_inline thunk_cpr_ok rhs dmd_ty
442 never_inline = isNeverActive (idInlinePragma id)
443 maybe_id_dmd = idNewDemandInfo_maybe id
444 -- Is Nothing the first time round
447 | isTopLevel top_lvl = False -- Top level things don't get
448 -- their demandInfo set at all
449 | isRec rec_flag = False -- Ditto recursive things
450 | Just dmd <- maybe_id_dmd = isStrictDmd dmd
451 | otherwise = True -- Optimistic, first time round
455 The thunk_cpr_ok stuff [CPR-AND-STRICTNESS]
456 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
457 If the rhs is a thunk, we usually forget the CPR info, because
458 it is presumably shared (else it would have been inlined, and
459 so we'd lose sharing if w/w'd it into a function.
461 However, if the strictness analyser has figured out (in a previous
462 iteration) that it's strict, then we DON'T need to forget the CPR info.
463 Instead we can retain the CPR info and do the thunk-splitting transform
464 (see WorkWrap.splitThunk).
466 This made a big difference to PrelBase.modInt, which had something like
467 modInt = \ x -> let r = ... -> I# v in
468 ...body strict in r...
469 r's RHS isn't a value yet; but modInt returns r in various branches, so
470 if r doesn't have the CPR property then neither does modInt
471 Another case I found in practice (in Complex.magnitude), looks like this:
472 let k = if ... then I# a else I# b
473 in ... body strict in k ....
474 (For this example, it doesn't matter whether k is returned as part of
475 the overall result; but it does matter that k's RHS has the CPR property.)
476 Left to itself, the simplifier will make a join point thus:
477 let $j k = ...body strict in k...
478 if ... then $j (I# a) else $j (I# b)
479 With thunk-splitting, we get instead
480 let $j x = let k = I#x in ...body strict in k...
481 in if ... then $j a else $j b
482 This is much better; there's a good chance the I# won't get allocated.
484 The difficulty with this is that we need the strictness type to
485 look at the body... but we now need the body to calculate the demand
486 on the variable, so we can decide whether its strictness type should
487 have a CPR in it or not. Simple solution:
488 a) use strictness info from the previous iteration
489 b) make sure we do at least 2 iterations, by doing a second
490 round for top-level non-recs. Top level recs will get at
491 least 2 iterations except for totally-bottom functions
492 which aren't very interesting anyway.
494 NB: strictly_demanded is never true of a top-level Id, or of a recursive Id.
496 The Nothing case in thunk_cpr_ok [CPR-AND-STRICTNESS]
497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
498 Demand info now has a 'Nothing' state, just like strictness info.
499 The analysis works from 'dangerous' towards a 'safe' state; so we
500 start with botSig for 'Nothing' strictness infos, and we start with
501 "yes, it's demanded" for 'Nothing' in the demand info. The
502 fixpoint iteration will sort it all out.
504 We can't start with 'not-demanded' because then consider
508 if ... then t else I# y else f x'
510 In the first iteration we'd have no demand info for x, so assume
511 not-demanded; then we'd get TopRes for f's CPR info. Next iteration
512 we'd see that t was demanded, and so give it the CPR property, but by
513 now f has TopRes, so it will stay TopRes. Instead, with the Nothing
514 setting the first time round, we say 'yes t is demanded' the first
517 However, this does mean that for non-recursive bindings we must
518 iterate twice to be sure of not getting over-optimistic CPR info,
519 in the case where t turns out to be not-demanded. This is handled
524 mk_sig_ty never_inline thunk_cpr_ok rhs (DmdType fv dmds res)
525 | never_inline && not (isBotRes res)
527 -- Don't strictness-analyse NOINLINE things. Why not? Because
528 -- the NOINLINE says "don't expose any of the inner workings at the call
529 -- site" and the strictness is certainly an inner working.
531 -- More concretely, the demand analyser discovers the following strictness
532 -- for unsafePerformIO: C(U(AV))
534 -- unsafePerformIO (\s -> let r = f x in
535 -- case writeIORef v r s of (# s1, _ #) ->
537 -- The strictness analyser will find that the binding for r is strict,
538 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
539 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
542 -- Solution: don't expose the strictness of unsafePerformIO.
544 -- But we do want to expose the strictness of error functions,
545 -- which are also often marked NOINLINE
546 -- {-# NOINLINE foo #-}
547 -- foo x = error ("wubble buggle" ++ x)
548 -- So (hack, hack) we only drop the strictness for non-bottom things
549 -- This is all very unsatisfactory.
550 = (deferEnv fv, topSig)
553 = (lazy_fv, mkStrictSig dmd_ty)
555 dmd_ty = DmdType strict_fv final_dmds res'
557 lazy_fv = filterUFM (not . isStrictDmd) fv
558 strict_fv = filterUFM isStrictDmd fv
559 -- We put the strict FVs in the DmdType of the Id, so
560 -- that at its call sites we unleash demands on its strict fvs.
561 -- An example is 'roll' in imaginary/wheel-sieve2
562 -- Something like this:
564 -- go y = if ... then roll (x-1) else x+1
567 -- We want to see that roll is strict in x, which is because
568 -- go is called. So we put the DmdEnv for x in go's DmdType.
571 -- f :: Int -> Int -> Int
572 -- f x y = let t = x+1
573 -- h z = if z==0 then t else
574 -- if z==1 then x+1 else
578 -- Calling h does indeed evaluate x, but we can only see
579 -- that if we unleash a demand on x at the call site for t.
581 -- Incidentally, here's a place where lambda-lifting h would
582 -- lose the cigar --- we couldn't see the joint strictness in t/x
585 -- We don't want to put *all* the fv's from the RHS into the
586 -- DmdType, because that makes fixpointing very slow --- the
587 -- DmdType gets full of lazy demands that are slow to converge.
589 final_dmds = setUnpackStrategy dmds
590 -- Set the unpacking strategy
593 RetCPR | ignore_cpr_info -> TopRes
595 ignore_cpr_info = not (exprIsValue rhs || thunk_cpr_ok)
598 The unpack strategy determines whether we'll *really* unpack the argument,
599 or whether we'll just remember its strictness. If unpacking would give
600 rise to a *lot* of worker args, we may decide not to unpack after all.
603 setUnpackStrategy :: [Demand] -> [Demand]
605 = snd (go (opt_MaxWorkerArgs - nonAbsentArgs ds) ds)
607 go :: Int -- Max number of args available for sub-components of [Demand]
609 -> (Int, [Demand]) -- Args remaining after subcomponents of [Demand] are unpacked
611 go n (Eval (Prod cs) : ds)
612 | n' >= 0 = Eval (Prod cs') `cons` go n'' ds
613 | otherwise = Box (Eval (Prod cs)) `cons` go n ds
616 n' = n + 1 - non_abs_args
617 -- Add one to the budget 'cos we drop the top-level arg
618 non_abs_args = nonAbsentArgs cs
619 -- Delete # of non-absent args to which we'll now be committed
621 go n (d:ds) = d `cons` go n ds
624 cons d (n,ds) = (n, d:ds)
626 nonAbsentArgs :: [Demand] -> Int
628 nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
629 nonAbsentArgs (d : ds) = 1 + nonAbsentArgs ds
633 %************************************************************************
635 \subsection{Strictness signatures and types}
637 %************************************************************************
640 splitDmdTy :: DmdType -> (Demand, DmdType)
641 -- Split off one function argument
642 -- We already have a suitable demand on all
643 -- free vars, so no need to add more!
644 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
645 splitDmdTy ty@(DmdType fv [] res_ty) = (resTypeArgDmd res_ty, ty)
649 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
651 addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd
652 | isTopLevel top_lvl = dmd_ty -- Don't record top level things
653 | otherwise = DmdType (extendVarEnv fv var dmd) ds res
655 addLazyFVs (DmdType fv ds res) lazy_fvs
656 = DmdType both_fv1 ds res
658 both_fv = (plusUFM_C both fv lazy_fvs)
659 both_fv1 = modifyEnv (isBotRes res) (`both` Bot) lazy_fvs fv both_fv
660 -- This modifyEnv is vital. Consider
661 -- let f = \x -> (x,y)
663 -- Here, y is treated as a lazy-fv of f, but we must `both` that L
664 -- demand with the bottom coming up from 'error'
666 -- I got a loop in the fixpointer without this, due to an interaction
667 -- with the lazy_fv filtering in mkSigTy. Roughly, it was
669 -- = letrec g y = x `fatbar`
670 -- letrec h z = z + ...g...
673 -- In the initial iteration for f, f=Bot
674 -- Suppose h is found to be strict in z, but the occurrence of g in its RHS
675 -- is lazy. Now consider the fixpoint iteration for g, esp the demands it
676 -- places on its free variables. Suppose it places none. Then the
677 -- x `fatbar` ...call to h...
678 -- will give a x->V demand for x. That turns into a L demand for x,
679 -- which floats out of the defn for h. Without the modifyEnv, that
680 -- L demand doesn't get both'd with the Bot coming up from the inner
681 -- call to f. So we just get an L demand for x for g.
683 -- A better way to say this is that the lazy-fv filtering should give the
684 -- same answer as putting the lazy fv demands in the function's type.
686 annotateBndr :: DmdType -> Var -> (DmdType, Var)
687 -- The returned env has the var deleted
688 -- The returned var is annotated with demand info
689 -- No effect on the argument demands
690 annotateBndr dmd_ty@(DmdType fv ds res) var
691 | isTyVar var = (dmd_ty, var)
692 | otherwise = (DmdType fv' ds res, setIdNewDemandInfo var dmd)
694 (fv', dmd) = removeFV fv var res
696 annotateBndrs = mapAccumR annotateBndr
698 annotateLamIdBndr dmd_ty@(DmdType fv ds res) id
699 -- For lambdas we add the demand to the argument demands
700 -- Only called for Ids
702 (DmdType fv' (hacked_dmd:ds) res, setIdNewDemandInfo id hacked_dmd)
704 (fv', dmd) = removeFV fv id res
705 hacked_dmd = argDemand dmd
706 -- This call to argDemand is vital, because otherwise we label
707 -- a lambda binder with demand 'B'. But in terms of calling
708 -- conventions that's Abs, because we don't pass it. But
709 -- when we do a w/w split we get
710 -- fw x = (\x y:B -> ...) x (error "oops")
711 -- And then the simplifier things the 'B' is a strict demand
712 -- and evaluates the (error "oops"). Sigh
714 removeFV fv id res = (fv', zapUnlifted id dmd)
716 fv' = fv `delVarEnv` id
717 dmd = lookupVarEnv fv id `orElse` deflt
718 deflt | isBotRes res = Bot
721 -- For unlifted-type variables, we are only
722 -- interested in Bot/Abs/Box Abs
723 zapUnlifted is Bot = Bot
724 zapUnlifted id Abs = Abs
725 zapUnlifted id dmd | isUnLiftedType (idType id) = lazyDmd
729 %************************************************************************
731 \subsection{Strictness signatures}
733 %************************************************************************
736 type SigEnv = VarEnv (StrictSig, TopLevelFlag)
737 -- We use the SigEnv to tell us whether to
738 -- record info about a variable in the DmdEnv
739 -- We do so if it's a LocalId, but not top-level
741 -- The DmdEnv gives the demand on the free vars of the function
742 -- when it is given enough args to satisfy the strictness signature
744 emptySigEnv = emptyVarEnv
746 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
747 extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl)
749 extendSigEnvList = extendVarEnvList
751 extendSigsWithLam :: SigEnv -> Id -> SigEnv
752 -- Extend the SigEnv when we meet a lambda binder
753 -- If the binder is marked demanded with a product demand, then give it a CPR
754 -- signature, because in the likely event that this is a lambda on a fn defn
755 -- [we only use this when the lambda is being consumed with a call demand],
756 -- it'll be w/w'd and so it will be CPR-ish. E.g.
757 -- f = \x::(Int,Int). if ...strict in x... then
761 -- We want f to have the CPR property because x does, by the time f has been w/w'd
763 -- NOTE: see notes [CPR-AND-STRICTNESS]
765 -- Also note that we only want to do this for something that
766 -- definitely has product type, else we may get over-optimistic
767 -- CPR results (e.g. from \x -> x!).
769 extendSigsWithLam sigs id
770 = case idNewDemandInfo_maybe id of
771 Nothing -> extendVarEnv sigs id (cprSig, NotTopLevel)
772 Just (Eval (Prod ds)) -> extendVarEnv sigs id (cprSig, NotTopLevel)
776 dmdTransform :: SigEnv -- The strictness environment
777 -> Id -- The function
778 -> Demand -- The demand on the function
779 -> DmdType -- The demand type of the function in this context
780 -- Returned DmdEnv includes the demand on
781 -- this function plus demand on its free variables
783 dmdTransform sigs var dmd
785 ------ DATA CONSTRUCTOR
786 | isDataConWorkId var -- Data constructor
788 StrictSig dmd_ty = idNewStrictness var -- It must have a strictness sig
789 DmdType _ _ con_res = dmd_ty
792 if arity == call_depth then -- Saturated, so unleash the demand
794 -- Important! If we Keep the constructor application, then
795 -- we need the demands the constructor places (always lazy)
796 -- If not, we don't need to. For example:
797 -- f p@(x,y) = (p,y) -- S(AL)
799 -- It's vital that we don't calculate Absent for a!
800 dmd_ds = case res_dmd of
801 Box (Eval ds) -> mapDmds box ds
805 -- ds can be empty, when we are just seq'ing the thing
806 -- If so we must make up a suitable bunch of demands
807 arg_ds = case dmd_ds of
808 Poly d -> replicate arity d
809 Prod ds -> ASSERT( ds `lengthIs` arity ) ds
812 mkDmdType emptyDmdEnv arg_ds con_res
813 -- Must remember whether it's a product, hence con_res, not TopRes
817 ------ IMPORTED FUNCTION
818 | isGlobalId var, -- Imported function
819 let StrictSig dmd_ty = idNewStrictness var
820 = if dmdTypeDepth dmd_ty <= call_depth then -- Saturated, so unleash the demand
825 ------ LOCAL LET/REC BOUND THING
826 | Just (StrictSig dmd_ty, top_lvl) <- lookupVarEnv sigs var
828 fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty
829 | otherwise = deferType dmd_ty
830 -- NB: it's important to use deferType, and not just return topDmdType
831 -- Consider let { f x y = p + x } in f 1
832 -- The application isn't saturated, but we must nevertheless propagate
833 -- a lazy demand for p!
835 addVarDmd top_lvl fn_ty var dmd
837 ------ LOCAL NON-LET/REC BOUND THING
838 | otherwise -- Default case
842 (call_depth, res_dmd) = splitCallDmd dmd
846 %************************************************************************
850 %************************************************************************
853 splitCallDmd :: Demand -> (Int, Demand)
854 splitCallDmd (Call d) = case splitCallDmd d of
856 splitCallDmd d = (0, d)
858 vanillaCall :: Arity -> Demand
859 vanillaCall 0 = evalDmd
860 vanillaCall n = Call (vanillaCall (n-1))
862 deferType :: DmdType -> DmdType
863 deferType (DmdType fv _ _) = DmdType (deferEnv fv) [] TopRes
864 -- Notice that we throw away info about both arguments and results
865 -- For example, f = let ... in \x -> x
866 -- We don't want to get a stricness type V->T for f.
869 deferEnv :: DmdEnv -> DmdEnv
870 deferEnv fv = mapVarEnv defer fv
874 argDemand :: Demand -> Demand
875 -- The 'Defer' demands are just Lazy at function boundaries
876 -- Ugly! Ask John how to improve it.
877 argDemand Top = lazyDmd
878 argDemand (Defer d) = lazyDmd
879 argDemand (Eval ds) = Eval (mapDmds argDemand ds)
880 argDemand (Box Bot) = evalDmd
881 argDemand (Box d) = box (argDemand d)
882 argDemand Bot = Abs -- Don't pass args that are consumed (only) by bottom
887 -------------------------
888 -- Consider (if x then y else []) with demand V
889 -- Then the first branch gives {y->V} and the second
890 -- *implicitly* has {y->A}. So we must put {y->(V `lub` A)}
891 -- in the result env.
892 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
893 = DmdType lub_fv2 (lub_ds ds1 ds2) (r1 `lubRes` r2)
895 lub_fv = plusUFM_C lub fv1 fv2
896 lub_fv1 = modifyEnv (not (isBotRes r1)) absLub fv2 fv1 lub_fv
897 lub_fv2 = modifyEnv (not (isBotRes r2)) absLub fv1 fv2 lub_fv1
898 -- lub is the identity for Bot
900 -- Extend the shorter argument list to match the longer
901 lub_ds (d1:ds1) (d2:ds2) = lub d1 d2 : lub_ds ds1 ds2
903 lub_ds ds1 [] = map (`lub` resTypeArgDmd r2) ds1
904 lub_ds [] ds2 = map (resTypeArgDmd r1 `lub`) ds2
906 -----------------------------------
907 -- (t1 `bothType` t2) takes the argument/result info from t1,
908 -- using t2 just for its free-var info
909 -- NB: Don't forget about r2! It might be BotRes, which is
910 -- a bottom demand on all the in-scope variables.
911 -- Peter: can this be done more neatly?
912 bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
913 = DmdType both_fv2 ds1 (r1 `bothRes` r2)
915 both_fv = plusUFM_C both fv1 fv2
916 both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
917 both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
918 -- both is the identity for Abs
925 lubRes RetCPR RetCPR = RetCPR
926 lubRes r1 r2 = TopRes
928 -- If either diverges, the whole thing does
929 -- Otherwise take CPR info from the first
930 bothRes r1 BotRes = BotRes
935 modifyEnv :: Bool -- No-op if False
936 -> (Demand -> Demand) -- The zapper
937 -> DmdEnv -> DmdEnv -- Env1 and Env2
938 -> DmdEnv -> DmdEnv -- Transform this env
939 -- Zap anything in Env1 but not in Env2
940 -- Assume: dom(env) includes dom(Env1) and dom(Env2)
942 modifyEnv need_to_modify zapper env1 env2 env
943 | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2))
946 zap uniq env = addToUFM_Directly env uniq (zapper current_val)
948 current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
952 %************************************************************************
954 \subsection{LUB and BOTH}
956 %************************************************************************
959 lub :: Demand -> Demand -> Demand
962 lub Abs d2 = absLub d2
964 lub (Defer ds1) d2 = defer (Eval ds1 `lub` d2)
966 lub (Call d1) (Call d2) = Call (d1 `lub` d2)
967 lub d1@(Call _) (Box d2) = d1 `lub` d2 -- Just strip the box
968 lub d1@(Call _) d2@(Eval _) = d2 -- Presumably seq or vanilla eval
969 lub d1@(Call _) d2 = d2 `lub` d1 -- Bot, Abs, Top
971 -- For the Eval case, we use these approximation rules
972 -- Box Bot <= Eval (Box Bot ...)
973 -- Box Top <= Defer (Box Bot ...)
974 -- Box (Eval ds) <= Eval (map Box ds)
975 lub (Eval ds1) (Eval ds2) = Eval (ds1 `lubs` ds2)
976 lub (Eval ds1) (Box Bot) = Eval (mapDmds (`lub` Box Bot) ds1)
977 lub (Eval ds1) (Box (Eval ds2)) = Eval (ds1 `lubs` mapDmds box ds2)
978 lub (Eval ds1) (Box Abs) = deferEval (mapDmds (`lub` Box Bot) ds1)
979 lub d1@(Eval _) d2 = d2 `lub` d1 -- Bot,Abs,Top,Call,Defer
981 lub (Box d1) (Box d2) = box (d1 `lub` d2)
982 lub d1@(Box _) d2 = d2 `lub` d1
984 lubs = zipWithDmds lub
986 ---------------------
987 -- box is the smart constructor for Box
988 -- It computes <B,bot> & d
989 -- INVARIANT: (Box d) => d = Bot, Abs, Eval
990 -- Seems to be no point in allowing (Box (Call d))
991 box (Call d) = Call d -- The odd man out. Why?
993 box (Defer _) = lazyDmd
994 box Top = lazyDmd -- Box Abs and Box Top
995 box Abs = lazyDmd -- are the same <B,L>
996 box d = Box d -- Bot, Eval
999 defer :: Demand -> Demand
1001 -- defer is the smart constructor for Defer
1002 -- The idea is that (Defer ds) = <U(ds), L>
1004 -- It specifies what happens at a lazy function argument
1005 -- or a lambda; the L* operator
1006 -- Set the strictness part to L, but leave
1007 -- the boxity side unaffected
1008 -- It also ensures that Defer (Eval [LLLL]) = L
1013 defer (Call _) = lazyDmd -- Approximation here?
1014 defer (Box _) = lazyDmd
1015 defer (Defer ds) = Defer ds
1016 defer (Eval ds) = deferEval ds
1018 -- deferEval ds = defer (Eval ds)
1019 deferEval ds | allTop ds = Top
1020 | otherwise = Defer ds
1022 ---------------------
1023 absLub :: Demand -> Demand
1024 -- Computes (Abs `lub` d)
1025 -- For the Bot case consider
1026 -- f x y = if ... then x else error x
1027 -- Then for y we get Abs `lub` Bot, and we really
1032 absLub (Call _) = Top
1033 absLub (Box _) = Top
1034 absLub (Eval ds) = Defer (absLubs ds) -- Or (Defer ds)?
1035 absLub (Defer ds) = Defer (absLubs ds) -- Or (Defer ds)?
1037 absLubs = mapDmds absLub
1040 both :: Demand -> Demand -> Demand
1046 both Bot (Eval ds) = Eval (mapDmds (`both` Bot) ds)
1049 -- From 'error' itself we get demand Bot on x
1050 -- From the arg demand on x we get
1051 -- x :-> evalDmd = Box (Eval (Poly Abs))
1052 -- So we get Bot `both` Box (Eval (Poly Abs))
1053 -- = Seq Keep (Poly Bot)
1056 -- f x = if ... then error (fst x) else fst x
1057 -- Then we get (Eval (Box Bot, Bot) `lub` Eval (SA))
1059 -- which is what we want.
1062 both Top Bot = errDmd
1065 both Top (Box d) = Box d
1066 both Top (Call d) = Call d
1067 both Top (Eval ds) = Eval (mapDmds (`both` Top) ds)
1068 both Top (Defer ds) -- = defer (Top `both` Eval ds)
1069 -- = defer (Eval (mapDmds (`both` Top) ds))
1070 = deferEval (mapDmds (`both` Top) ds)
1073 both (Box d1) (Box d2) = box (d1 `both` d2)
1074 both (Box d1) d2@(Call _) = box (d1 `both` d2)
1075 both (Box d1) d2@(Eval _) = box (d1 `both` d2)
1076 both (Box d1) (Defer d2) = Box d1
1077 both d1@(Box _) d2 = d2 `both` d1
1079 both (Call d1) (Call d2) = Call (d1 `both` d2)
1080 both (Call d1) (Eval ds2) = Call d1 -- Could do better for (Poly Bot)?
1081 both (Call d1) (Defer ds2) = Call d1 -- Ditto
1082 both d1@(Call _) d2 = d1 `both` d1
1084 both (Eval ds1) (Eval ds2) = Eval (ds1 `boths` ds2)
1085 both (Eval ds1) (Defer ds2) = Eval (ds1 `boths` mapDmds defer ds2)
1086 both d1@(Eval ds1) d2 = d2 `both` d1
1088 both (Defer ds1) (Defer ds2) = deferEval (ds1 `boths` ds2)
1089 both d1@(Defer ds1) d2 = d2 `both` d1
1091 boths = zipWithDmds both
1096 %************************************************************************
1098 \subsection{Miscellaneous
1100 %************************************************************************
1104 #ifdef OLD_STRICTNESS
1105 get_changes binds = vcat (map get_changes_bind binds)
1107 get_changes_bind (Rec pairs) = vcat (map get_changes_pr pairs)
1108 get_changes_bind (NonRec id rhs) = get_changes_pr (id,rhs)
1110 get_changes_pr (id,rhs)
1111 = get_changes_var id $$ get_changes_expr rhs
1114 | isId var = get_changes_str var $$ get_changes_dmd var
1117 get_changes_expr (Type t) = empty
1118 get_changes_expr (Var v) = empty
1119 get_changes_expr (Lit l) = empty
1120 get_changes_expr (Note n e) = get_changes_expr e
1121 get_changes_expr (App e1 e2) = get_changes_expr e1 $$ get_changes_expr e2
1122 get_changes_expr (Lam b e) = {- get_changes_var b $$ -} get_changes_expr e
1123 get_changes_expr (Let b e) = get_changes_bind b $$ get_changes_expr e
1124 get_changes_expr (Case e b a) = get_changes_expr e $$ {- get_changes_var b $$ -} vcat (map get_changes_alt a)
1126 get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs
1129 | new_better && old_better = empty
1130 | new_better = message "BETTER"
1131 | old_better = message "WORSE"
1132 | otherwise = message "INCOMPARABLE"
1134 message word = text word <+> text "strictness for" <+> ppr id <+> info
1135 info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
1136 new = squashSig (idNewStrictness id) -- Don't report spurious diffs that the old
1137 -- strictness analyser can't track
1138 old = newStrictnessFromOld (idName id) (idArity id) (idStrictness id) (idCprInfo id)
1139 old_better = old `betterStrictness` new
1140 new_better = new `betterStrictness` old
1143 | isUnLiftedType (idType id) = empty -- Not useful
1144 | new_better && old_better = empty
1145 | new_better = message "BETTER"
1146 | old_better = message "WORSE"
1147 | otherwise = message "INCOMPARABLE"
1149 message word = text word <+> text "demand for" <+> ppr id <+> info
1150 info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
1151 new = squashDmd (argDemand (idNewDemandInfo id)) -- To avoid spurious improvements
1153 old = newDemand (idDemandInfo id)
1154 new_better = new `betterDemand` old
1155 old_better = old `betterDemand` new
1157 betterStrictness :: StrictSig -> StrictSig -> Bool
1158 betterStrictness (StrictSig t1) (StrictSig t2) = betterDmdType t1 t2
1160 betterDmdType t1 t2 = (t1 `lubType` t2) == t2
1162 betterDemand :: Demand -> Demand -> Bool
1163 -- If d1 `better` d2, and d2 `better` d2, then d1==d2
1164 betterDemand d1 d2 = (d1 `lub` d2) == d2
1166 squashSig (StrictSig (DmdType fv ds res))
1167 = StrictSig (DmdType emptyDmdEnv (map squashDmd ds) res)
1169 -- squash just gets rid of call demands
1170 -- which the old analyser doesn't track
1171 squashDmd (Call d) = evalDmd
1172 squashDmd (Box d) = Box (squashDmd d)
1173 squashDmd (Eval ds) = Eval (mapDmds squashDmd ds)
1174 squashDmd (Defer ds) = Defer (mapDmds squashDmd ds)