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