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