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