b6bd92fe4a51657bd4a5aa33aad699145bb6a04c
[ghc-hetmet.git] / ghc / compiler / stranal / DmdAnal.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4
5                         -----------------
6                         A demand analysis
7                         -----------------
8
9 \begin{code}
10 module DmdAnal ( dmdAnalPgm, dmdAnalTopRhs, 
11                  both {- needed by WwLib -}
12    ) where
13
14 #include "HsVersions.h"
15
16 import CmdLineOpts      ( DynFlags, DynFlag(..), opt_MaxWorkerArgs )
17 import NewDemand        -- All of it
18 import CoreSyn
19 import PprCore  
20 import CoreUtils        ( exprIsValue, exprArity )
21 import DataCon          ( dataConTyCon )
22 import TyCon            ( isProductTyCon, isRecursiveTyCon )
23 import Id               ( Id, idType, idInlinePragma,
24                           isDataConWorkId, isGlobalId, idArity,
25 #ifdef OLD_STRICTNESS
26                           idDemandInfo,  idStrictness, idCprInfo, idName,
27 #endif
28                           idNewStrictness, idNewStrictness_maybe,
29                           setIdNewStrictness, idNewDemandInfo,
30                           idNewDemandInfo_maybe,
31                           setIdNewDemandInfo
32                         )
33 #ifdef OLD_STRICTNESS
34 import IdInfo           ( newStrictnessFromOld, newDemand )
35 #endif
36 import Var              ( Var )
37 import VarEnv
38 import UniqFM           ( plusUFM_C, addToUFM_Directly, lookupUFM_Directly,
39                           keysUFM, minusUFM, ufmToList, filterUFM )
40 import Type             ( isUnLiftedType )
41 import CoreLint         ( showPass, endPass )
42 import Util             ( mapAndUnzip, mapAccumL, mapAccumR, lengthIs )
43 import BasicTypes       ( Arity, TopLevelFlag(..), isTopLevel, isNeverActive,
44                           RecFlag(..), isRec )
45 import Maybes           ( orElse, expectJust )
46 import Outputable
47 \end{code}
48
49 To think about
50
51 * set a noinline pragma on bottoming Ids
52
53 * Consider f x = x+1 `fatbar` error (show x)
54   We'd like to unbox x, even if that means reboxing it in the error case.
55
56 \begin{code}
57 instance Outputable TopLevelFlag where
58   ppr flag = empty
59 \end{code}
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection{Top level stuff}
64 %*                                                                      *
65 %************************************************************************
66
67 \begin{code}
68 dmdAnalPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
69 dmdAnalPgm dflags binds
70   = do {
71         showPass dflags "Demand analysis" ;
72         let { binds_plus_dmds = do_prog binds } ;
73
74         endPass dflags "Demand analysis" 
75                 Opt_D_dump_stranal binds_plus_dmds ;
76 #ifdef OLD_STRICTNESS
77         -- Only if OLD_STRICTNESS is on, because only then is the old
78         -- strictness analyser run
79         let { dmd_changes = get_changes binds_plus_dmds } ;
80         printDump (text "Changes in demands" $$ dmd_changes) ;
81 #endif
82         return binds_plus_dmds
83     }
84   where
85     do_prog :: [CoreBind] -> [CoreBind]
86     do_prog binds = snd $ mapAccumL dmdAnalTopBind emptySigEnv binds
87
88 dmdAnalTopBind :: SigEnv
89                -> CoreBind 
90                -> (SigEnv, CoreBind)
91 dmdAnalTopBind sigs (NonRec id rhs)
92   = let
93         (    _, _, (_,   rhs1)) = dmdAnalRhs TopLevel NonRecursive sigs (id, rhs)
94         (sigs2, _, (id2, rhs2)) = dmdAnalRhs TopLevel NonRecursive sigs (id, rhs1)
95                 -- Do two passes to improve CPR information
96                 -- See comments with ignore_cpr_info in mk_sig_ty
97                 -- and with extendSigsWithLam
98     in
99     (sigs2, NonRec id2 rhs2)    
100
101 dmdAnalTopBind sigs (Rec pairs)
102   = let
103         (sigs', _, pairs')  = dmdFix TopLevel sigs pairs
104                 -- We get two iterations automatically
105                 -- c.f. the NonRec case above
106     in
107     (sigs', Rec pairs')
108 \end{code}
109
110 \begin{code}
111 dmdAnalTopRhs :: CoreExpr -> (StrictSig, CoreExpr)
112 -- Analyse the RHS and return
113 --      a) appropriate strictness info
114 --      b) the unfolding (decorated with stricntess info)
115 dmdAnalTopRhs rhs
116   = (sig, rhs')
117   where
118     arity          = exprArity rhs
119     (rhs_ty, rhs') = dmdAnal emptySigEnv (vanillaCall arity) rhs
120     sig            = mkTopSigTy rhs rhs_ty
121 \end{code}
122
123 %************************************************************************
124 %*                                                                      *
125 \subsection{The analyser itself}        
126 %*                                                                      *
127 %************************************************************************
128
129 \begin{code}
130 dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
131
132 dmdAnal sigs Abs  e = (topDmdType, e)
133
134 dmdAnal sigs dmd e 
135   | not (isStrictDmd dmd)
136   = let 
137         (res_ty, e') = dmdAnal sigs evalDmd e
138     in
139     (deferType res_ty, e')
140         -- It's important not to analyse e with a lazy demand because
141         -- a) When we encounter   case s of (a,b) -> 
142         --      we demand s with U(d1d2)... but if the overall demand is lazy
143         --      that is wrong, and we'd need to reduce the demand on s,
144         --      which is inconvenient
145         -- b) More important, consider
146         --      f (let x = R in x+x), where f is lazy
147         --    We still want to mark x as demanded, because it will be when we
148         --    enter the let.  If we analyse f's arg with a Lazy demand, we'll
149         --    just mark x as Lazy
150         -- c) The application rule wouldn't be right either
151         --    Evaluating (f x) in a L demand does *not* cause
152         --    evaluation of f in a C(L) demand!
153
154
155 dmdAnal sigs dmd (Lit lit)
156   = (topDmdType, Lit lit)
157
158 dmdAnal sigs dmd (Var var)
159   = (dmdTransform sigs var dmd, Var var)
160
161 dmdAnal sigs dmd (Note n e)
162   = (dmd_ty, Note n e')
163   where
164     (dmd_ty, e') = dmdAnal sigs dmd' e  
165     dmd' = case n of
166              Coerce _ _ -> evalDmd  -- This coerce usually arises from a recursive
167              other      -> dmd      -- newtype, and we don't want to look inside them
168                                     -- for exactly the same reason that we don't look
169                                     -- inside recursive products -- we might not reach
170                                     -- a fixpoint.  So revert to a vanilla Eval demand
171
172 dmdAnal sigs dmd (App fun (Type ty))
173   = (fun_ty, App fun' (Type ty))
174   where
175     (fun_ty, fun') = dmdAnal sigs dmd fun
176
177 -- Lots of the other code is there to make this
178 -- beautiful, compositional, application rule :-)
179 dmdAnal sigs dmd e@(App fun arg)        -- Non-type arguments
180   = let                         -- [Type arg handled above]
181         (fun_ty, fun')    = dmdAnal sigs (Call dmd) fun
182         (arg_ty, arg')    = dmdAnal sigs arg_dmd arg
183         (arg_dmd, res_ty) = splitDmdTy fun_ty
184     in
185     (res_ty `bothType` arg_ty, App fun' arg')
186
187 dmdAnal sigs dmd (Lam var body)
188   | isTyVar var
189   = let   
190         (body_ty, body') = dmdAnal sigs dmd body
191     in
192     (body_ty, Lam var body')
193
194   | Call body_dmd <- dmd        -- A call demand: good!
195   = let 
196         sigs'            = extendSigsWithLam sigs var
197         (body_ty, body') = dmdAnal sigs' body_dmd body
198         (lam_ty, var')   = annotateLamIdBndr body_ty var
199     in
200     (lam_ty, Lam var' body')
201
202   | otherwise   -- Not enough demand on the lambda; but do the body
203   = let         -- anyway to annotate it and gather free var info
204         (body_ty, body') = dmdAnal sigs evalDmd body
205         (lam_ty, var')   = annotateLamIdBndr body_ty var
206     in
207     (deferType lam_ty, Lam var' body')
208
209 dmdAnal sigs dmd (Case scrut case_bndr [alt@(DataAlt dc,bndrs,rhs)])
210   | let tycon = dataConTyCon dc,
211     isProductTyCon tycon,
212     not (isRecursiveTyCon tycon)
213   = let
214         sigs_alt              = extendSigEnv NotTopLevel sigs case_bndr case_bndr_sig
215         (alt_ty, alt')        = dmdAnalAlt sigs_alt dmd alt
216         (alt_ty1, case_bndr') = annotateBndr alt_ty case_bndr
217         (_, bndrs', _)        = alt'
218         case_bndr_sig         = cprSig
219                 -- Inside the alternative, the case binder has the CPR property.
220                 -- Meaning that a case on it will successfully cancel.
221                 -- Example:
222                 --      f True  x = case x of y { I# x' -> if x' ==# 3 then y else I# 8 }
223                 --      f False x = I# 3
224                 --      
225                 -- We want f to have the CPR property:
226                 --      f b x = case fw b x of { r -> I# r }
227                 --      fw True  x = case x of y { I# x' -> if x' ==# 3 then x' else 8 }
228                 --      fw False x = 3
229
230         -- Figure out whether the demand on the case binder is used, and use
231         -- that to set the scrut_dmd.  This is utterly essential.
232         -- Consider     f x = case x of y { (a,b) -> k y a }
233         -- If we just take scrut_demand = U(L,A), then we won't pass x to the
234         -- worker, so the worker will rebuild 
235         --      x = (a, absent-error)
236         -- and that'll crash.
237         -- So at one stage I had:
238         --      dead_case_bndr           = isAbsentDmd (idNewDemandInfo case_bndr')
239         --      keepity | dead_case_bndr = Drop
240         --              | otherwise      = Keep         
241         --
242         -- But then consider
243         --      case x of y { (a,b) -> h y + a }
244         -- where h : U(LL) -> T
245         -- The above code would compute a Keep for x, since y is not Abs, which is silly
246         -- The insight is, of course, that a demand on y is a demand on the
247         -- scrutinee, so we need to `both` it with the scrut demand
248
249         scrut_dmd          = Eval (Prod [idNewDemandInfo b | b <- bndrs', isId b])
250                                    `both`
251                              idNewDemandInfo case_bndr'
252
253         (scrut_ty, scrut') = dmdAnal sigs scrut_dmd scrut
254     in
255     (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' [alt'])
256
257 dmdAnal sigs dmd (Case scrut case_bndr alts)
258   = let
259         (alt_tys, alts')        = mapAndUnzip (dmdAnalAlt sigs dmd) alts
260         (scrut_ty, scrut')      = dmdAnal sigs evalDmd scrut
261         (alt_ty, case_bndr')    = annotateBndr (foldr1 lubType alt_tys) case_bndr
262     in
263 --    pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
264     (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' alts')
265
266 dmdAnal sigs dmd (Let (NonRec id rhs) body) 
267   = let
268         (sigs', lazy_fv, (id1, rhs')) = dmdAnalRhs NotTopLevel NonRecursive sigs (id, rhs)
269         (body_ty, body')              = dmdAnal sigs' dmd body
270         (body_ty1, id2)               = annotateBndr body_ty id1
271         body_ty2                      = addLazyFVs body_ty1 lazy_fv
272     in
273         -- If the actual demand is better than the vanilla call
274         -- demand, you might think that we might do better to re-analyse 
275         -- the RHS with the stronger demand.
276         -- But (a) That seldom happens, because it means that *every* path in 
277         --         the body of the let has to use that stronger demand
278         -- (b) It often happens temporarily in when fixpointing, because
279         --     the recursive function at first seems to place a massive demand.
280         --     But we don't want to go to extra work when the function will
281         --     probably iterate to something less demanding.  
282         -- In practice, all the times the actual demand on id2 is more than
283         -- the vanilla call demand seem to be due to (b).  So we don't
284         -- bother to re-analyse the RHS.
285     (body_ty2, Let (NonRec id2 rhs') body')    
286
287 dmdAnal sigs dmd (Let (Rec pairs) body) 
288   = let
289         bndrs                    = map fst pairs
290         (sigs', lazy_fv, pairs') = dmdFix NotTopLevel sigs pairs
291         (body_ty, body')         = dmdAnal sigs' dmd body
292         body_ty1                 = addLazyFVs body_ty lazy_fv
293     in
294     sigs' `seq` body_ty `seq`
295     let
296         (body_ty2, _) = annotateBndrs body_ty1 bndrs
297                 -- Don't bother to add demand info to recursive
298                 -- binders as annotateBndr does; 
299                 -- being recursive, we can't treat them strictly.
300                 -- But we do need to remove the binders from the result demand env
301     in
302     (body_ty2,  Let (Rec pairs') body')
303
304
305 dmdAnalAlt sigs dmd (con,bndrs,rhs) 
306   = let 
307         (rhs_ty, rhs')   = dmdAnal sigs dmd rhs
308         (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs
309     in
310     (alt_ty, (con, bndrs', rhs'))
311 \end{code}
312
313 %************************************************************************
314 %*                                                                      *
315 \subsection{Bindings}
316 %*                                                                      *
317 %************************************************************************
318
319 \begin{code}
320 dmdFix :: TopLevelFlag
321        -> SigEnv                -- Does not include bindings for this binding
322        -> [(Id,CoreExpr)]
323        -> (SigEnv, DmdEnv,
324            [(Id,CoreExpr)])     -- Binders annotated with stricness info
325
326 dmdFix top_lvl sigs orig_pairs
327   = loop 1 initial_sigs orig_pairs
328   where
329     bndrs        = map fst orig_pairs
330     initial_sigs = extendSigEnvList sigs [(id, (initialSig id, top_lvl)) | id <- bndrs]
331     
332     loop :: Int
333          -> SigEnv                      -- Already contains the current sigs
334          -> [(Id,CoreExpr)]             
335          -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
336     loop n sigs pairs
337       | found_fixpoint
338       = (sigs', lazy_fv, pairs')
339                 -- Note: use pairs', not pairs.   pairs' is the result of 
340                 -- processing the RHSs with sigs (= sigs'), whereas pairs 
341                 -- is the result of processing the RHSs with the *previous* 
342                 -- iteration of sigs.
343
344       | n >= 10  = pprTrace "dmdFix loop" (ppr n <+> (vcat 
345                                 [ text "Sigs:" <+> ppr [(id,lookup sigs id, lookup sigs' id) | (id,_) <- pairs],
346                                   text "env:" <+> ppr (ufmToList sigs),
347                                   text "binds:" <+> pprCoreBinding (Rec pairs)]))
348                               (emptySigEnv, lazy_fv, orig_pairs)        -- Safe output
349                         -- The lazy_fv part is really important!  orig_pairs has no strictness
350                         -- info, including nothing about free vars.  But if we have
351                         --      letrec f = ....y..... in ...f...
352                         -- where 'y' is free in f, we must record that y is mentioned, 
353                         -- otherwise y will get recorded as absent altogether
354
355       | otherwise    = loop (n+1) sigs' pairs'
356       where
357         found_fixpoint = all (same_sig sigs sigs') bndrs 
358                 -- Use the new signature to do the next pair
359                 -- The occurrence analyser has arranged them in a good order
360                 -- so this can significantly reduce the number of iterations needed
361         ((sigs',lazy_fv), pairs') = mapAccumL (my_downRhs top_lvl) (sigs, emptyDmdEnv) pairs
362         
363     my_downRhs top_lvl (sigs,lazy_fv) (id,rhs)
364         = -- pprTrace "downRhs {" (ppr id <+> (ppr old_sig))
365           -- (new_sig `seq` 
366           --    pprTrace "downRhsEnd" (ppr id <+> ppr new_sig <+> char '}' ) 
367           ((sigs', lazy_fv'), pair')
368           --     )
369         where
370           (sigs', lazy_fv1, pair') = dmdAnalRhs top_lvl Recursive sigs (id,rhs)
371           lazy_fv'                 = plusUFM_C both lazy_fv lazy_fv1   
372           -- old_sig               = lookup sigs id
373           -- new_sig               = lookup sigs' id
374            
375     same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
376     lookup sigs var = case lookupVarEnv sigs var of
377                         Just (sig,_) -> sig
378
379         -- Get an initial strictness signature from the Id
380         -- itself.  That way we make use of earlier iterations
381         -- of the fixpoint algorithm.  (Cunning plan.)
382         -- Note that the cunning plan extends to the DmdEnv too,
383         -- since it is part of the strictness signature
384 initialSig id = idNewStrictness_maybe id `orElse` botSig
385
386 dmdAnalRhs :: TopLevelFlag -> RecFlag
387         -> SigEnv -> (Id, CoreExpr)
388         -> (SigEnv,  DmdEnv, (Id, CoreExpr))
389 -- Process the RHS of the binding, add the strictness signature
390 -- to the Id, and augment the environment with the signature as well.
391
392 dmdAnalRhs top_lvl rec_flag sigs (id, rhs)
393  = (sigs', lazy_fv, (id', rhs'))
394  where
395   arity              = idArity id   -- The idArity should be up to date
396                                     -- The simplifier was run just beforehand
397   (rhs_dmd_ty, rhs') = dmdAnal sigs (vanillaCall arity) rhs
398   (lazy_fv, sig_ty)  = WARN( arity /= dmdTypeDepth rhs_dmd_ty, ppr id )
399                        mkSigTy top_lvl rec_flag id rhs rhs_dmd_ty
400   id'                = id `setIdNewStrictness` sig_ty
401   sigs'              = extendSigEnv top_lvl sigs id sig_ty
402 \end{code}
403
404 %************************************************************************
405 %*                                                                      *
406 \subsection{Strictness signatures and types}
407 %*                                                                      *
408 %************************************************************************
409
410 \begin{code}
411 mkTopSigTy :: CoreExpr -> DmdType -> StrictSig
412         -- Take a DmdType and turn it into a StrictSig
413         -- NB: not used for never-inline things; hence False
414 mkTopSigTy rhs dmd_ty = snd (mk_sig_ty False False rhs dmd_ty)
415
416 mkSigTy :: TopLevelFlag -> RecFlag -> Id -> CoreExpr -> DmdType -> (DmdEnv, StrictSig)
417 mkSigTy top_lvl rec_flag id rhs dmd_ty 
418   = mk_sig_ty never_inline thunk_cpr_ok rhs dmd_ty
419   where
420     never_inline = isNeverActive (idInlinePragma id)
421     maybe_id_dmd = idNewDemandInfo_maybe id
422         -- Is Nothing the first time round
423
424     thunk_cpr_ok
425         | isTopLevel top_lvl       = False      -- Top level things don't get
426                                                 -- their demandInfo set at all
427         | isRec rec_flag           = False      -- Ditto recursive things
428         | Just dmd <- maybe_id_dmd = isStrictDmd dmd
429         | otherwise                = True       -- Optimistic, first time round
430                                                 -- See notes below
431 \end{code}
432
433 The thunk_cpr_ok stuff [CPR-AND-STRICTNESS]
434 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
435 If the rhs is a thunk, we usually forget the CPR info, because
436 it is presumably shared (else it would have been inlined, and 
437 so we'd lose sharing if w/w'd it into a function.
438
439 However, if the strictness analyser has figured out (in a previous 
440 iteration) that it's strict, then we DON'T need to forget the CPR info.
441 Instead we can retain the CPR info and do the thunk-splitting transform 
442 (see WorkWrap.splitThunk).
443
444 This made a big difference to PrelBase.modInt, which had something like
445         modInt = \ x -> let r = ... -> I# v in
446                         ...body strict in r...
447 r's RHS isn't a value yet; but modInt returns r in various branches, so
448 if r doesn't have the CPR property then neither does modInt
449 Another case I found in practice (in Complex.magnitude), looks like this:
450                 let k = if ... then I# a else I# b
451                 in ... body strict in k ....
452 (For this example, it doesn't matter whether k is returned as part of
453 the overall result; but it does matter that k's RHS has the CPR property.)  
454 Left to itself, the simplifier will make a join point thus:
455                 let $j k = ...body strict in k...
456                 if ... then $j (I# a) else $j (I# b)
457 With thunk-splitting, we get instead
458                 let $j x = let k = I#x in ...body strict in k...
459                 in if ... then $j a else $j b
460 This is much better; there's a good chance the I# won't get allocated.
461
462 The difficulty with this is that we need the strictness type to
463 look at the body... but we now need the body to calculate the demand
464 on the variable, so we can decide whether its strictness type should
465 have a CPR in it or not.  Simple solution: 
466         a) use strictness info from the previous iteration
467         b) make sure we do at least 2 iterations, by doing a second
468            round for top-level non-recs.  Top level recs will get at
469            least 2 iterations except for totally-bottom functions
470            which aren't very interesting anyway.
471
472 NB: strictly_demanded is never true of a top-level Id, or of a recursive Id.
473
474 The Nothing case in thunk_cpr_ok [CPR-AND-STRICTNESS]
475 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
476 Demand info now has a 'Nothing' state, just like strictness info.
477 The analysis works from 'dangerous' towards a 'safe' state; so we 
478 start with botSig for 'Nothing' strictness infos, and we start with
479 "yes, it's demanded" for 'Nothing' in the demand info.  The
480 fixpoint iteration will sort it all out.
481
482 We can't start with 'not-demanded' because then consider
483         f x = let 
484                   t = ... I# x
485               in
486               if ... then t else I# y else f x'
487
488 In the first iteration we'd have no demand info for x, so assume
489 not-demanded; then we'd get TopRes for f's CPR info.  Next iteration
490 we'd see that t was demanded, and so give it the CPR property, but by
491 now f has TopRes, so it will stay TopRes.  Instead, with the Nothing
492 setting the first time round, we say 'yes t is demanded' the first
493 time.
494
495 However, this does mean that for non-recursive bindings we must
496 iterate twice to be sure of not getting over-optimistic CPR info,
497 in the case where t turns out to be not-demanded.  This is handled
498 by dmdAnalTopBind.
499
500
501 \begin{code}
502 mk_sig_ty never_inline thunk_cpr_ok rhs (DmdType fv dmds res) 
503   | never_inline && not (isBotRes res)
504         --                      HACK ALERT
505         -- Don't strictness-analyse NOINLINE things.  Why not?  Because
506         -- the NOINLINE says "don't expose any of the inner workings at the call 
507         -- site" and the strictness is certainly an inner working.
508         --
509         -- More concretely, the demand analyser discovers the following strictness
510         -- for unsafePerformIO:  C(U(AV))
511         -- But then consider
512         --      unsafePerformIO (\s -> let r = f x in 
513         --                             case writeIORef v r s of (# s1, _ #) ->
514         --                             (# s1, r #)
515         -- The strictness analyser will find that the binding for r is strict,
516         -- (becuase of uPIO's strictness sig), and so it'll evaluate it before 
517         -- doing the writeIORef.  This actually makes tests/lib/should_run/memo002
518         -- get a deadlock!  
519         --
520         -- Solution: don't expose the strictness of unsafePerformIO.
521         --
522         -- But we do want to expose the strictness of error functions, 
523         -- which are also often marked NOINLINE
524         --      {-# NOINLINE foo #-}
525         --      foo x = error ("wubble buggle" ++ x)
526         -- So (hack, hack) we only drop the strictness for non-bottom things
527         -- This is all very unsatisfactory.
528   = (deferEnv fv, topSig)
529
530   | otherwise
531   = (lazy_fv, mkStrictSig dmd_ty)
532   where
533     dmd_ty = DmdType strict_fv final_dmds res'
534
535     lazy_fv   = filterUFM (not . isStrictDmd) fv
536     strict_fv = filterUFM isStrictDmd         fv
537         -- We put the strict FVs in the DmdType of the Id, so 
538         -- that at its call sites we unleash demands on its strict fvs.
539         -- An example is 'roll' in imaginary/wheel-sieve2
540         -- Something like this:
541         --      roll x = letrec 
542         --                   go y = if ... then roll (x-1) else x+1
543         --               in 
544         --               go ms
545         -- We want to see that roll is strict in x, which is because
546         -- go is called.   So we put the DmdEnv for x in go's DmdType.
547         --
548         -- Another example:
549         --      f :: Int -> Int -> Int
550         --      f x y = let t = x+1
551         --          h z = if z==0 then t else 
552         --                if z==1 then x+1 else
553         --                x + h (z-1)
554         --      in
555         --      h y
556         -- Calling h does indeed evaluate x, but we can only see
557         -- that if we unleash a demand on x at the call site for t.
558         --
559         -- Incidentally, here's a place where lambda-lifting h would
560         -- lose the cigar --- we couldn't see the joint strictness in t/x
561         --
562         --      ON THE OTHER HAND
563         -- We don't want to put *all* the fv's from the RHS into the
564         -- DmdType, because that makes fixpointing very slow --- the 
565         -- DmdType gets full of lazy demands that are slow to converge.
566
567     final_dmds = setUnpackStrategy dmds
568         -- Set the unpacking strategy
569         
570     res' = case res of
571                 RetCPR | ignore_cpr_info -> TopRes
572                 other                    -> res
573     ignore_cpr_info = not (exprIsValue rhs || thunk_cpr_ok)
574 \end{code}
575
576 The unpack strategy determines whether we'll *really* unpack the argument,
577 or whether we'll just remember its strictness.  If unpacking would give
578 rise to a *lot* of worker args, we may decide not to unpack after all.
579
580 \begin{code}
581 setUnpackStrategy :: [Demand] -> [Demand]
582 setUnpackStrategy ds
583   = snd (go (opt_MaxWorkerArgs - nonAbsentArgs ds) ds)
584   where
585     go :: Int                   -- Max number of args available for sub-components of [Demand]
586        -> [Demand]
587        -> (Int, [Demand])       -- Args remaining after subcomponents of [Demand] are unpacked
588
589     go n (Eval (Prod cs) : ds) 
590         | n' >= 0   = Eval (Prod cs') `cons` go n'' ds
591         | otherwise = Box (Eval (Prod cs)) `cons` go n ds
592         where
593           (n'',cs') = go n' cs
594           n' = n + 1 - non_abs_args
595                 -- Add one to the budget 'cos we drop the top-level arg
596           non_abs_args = nonAbsentArgs cs
597                 -- Delete # of non-absent args to which we'll now be committed
598                                 
599     go n (d:ds) = d `cons` go n ds
600     go n []     = (n,[])
601
602     cons d (n,ds) = (n, d:ds)
603
604 nonAbsentArgs :: [Demand] -> Int
605 nonAbsentArgs []         = 0
606 nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
607 nonAbsentArgs (d   : ds) = 1 + nonAbsentArgs ds
608 \end{code}
609
610
611 %************************************************************************
612 %*                                                                      *
613 \subsection{Strictness signatures and types}
614 %*                                                                      *
615 %************************************************************************
616
617 \begin{code}
618 splitDmdTy :: DmdType -> (Demand, DmdType)
619 -- Split off one function argument
620 -- We already have a suitable demand on all
621 -- free vars, so no need to add more!
622 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
623 splitDmdTy ty@(DmdType fv [] res_ty)      = (resTypeArgDmd res_ty, ty)
624 \end{code}
625
626 \begin{code}
627 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
628
629 addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd
630   | isTopLevel top_lvl = dmd_ty         -- Don't record top level things
631   | otherwise          = DmdType (extendVarEnv fv var dmd) ds res
632
633 addLazyFVs (DmdType fv ds res) lazy_fvs
634   = DmdType both_fv1 ds res
635   where
636     both_fv = (plusUFM_C both fv lazy_fvs)
637     both_fv1 = modifyEnv (isBotRes res) (`both` Bot) lazy_fvs fv both_fv
638         -- This modifyEnv is vital.  Consider
639         --      let f = \x -> (x,y)
640         --      in  error (f 3)
641         -- Here, y is treated as a lazy-fv of f, but we must `both` that L
642         -- demand with the bottom coming up from 'error'
643         -- 
644         -- I got a loop in the fixpointer without this, due to an interaction
645         -- with the lazy_fv filtering in mkSigTy.  Roughly, it was
646         --      letrec f n x 
647         --          = letrec g y = x `fatbar` 
648         --                         letrec h z = z + ...g...
649         --                         in h (f (n-1) x)
650         --      in ...
651         -- In the initial iteration for f, f=Bot
652         -- Suppose h is found to be strict in z, but the occurrence of g in its RHS
653         -- is lazy.  Now consider the fixpoint iteration for g, esp the demands it
654         -- places on its free variables.  Suppose it places none.  Then the
655         --      x `fatbar` ...call to h...
656         -- will give a x->V demand for x.  That turns into a L demand for x,
657         -- which floats out of the defn for h.  Without the modifyEnv, that
658         -- L demand doesn't get both'd with the Bot coming up from the inner
659         -- call to f.  So we just get an L demand for x for g.
660         --
661         -- A better way to say this is that the lazy-fv filtering should give the
662         -- same answer as putting the lazy fv demands in the function's type.
663
664 annotateBndr :: DmdType -> Var -> (DmdType, Var)
665 -- The returned env has the var deleted
666 -- The returned var is annotated with demand info
667 -- No effect on the argument demands
668 annotateBndr dmd_ty@(DmdType fv ds res) var
669   | isTyVar var = (dmd_ty, var)
670   | otherwise   = (DmdType fv' ds res, setIdNewDemandInfo var dmd)
671   where
672     (fv', dmd) = removeFV fv var res
673
674 annotateBndrs = mapAccumR annotateBndr
675
676 annotateLamIdBndr dmd_ty@(DmdType fv ds res) id
677 -- For lambdas we add the demand to the argument demands
678 -- Only called for Ids
679   = ASSERT( isId id )
680     (DmdType fv' (hacked_dmd:ds) res, setIdNewDemandInfo id hacked_dmd)
681   where
682     (fv', dmd) = removeFV fv id res
683     hacked_dmd = argDemand dmd
684         -- This call to argDemand is vital, because otherwise we label
685         -- a lambda binder with demand 'B'.  But in terms of calling
686         -- conventions that's Abs, because we don't pass it.  But
687         -- when we do a w/w split we get
688         --      fw x = (\x y:B -> ...) x (error "oops")
689         -- And then the simplifier things the 'B' is a strict demand
690         -- and evaluates the (error "oops").  Sigh
691
692 removeFV fv id res = (fv', zapUnlifted id dmd)
693                 where
694                   fv' = fv `delVarEnv` id
695                   dmd = lookupVarEnv fv id `orElse` deflt
696                   deflt | isBotRes res = Bot
697                         | otherwise    = Abs
698
699 -- For unlifted-type variables, we are only 
700 -- interested in Bot/Abs/Box Abs
701 zapUnlifted is Bot = Bot
702 zapUnlifted id Abs = Abs
703 zapUnlifted id dmd | isUnLiftedType (idType id) = lazyDmd
704                    | otherwise                  = dmd
705 \end{code}
706
707 %************************************************************************
708 %*                                                                      *
709 \subsection{Strictness signatures}
710 %*                                                                      *
711 %************************************************************************
712
713 \begin{code}
714 type SigEnv  = VarEnv (StrictSig, TopLevelFlag)
715         -- We use the SigEnv to tell us whether to
716         -- record info about a variable in the DmdEnv
717         -- We do so if it's a LocalId, but not top-level
718         --
719         -- The DmdEnv gives the demand on the free vars of the function
720         -- when it is given enough args to satisfy the strictness signature
721
722 emptySigEnv  = emptyVarEnv
723
724 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
725 extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl)
726
727 extendSigEnvList = extendVarEnvList
728
729 extendSigsWithLam :: SigEnv -> Id -> SigEnv
730 -- Extend the SigEnv when we meet a lambda binder
731 -- If the binder is marked demanded with a product demand, then give it a CPR 
732 -- signature, because in the likely event that this is a lambda on a fn defn 
733 -- [we only use this when the lambda is being consumed with a call demand],
734 -- it'll be w/w'd and so it will be CPR-ish.  E.g.
735 --      f = \x::(Int,Int).  if ...strict in x... then
736 --                              x
737 --                          else
738 --                              (a,b)
739 -- We want f to have the CPR property because x does, by the time f has been w/w'd
740 --
741 --      NOTE: see notes [CPR-AND-STRICTNESS]
742 --
743 -- Also note that we only want to do this for something that
744 -- definitely has product type, else we may get over-optimistic 
745 -- CPR results (e.g. from \x -> x!).
746
747 extendSigsWithLam sigs id
748   = case idNewDemandInfo_maybe id of
749         Nothing               -> extendVarEnv sigs id (cprSig, NotTopLevel)
750         Just (Eval (Prod ds)) -> extendVarEnv sigs id (cprSig, NotTopLevel)
751         other                 -> sigs
752
753
754 dmdTransform :: SigEnv          -- The strictness environment
755              -> Id              -- The function
756              -> Demand          -- The demand on the function
757              -> DmdType         -- The demand type of the function in this context
758         -- Returned DmdEnv includes the demand on 
759         -- this function plus demand on its free variables
760
761 dmdTransform sigs var dmd
762
763 ------  DATA CONSTRUCTOR
764   | isDataConWorkId var         -- Data constructor
765   = let 
766         StrictSig dmd_ty    = idNewStrictness var       -- It must have a strictness sig
767         DmdType _ _ con_res = dmd_ty
768         arity               = idArity var
769     in
770     if arity == call_depth then         -- Saturated, so unleash the demand
771         let 
772                 -- Important!  If we Keep the constructor application, then
773                 -- we need the demands the constructor places (always lazy)
774                 -- If not, we don't need to.  For example:
775                 --      f p@(x,y) = (p,y)       -- S(AL)
776                 --      g a b     = f (a,b)
777                 -- It's vital that we don't calculate Absent for a!
778            dmd_ds = case res_dmd of
779                         Box (Eval ds) -> mapDmds box ds
780                         Eval ds       -> ds
781                         other         -> Poly Top
782
783                 -- ds can be empty, when we are just seq'ing the thing
784                 -- If so we must make up a suitable bunch of demands
785            arg_ds = case dmd_ds of
786                       Poly d  -> replicate arity d
787                       Prod ds -> ASSERT( ds `lengthIs` arity ) ds
788
789         in
790         mkDmdType emptyDmdEnv arg_ds con_res
791                 -- Must remember whether it's a product, hence con_res, not TopRes
792     else
793         topDmdType
794
795 ------  IMPORTED FUNCTION
796   | isGlobalId var,             -- Imported function
797     let StrictSig dmd_ty = idNewStrictness var
798   = if dmdTypeDepth dmd_ty <= call_depth then   -- Saturated, so unleash the demand
799         dmd_ty
800     else
801         topDmdType
802
803 ------  LOCAL LET/REC BOUND THING
804   | Just (StrictSig dmd_ty, top_lvl) <- lookupVarEnv sigs var
805   = let
806         fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty 
807               | otherwise                         = deferType dmd_ty
808         -- NB: it's important to use deferType, and not just return topDmdType
809         -- Consider     let { f x y = p + x } in f 1
810         -- The application isn't saturated, but we must nevertheless propagate 
811         --      a lazy demand for p!  
812     in
813     addVarDmd top_lvl fn_ty var dmd
814
815 ------  LOCAL NON-LET/REC BOUND THING
816   | otherwise                   -- Default case
817   = unitVarDmd var dmd
818
819   where
820     (call_depth, res_dmd) = splitCallDmd dmd
821 \end{code}
822
823
824 %************************************************************************
825 %*                                                                      *
826 \subsection{Demands}
827 %*                                                                      *
828 %************************************************************************
829
830 \begin{code}
831 splitCallDmd :: Demand -> (Int, Demand)
832 splitCallDmd (Call d) = case splitCallDmd d of
833                           (n, r) -> (n+1, r)
834 splitCallDmd d        = (0, d)
835
836 vanillaCall :: Arity -> Demand
837 vanillaCall 0 = evalDmd
838 vanillaCall n = Call (vanillaCall (n-1))
839
840 deferType :: DmdType -> DmdType
841 deferType (DmdType fv _ _) = DmdType (deferEnv fv) [] TopRes
842         -- Notice that we throw away info about both arguments and results
843         -- For example,   f = let ... in \x -> x
844         -- We don't want to get a stricness type V->T for f.
845         -- Peter??
846
847 deferEnv :: DmdEnv -> DmdEnv
848 deferEnv fv = mapVarEnv defer fv
849
850
851 ----------------
852 argDemand :: Demand -> Demand
853 -- The 'Defer' demands are just Lazy at function boundaries
854 -- Ugly!  Ask John how to improve it.
855 argDemand Top       = lazyDmd
856 argDemand (Defer d) = lazyDmd
857 argDemand (Eval ds) = Eval (mapDmds argDemand ds)
858 argDemand (Box Bot) = evalDmd
859 argDemand (Box d)   = box (argDemand d)
860 argDemand Bot       = Abs       -- Don't pass args that are consumed (only) by bottom
861 argDemand d         = d
862 \end{code}
863
864 \begin{code}
865 betterStrictness :: StrictSig -> StrictSig -> Bool
866 betterStrictness (StrictSig t1) (StrictSig t2) = betterDmdType t1 t2
867
868 betterDmdType t1 t2 = (t1 `lubType` t2) == t2
869
870 betterDemand :: Demand -> Demand -> Bool
871 -- If d1 `better` d2, and d2 `better` d2, then d1==d2
872 betterDemand d1 d2 = (d1 `lub` d2) == d2
873 \end{code}
874
875 \begin{code}
876 -------------------------
877 -- Consider (if x then y else []) with demand V
878 -- Then the first branch gives {y->V} and the second
879 -- *implicitly* has {y->A}.  So we must put {y->(V `lub` A)}
880 -- in the result env.
881 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
882   = DmdType lub_fv2 (lub_ds ds1 ds2) (r1 `lubRes` r2)
883   where
884     lub_fv  = plusUFM_C lub fv1 fv2
885     lub_fv1 = modifyEnv (not (isBotRes r1)) absLub fv2 fv1 lub_fv
886     lub_fv2 = modifyEnv (not (isBotRes r2)) absLub fv1 fv2 lub_fv1
887         -- lub is the identity for Bot
888
889         -- Extend the shorter argument list to match the longer
890     lub_ds (d1:ds1) (d2:ds2) = lub d1 d2 : lub_ds ds1 ds2
891     lub_ds []       []       = []
892     lub_ds ds1      []       = map (`lub` resTypeArgDmd r2) ds1
893     lub_ds []       ds2      = map (resTypeArgDmd r1 `lub`) ds2
894
895 -----------------------------------
896 -- (t1 `bothType` t2) takes the argument/result info from t1,
897 -- using t2 just for its free-var info
898 -- NB: Don't forget about r2!  It might be BotRes, which is
899 --     a bottom demand on all the in-scope variables.
900 -- Peter: can this be done more neatly?
901 bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
902   = DmdType both_fv2 ds1 (r1 `bothRes` r2)
903   where
904     both_fv  = plusUFM_C both fv1 fv2
905     both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
906     both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
907         -- both is the identity for Abs
908 \end{code}
909
910
911 \begin{code}
912 lubRes BotRes r      = r
913 lubRes r      BotRes = r
914 lubRes RetCPR RetCPR = RetCPR
915 lubRes r1     r2     = TopRes
916
917 -- If either diverges, the whole thing does
918 -- Otherwise take CPR info from the first
919 bothRes r1 BotRes = BotRes
920 bothRes r1 r2     = r1
921 \end{code}
922
923 \begin{code}
924 modifyEnv :: Bool                       -- No-op if False
925           -> (Demand -> Demand)         -- The zapper
926           -> DmdEnv -> DmdEnv           -- Env1 and Env2
927           -> DmdEnv -> DmdEnv           -- Transform this env
928         -- Zap anything in Env1 but not in Env2
929         -- Assume: dom(env) includes dom(Env1) and dom(Env2)
930
931 modifyEnv need_to_modify zapper env1 env2 env
932   | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2))
933   | otherwise      = env
934   where
935     zap uniq env = addToUFM_Directly env uniq (zapper current_val)
936                  where
937                    current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
938 \end{code}
939
940
941 %************************************************************************
942 %*                                                                      *
943 \subsection{LUB and BOTH}
944 %*                                                                      *
945 %************************************************************************
946
947 \begin{code}
948 lub :: Demand -> Demand -> Demand
949
950 lub Bot         d2 = d2
951 lub Abs         d2 = absLub d2
952 lub Top         d2 = Top
953 lub (Defer ds1) d2 = defer (Eval ds1 `lub` d2)
954
955 lub (Call d1)   (Call d2)    = Call (d1 `lub` d2)
956 lub d1@(Call _) (Box d2)     = d1 `lub` d2      -- Just strip the box
957 lub d1@(Call _) d2@(Eval _)  = d2               -- Presumably seq or vanilla eval
958 lub d1@(Call _) d2           = d2 `lub` d1      -- Bot, Abs, Top
959
960 -- For the Eval case, we use these approximation rules
961 -- Box Bot       <= Eval (Box Bot ...)
962 -- Box Top       <= Defer (Box Bot ...)
963 -- Box (Eval ds) <= Eval (map Box ds)
964 lub (Eval ds1)  (Eval ds2)        = Eval (ds1 `lubs` ds2)
965 lub (Eval ds1)  (Box Bot)         = Eval (mapDmds (`lub` Box Bot) ds1)
966 lub (Eval ds1)  (Box (Eval ds2)) = Eval (ds1 `lubs` mapDmds box ds2)
967 lub (Eval ds1)  (Box Abs)        = deferEval (mapDmds (`lub` Box Bot) ds1)
968 lub d1@(Eval _) d2                = d2 `lub` d1 -- Bot,Abs,Top,Call,Defer
969
970 lub (Box d1)   (Box d2) = box (d1 `lub` d2)
971 lub d1@(Box _)  d2      = d2 `lub` d1
972
973 lubs = zipWithDmds lub
974
975 ---------------------
976 -- box is the smart constructor for Box
977 -- It computes <B,bot> & d
978 -- INVARIANT: (Box d) => d = Bot, Abs, Eval
979 -- Seems to be no point in allowing (Box (Call d))
980 box (Call d)  = Call d  -- The odd man out.  Why?
981 box (Box d)   = Box d
982 box (Defer _) = lazyDmd
983 box Top       = lazyDmd -- Box Abs and Box Top
984 box Abs       = lazyDmd -- are the same <B,L>
985 box d         = Box d   -- Bot, Eval
986
987 ---------------
988 defer :: Demand -> Demand
989
990 -- defer is the smart constructor for Defer
991 -- The idea is that (Defer ds) = <U(ds), L>
992 --
993 -- It specifies what happens at a lazy function argument
994 -- or a lambda; the L* operator
995 -- Set the strictness part to L, but leave
996 -- the boxity side unaffected
997 -- It also ensures that Defer (Eval [LLLL]) = L
998
999 defer Bot        = Abs
1000 defer Abs        = Abs
1001 defer Top        = Top
1002 defer (Call _)   = lazyDmd      -- Approximation here?
1003 defer (Box _)    = lazyDmd
1004 defer (Defer ds) = Defer ds
1005 defer (Eval ds)  = deferEval ds
1006
1007 -- deferEval ds = defer (Eval ds)
1008 deferEval ds | allTop ds = Top
1009              | otherwise  = Defer ds
1010
1011 ---------------------
1012 absLub :: Demand -> Demand
1013 -- Computes (Abs `lub` d)
1014 -- For the Bot case consider
1015 --      f x y = if ... then x else error x
1016 --   Then for y we get Abs `lub` Bot, and we really
1017 --   want Abs overall
1018 absLub Bot        = Abs
1019 absLub Abs        = Abs
1020 absLub Top        = Top
1021 absLub (Call _)   = Top
1022 absLub (Box _)    = Top
1023 absLub (Eval ds)  = Defer (absLubs ds)  -- Or (Defer ds)?
1024 absLub (Defer ds) = Defer (absLubs ds)  -- Or (Defer ds)?
1025
1026 absLubs = mapDmds absLub
1027
1028 ---------------
1029 both :: Demand -> Demand -> Demand
1030
1031 both Abs d2 = d2
1032
1033 both Bot Bot       = Bot
1034 both Bot Abs       = Bot 
1035 both Bot (Eval ds) = Eval (mapDmds (`both` Bot) ds)
1036         -- Consider
1037         --      f x = error x
1038         -- From 'error' itself we get demand Bot on x
1039         -- From the arg demand on x we get 
1040         --      x :-> evalDmd = Box (Eval (Poly Abs))
1041         -- So we get  Bot `both` Box (Eval (Poly Abs))
1042         --          = Seq Keep (Poly Bot)
1043         --
1044         -- Consider also
1045         --      f x = if ... then error (fst x) else fst x
1046         -- Then we get (Eval (Box Bot, Bot) `lub` Eval (SA))
1047         --      = Eval (SA)
1048         -- which is what we want.
1049 both Bot d = errDmd
1050
1051 both Top Bot         = errDmd
1052 both Top Abs         = Top
1053 both Top Top         = Top
1054 both Top (Box d)    = Box d
1055 both Top (Call d)   = Call d
1056 both Top (Eval ds)  = Eval (mapDmds (`both` Top) ds)
1057 both Top (Defer ds)     -- = defer (Top `both` Eval ds)
1058                         -- = defer (Eval (mapDmds (`both` Top) ds))
1059                      = deferEval (mapDmds (`both` Top) ds)
1060
1061
1062 both (Box d1)   (Box d2)    = box (d1 `both` d2)
1063 both (Box d1)   d2@(Call _) = box (d1 `both` d2)
1064 both (Box d1)   d2@(Eval _) = box (d1 `both` d2)
1065 both (Box d1)   (Defer d2)  = Box d1
1066 both d1@(Box _) d2          = d2 `both` d1
1067
1068 both (Call d1)   (Call d2)   = Call (d1 `both` d2)
1069 both (Call d1)   (Eval ds2)  = Call d1  -- Could do better for (Poly Bot)?
1070 both (Call d1)   (Defer ds2) = Call d1  -- Ditto
1071 both d1@(Call _) d2          = d1 `both` d1
1072
1073 both (Eval ds1)    (Eval  ds2) = Eval (ds1 `boths` ds2)
1074 both (Eval ds1)    (Defer ds2) = Eval (ds1 `boths` mapDmds defer ds2)
1075 both d1@(Eval ds1) d2          = d2 `both` d1
1076
1077 both (Defer ds1) (Defer ds2) = deferEval (ds1 `boths` ds2)
1078 both d1@(Defer ds1) d2       = d2 `both` d1
1079  
1080 boths = zipWithDmds both
1081 \end{code}
1082
1083
1084
1085 %************************************************************************
1086 %*                                                                      *
1087 \subsection{Miscellaneous
1088 %*                                                                      *
1089 %************************************************************************
1090
1091
1092 \begin{code}
1093 #ifdef OLD_STRICTNESS
1094 get_changes binds = vcat (map get_changes_bind binds)
1095
1096 get_changes_bind (Rec pairs) = vcat (map get_changes_pr pairs)
1097 get_changes_bind (NonRec id rhs) = get_changes_pr (id,rhs)
1098
1099 get_changes_pr (id,rhs) 
1100   = get_changes_var id $$ get_changes_expr rhs
1101
1102 get_changes_var var
1103   | isId var  = get_changes_str var $$ get_changes_dmd var
1104   | otherwise = empty
1105
1106 get_changes_expr (Type t)     = empty
1107 get_changes_expr (Var v)      = empty
1108 get_changes_expr (Lit l)      = empty
1109 get_changes_expr (Note n e)   = get_changes_expr e
1110 get_changes_expr (App e1 e2)  = get_changes_expr e1 $$ get_changes_expr e2
1111 get_changes_expr (Lam b e)    = {- get_changes_var b $$ -} get_changes_expr e
1112 get_changes_expr (Let b e)    = get_changes_bind b $$ get_changes_expr e
1113 get_changes_expr (Case e b a) = get_changes_expr e $$ {- get_changes_var b $$ -} vcat (map get_changes_alt a)
1114
1115 get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs
1116
1117 get_changes_str id
1118   | new_better && old_better = empty
1119   | new_better               = message "BETTER"
1120   | old_better               = message "WORSE"
1121   | otherwise                = message "INCOMPARABLE" 
1122   where
1123     message word = text word <+> text "strictness for" <+> ppr id <+> info
1124     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
1125     new = squashSig (idNewStrictness id)        -- Don't report spurious diffs that the old
1126                                                 -- strictness analyser can't track
1127     old = newStrictnessFromOld (idName id) (idArity id) (idStrictness id) (idCprInfo id)
1128     old_better = old `betterStrictness` new
1129     new_better = new `betterStrictness` old
1130
1131 get_changes_dmd id
1132   | isUnLiftedType (idType id) = empty  -- Not useful
1133   | new_better && old_better = empty
1134   | new_better               = message "BETTER"
1135   | old_better               = message "WORSE"
1136   | otherwise                = message "INCOMPARABLE" 
1137   where
1138     message word = text word <+> text "demand for" <+> ppr id <+> info
1139     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
1140     new = squashDmd (argDemand (idNewDemandInfo id))    -- To avoid spurious improvements
1141                                                         -- A bit of a hack
1142     old = newDemand (idDemandInfo id)
1143     new_better = new `betterDemand` old 
1144     old_better = old `betterDemand` new
1145 #endif
1146
1147 squashSig (StrictSig (DmdType fv ds res))
1148   = StrictSig (DmdType emptyDmdEnv (map squashDmd ds) res)
1149   where
1150         -- squash just gets rid of call demands
1151         -- which the old analyser doesn't track
1152 squashDmd (Call d)   = evalDmd
1153 squashDmd (Box d)    = Box (squashDmd d)
1154 squashDmd (Eval ds)  = Eval (mapDmds squashDmd ds)
1155 squashDmd (Defer ds) = Defer (mapDmds squashDmd ds)
1156 squashDmd d          = d
1157 \end{code}