[project @ 2001-07-19 09:26:33 by simonpj]
[ghc-hetmet.git] / ghc / compiler / stranal / DmdAnal.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4
5                         -----------------
6                         A demand analysis
7                         -----------------
8
9 \begin{code}
10 module DmdAnal ( dmdAnalPgm ) where
11
12 #include "HsVersions.h"
13
14 import CmdLineOpts      ( DynFlags, DynFlag(..) )
15 import NewDemand        -- All of it
16 import CoreSyn
17 import CoreUtils        ( exprIsValue, exprArity )
18 import DataCon          ( dataConTyCon )
19 import TyCon            ( isProductTyCon, isRecursiveTyCon )
20 import Id               ( Id, idType, idInfo, idArity, idStrictness, idCprInfo, idDemandInfo,
21                           modifyIdInfo, isDataConId, isImplicitId, isGlobalId )
22 import IdInfo           ( newStrictnessInfo, setNewStrictnessInfo, mkNewStrictnessInfo,
23                           newDemandInfo, setNewDemandInfo, newDemand
24                         )
25 import Var              ( Var )
26 import VarEnv
27 import UniqFM           ( plusUFM_C, addToUFM_Directly, lookupUFM_Directly,
28                           keysUFM, minusUFM, ufmToList )
29 import Type             ( isUnLiftedType )
30 import CoreLint         ( showPass, endPass )
31 import ErrUtils         ( dumpIfSet_dyn )
32 import Util             ( mapAndUnzip, mapAccumL, mapAccumR, zipWithEqual )
33 import BasicTypes       ( Arity, TopLevelFlag(..), isTopLevel )
34 import Maybes           ( orElse, expectJust )
35 import Outputable
36 import FastTypes
37 \end{code}
38
39 ToDo:   set a noinline pragma on bottoming Ids
40 \begin{code}
41 instance Outputable TopLevelFlag where
42   ppr flag = empty
43 \end{code}
44
45 %************************************************************************
46 %*                                                                      *
47 \subsection{Top level stuff}
48 %*                                                                      *
49 %************************************************************************
50
51 \begin{code}
52 dmdAnalPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
53 #ifndef DEBUG
54
55 dmdAnalPgm dflags binds = return binds
56
57 #else
58
59 dmdAnalPgm dflags binds
60   = do {
61         showPass dflags "Demand analysis" ;
62         let { binds_plus_dmds = do_prog binds ;
63               dmd_changes = get_changes binds_plus_dmds } ;
64         endPass dflags "Demand analysis" 
65                 Opt_D_dump_stranal binds_plus_dmds ;
66         printDump (text "Changes in demands" $$ dmd_changes) ;
67         return binds_plus_dmds
68     }
69   where
70     do_prog :: [CoreBind] -> [CoreBind]
71     do_prog binds = snd $ mapAccumL dmdAnalTopBind emptySigEnv binds
72
73 dmdAnalTopBind :: SigEnv
74                -> CoreBind 
75                -> (SigEnv, CoreBind)
76 dmdAnalTopBind sigs (NonRec id rhs)
77   | isImplicitId id             -- Don't touch the info on constructors, selectors etc
78   = (sigs, NonRec id rhs)       -- It's pre-computed in MkId.lhs
79   | otherwise
80   = let
81         (sigs', (id', rhs')) = downRhs TopLevel sigs (id, rhs)
82     in
83     (sigs', NonRec id' rhs')    
84
85 dmdAnalTopBind sigs (Rec pairs)
86   = let
87         (sigs', pairs')  = dmdFix TopLevel sigs pairs
88     in
89     (sigs', Rec pairs')
90 \end{code}
91
92
93 %************************************************************************
94 %*                                                                      *
95 \subsection{The analyser itself}        
96 %*                                                                      *
97 %************************************************************************
98
99 \begin{code}
100 dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
101
102 dmdAnal sigs Abs  e = (topDmdType, e)
103
104 dmdAnal sigs Lazy e = let 
105                         (res_ty, e') = dmdAnal sigs Eval e
106                       in
107                       (deferType res_ty, e')
108         -- It's important not to analyse e with a lazy demand because
109         -- a) When we encounter   case s of (a,b) -> 
110         --      we demand s with U(d1d2)... but if the overall demand is lazy
111         --      that is wrong, and we'd need to reduce the demand on s,
112         --      which is inconvenient
113         -- b) More important, consider
114         --      f (let x = R in x+x), where f is lazy
115         --    We still want to mark x as demanded, because it will be when we
116         --    enter the let.  If we analyse f's arg with a Lazy demand, we'll
117         --    just mark x as Lazy
118
119
120 dmdAnal sigs dmd (Lit lit)
121   = (topDmdType, Lit lit)
122
123 dmdAnal sigs dmd (Var var)
124   = (dmdTransform sigs var dmd, Var var)
125
126 dmdAnal sigs dmd (Note n e)
127   = (dmd_ty, Note n e')
128   where
129     (dmd_ty, e') = dmdAnal sigs dmd e   
130
131 dmdAnal sigs dmd (App fun (Type ty))
132   = (fun_ty, App fun' (Type ty))
133   where
134     (fun_ty, fun') = dmdAnal sigs dmd fun
135
136 dmdAnal sigs dmd (App fun arg)  -- Non-type arguments
137   = let                         -- [Type arg handled above]
138         (fun_ty, fun')    = dmdAnal sigs (Call dmd) fun
139         (arg_ty, arg')    = dmdAnal sigs arg_dmd arg
140         (arg_dmd, res_ty) = splitDmdTy fun_ty
141     in
142     (res_ty `bothType` arg_ty, App fun' arg')
143
144 dmdAnal sigs dmd (Lam var body)
145   | isTyVar var
146   = let   
147         (body_ty, body') = dmdAnal sigs dmd body
148     in
149     (body_ty, Lam var body')
150
151   | otherwise
152   = let
153         body_dmd = case dmd of
154                         Call dmd -> dmd
155                         other    -> Lazy        -- Conservative
156
157         (body_ty, body') = dmdAnal sigs body_dmd body
158         (lam_ty, var') = annotateLamIdBndr body_ty var
159     in
160     (lam_ty, Lam var' body')
161
162 dmdAnal sigs dmd (Case scrut case_bndr [alt@(DataAlt dc,bndrs,rhs)])
163   | let tycon = dataConTyCon dc,
164     isProductTyCon tycon,
165     not (isRecursiveTyCon tycon)
166   = let
167         bndr_ids                = filter isId bndrs
168         (alt_ty, alt')          = dmdAnalAlt sigs dmd alt
169         (alt_ty1, case_bndr')   = annotateBndr alt_ty case_bndr
170         (_, bndrs', _)          = alt'
171         scrut_dmd               = Seq Drop Now [idNewDemandInfo b | b <- bndrs', isId b]
172         (scrut_ty, scrut')      = dmdAnal sigs scrut_dmd scrut
173     in
174     (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' [alt'])
175
176 dmdAnal sigs dmd (Case scrut case_bndr alts)
177   = let
178         (alt_tys, alts')        = mapAndUnzip (dmdAnalAlt sigs dmd) alts
179         (scrut_ty, scrut')      = dmdAnal sigs Eval scrut
180         (alt_ty, case_bndr')    = annotateBndr (foldr1 lubType alt_tys) case_bndr
181     in
182 --    pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
183     (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' alts')
184
185 dmdAnal sigs dmd (Let (NonRec id rhs) body) 
186   = let
187         (sigs', (id1, rhs')) = downRhs NotTopLevel sigs (id, rhs)
188         (body_ty, body')     = dmdAnal sigs' dmd body
189         (body_ty1, id2)      = annotateBndr body_ty id1
190     in
191 --    pprTrace "dmdLet" (ppr id <+> ppr (sig,rhs_env))
192     (body_ty1, Let (NonRec id2 rhs') body')    
193
194 dmdAnal sigs dmd (Let (Rec pairs) body) 
195   = let
196         bndrs            = map fst pairs
197         (sigs', pairs')  = dmdFix NotTopLevel sigs pairs
198         (body_ty, body') = dmdAnal sigs' dmd body
199
200                 -- I saw occasions where it was really worth using the
201                 -- call demands on the Ids to propagate demand info
202                 -- on the free variables.  An example is 'roll' in imaginary/wheel-sieve2
203                 -- Something like this:
204                 --      roll x = letrec go y = if ... then roll (x-1) else x+1
205                 --               in go ms
206                 -- We want to see that this is strict in x.
207                 --
208                 -- This will happen because sigs' has a binding for 'go' that 
209                 -- has a demand on x.
210
211         (result_ty, _) = annotateBndrs body_ty bndrs
212                 -- Don't bother to add demand info to recursive
213                 -- binders as annotateBndr does; 
214                 -- being recursive, we can't treat them strictly.
215                 -- But we do need to remove the binders from the result demand env
216     in
217     (result_ty,  Let (Rec pairs') body')
218
219
220 dmdAnalAlt sigs dmd (con,bndrs,rhs) 
221   = let 
222         (rhs_ty, rhs')   = dmdAnal sigs dmd rhs
223         (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs
224     in
225     (alt_ty, (con, bndrs', rhs'))
226 \end{code}
227
228 %************************************************************************
229 %*                                                                      *
230 \subsection{Bindings}
231 %*                                                                      *
232 %************************************************************************
233
234 \begin{code}
235 dmdFix :: TopLevelFlag
236        -> SigEnv                -- Does not include bindings for this binding
237        -> [(Id,CoreExpr)]
238        -> (SigEnv,
239            [(Id,CoreExpr)])     -- Binders annotated with stricness info
240
241 dmdFix top_lvl sigs pairs
242   = loop 1 initial_sigs pairs
243   where
244     bndrs        = map fst pairs
245     initial_sigs = extendSigEnvList sigs [(id, (initial_sig id, top_lvl)) | id <- bndrs]
246     
247     loop :: Int
248          -> SigEnv                      -- Already contains the current sigs
249          -> [(Id,CoreExpr)]             
250          -> (SigEnv, [(Id,CoreExpr)])
251     loop n sigs pairs
252       | all (same_sig sigs sigs') bndrs = (sigs, pairs)
253                 -- Note: use pairs, not pairs'.   Since the sigs are the same
254                 -- there'll be no change, unless this is the very first visit,
255                 -- and the first iteraion of that visit.  But in that case, the 
256                 -- function is bottom anyway, there's no point in looking.
257       | n >= 5              = pprTrace "dmdFix" (ppr n <+> ppr pairs)   (loop (n+1) sigs' pairs')
258       | otherwise           = {- pprTrace "dmdFixLoop" (ppr id_sigs) -} (loop (n+1) sigs' pairs')
259       where
260                 -- Use the new signature to do the next pair
261                 -- The occurrence analyser has arranged them in a good order
262                 -- so this can significantly reduce the number of iterations needed
263         (sigs', pairs') = mapAccumL (downRhs top_lvl) sigs pairs
264
265            
266         -- Get an initial strictness signature from the Id
267         -- itself.  That way we make use of earlier iterations
268         -- of the fixpoint algorithm.  (Cunning plan.)
269         -- Note that the cunning plan extends to the DmdEnv too,
270         -- since it is part of the strictness signature
271     initial_sig id = idNewStrictness_maybe id `orElse` botSig
272
273     same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
274     lookup sigs var = case lookupVarEnv sigs var of
275                         Just (sig,_) -> sig
276
277 downRhs :: TopLevelFlag 
278         -> SigEnv -> (Id, CoreExpr)
279         -> (SigEnv,  (Id, CoreExpr))
280 -- On the way down, compute a strictness signature 
281 -- for the function.  Keep its annotated RHS and dmd env
282 -- for use on the way up
283 -- The demand-env is that computed for a vanilla call.
284
285 downRhs top_lvl sigs (id, rhs)
286  = (sigs', (id', rhs'))
287  where
288   arity          = exprArity rhs   -- The idArity may not be up to date
289   (rhs_ty, rhs') = dmdAnal sigs (vanillaCall arity) rhs
290   sig            = mkStrictSig id arity (mkSigTy rhs rhs_ty)
291   id'            = id `setIdNewStrictness` sig
292   sigs'          = extendSigEnv top_lvl sigs id sig
293
294 mkSigTy rhs (DmdType fv [] RetCPR) 
295         | not (exprIsValue rhs)    = DmdType fv [] TopRes
296         -- If the rhs is a thunk, we forget the CPR info, because
297         -- it is presumably shared (else it would have been inlined, and 
298         -- so we'd lose sharing if w/w'd it into a function.
299         --
300         -- ** But keep the demand unleashed on the free 
301         --    vars when the thing is evaluated! **
302         -- 
303         --      DONE IN OLD CPR ANALYSER, BUT NOT YET HERE
304         -- Also, if the strictness analyser has figured out that it's strict,
305         -- the let-to-case transformation will happen, so again it's good.
306         -- (CPR analysis runs before the simplifier has had a chance to do
307         --  the let-to-case transform.)
308         -- This made a big difference to PrelBase.modInt, which had something like
309         --      modInt = \ x -> let r = ... -> I# v in
310         --                      ...body strict in r...
311         -- r's RHS isn't a value yet; but modInt returns r in various branches, so
312         -- if r doesn't have the CPR property then neither does modInt
313
314 mkSigTy rhs (DmdType fv dmds res) = DmdType fv (map lazify dmds) res
315 -- Get rid of defers
316 \end{code}
317
318
319 %************************************************************************
320 %*                                                                      *
321 \subsection{Strictness signatures and types}
322 %*                                                                      *
323 %************************************************************************
324
325 \begin{code}
326 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
327
328 addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd
329   | isTopLevel top_lvl = dmd_ty         -- Don't record top level things
330   | otherwise          = DmdType (extendVarEnv fv var dmd) ds res
331
332 annotateBndr :: DmdType -> Var -> (DmdType, Var)
333 -- The returned env has the var deleted
334 -- The returned var is annotated with demand info
335 -- No effect on the argument demands
336 annotateBndr dmd_ty@(DmdType fv ds res) var
337   | isTyVar var = (dmd_ty, var)
338   | otherwise   = (DmdType fv' ds res, setIdNewDemandInfo var dmd)
339   where
340     (fv', dmd) = removeFV fv var res
341
342 annotateBndrs = mapAccumR annotateBndr
343
344 annotateLamIdBndr dmd_ty@(DmdType fv ds res) id
345 -- For lambdas we add the demand to the argument demands
346 -- Only called for Ids
347   = ASSERT( isId id )
348     (DmdType fv' (dmd:ds) res, setIdNewDemandInfo id dmd)
349   where
350     (fv', dmd) = removeFV fv id res
351
352 removeFV fv var res = (fv', dmd)
353                 where
354                   fv' = fv `delVarEnv` var
355                   dmd = lookupVarEnv fv var `orElse` deflt
356                   deflt | isBotRes res = Bot
357                         | otherwise    = Abs
358 \end{code}
359
360 %************************************************************************
361 %*                                                                      *
362 \subsection{Demand types}
363 %*                                                                      *
364 %************************************************************************
365
366 \begin{code}
367 splitDmdTy :: DmdType -> (Demand, DmdType)
368 -- Split off one function argument
369 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
370 splitDmdTy ty@(DmdType fv [] TopRes)         = (topDmd, ty)
371 splitDmdTy ty@(DmdType fv [] BotRes)         = (Abs,    ty)
372         -- We already have a suitable demand on all
373         -- free vars, so no need to add more!
374 splitDmdTy (DmdType fv [] RetCPR)         = panic "splitDmdTy"
375
376 -------------------------
377 dmdTypeRes :: DmdType -> DmdResult
378 dmdTypeRes (DmdType _ _ res_ty) = res_ty
379 \end{code}
380
381
382 %************************************************************************
383 %*                                                                      *
384 \subsection{Strictness signatures}
385 %*                                                                      *
386 %************************************************************************
387
388 \begin{code}
389 type SigEnv  = VarEnv (StrictSig, TopLevelFlag)
390         -- We use the SigEnv to tell us whether to
391         -- record info about a variable in the DmdEnv
392         -- We do so if it's a LocalId, but not top-level
393         --
394         -- The DmdEnv gives the demand on the free vars of the function
395         -- when it is given enough args to satisfy the strictness signature
396
397 emptySigEnv  = emptyVarEnv
398
399 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
400 extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl)
401
402 extendSigEnvList = extendVarEnvList
403
404 dmdTransform :: SigEnv          -- The strictness environment
405              -> Id              -- The function
406              -> Demand          -- The demand on the function
407              -> DmdType         -- The demand type of the function in this context
408         -- Returned DmdEnv includes the demand on 
409         -- this function plus demand on its free variables
410
411 dmdTransform sigs var dmd
412
413 ------  DATA CONSTRUCTOR
414   | isDataConId var,            -- Data constructor
415     Seq k Now ds <- res_dmd,    -- and the demand looks inside its fields
416     let StrictSig arity dmd_ty = idNewStrictness var    -- It must have a strictness sig
417   = if arity == length ds then  -- Saturated, so unleash the demand
418         -- ds can be empty, when we are just seq'ing the thing
419         mkDmdType emptyDmdEnv ds (dmdTypeRes dmd_ty)
420                 -- Need to extract whether it's a product
421     else
422         topDmdType
423
424 ------  IMPORTED FUNCTION
425   | isGlobalId var,             -- Imported function
426     let StrictSig arity dmd_ty = getNewStrictness var
427   = if arity <= depth then      -- Saturated, so unleash the demand
428         dmd_ty
429     else
430         topDmdType
431
432 ------  LOCAL LET/REC BOUND THING
433   | Just (StrictSig arity dmd_ty, top_lvl) <- lookupVarEnv sigs var
434   = let
435         fn_ty = if arity <= depth then dmd_ty else topDmdType
436     in
437     addVarDmd top_lvl fn_ty var dmd
438
439 ------  LOCAL NON-LET/REC BOUND THING
440   | otherwise                   -- Default case
441   = unitVarDmd var dmd
442
443   where
444     (depth, res_dmd) = splitCallDmd dmd
445 \end{code}
446
447 \begin{code}
448 squashDmdEnv (StrictSig a (DmdType fv ds res)) = StrictSig a (DmdType emptyDmdEnv ds res)
449
450 betterStrict :: StrictSig -> StrictSig -> Bool
451 betterStrict (StrictSig ar1 t1) (StrictSig ar2 t2)
452   = (ar1 >= ar2) && (t1 `betterDmdType` t2)
453
454 betterDmdType t1 t2 = (t1 `lubType` t2) == t2
455 \end{code}
456
457
458 %************************************************************************
459 %*                                                                      *
460 \subsection{Demands}
461 %*                                                                      *
462 %************************************************************************
463
464 \begin{code}
465 splitCallDmd :: Demand -> (Int, Demand)
466 splitCallDmd (Call d) = case splitCallDmd d of
467                           (n, r) -> (n+1, r)
468 splitCallDmd d        = (0, d)
469
470 vanillaCall :: Arity -> Demand
471 vanillaCall 0 = Eval
472 vanillaCall n = Call (vanillaCall (n-1))
473
474 deferType :: DmdType -> DmdType
475 deferType (DmdType fv ds _) = DmdType (mapVarEnv defer fv) ds TopRes
476         -- Check this
477
478 defer :: Demand -> Demand
479 -- c.f. `lub` Abs
480 defer Abs          = Abs
481 defer (Seq k _ ds) = Seq k Defer ds
482 defer other        = Lazy
483
484 lazify :: Demand -> Demand
485 -- The 'Defer' demands are just Lazy at function boundaries
486 lazify (Seq k Defer ds) = Lazy
487 lazify (Seq k Now   ds) = Seq k Now (map lazify ds)
488 lazify d                = d
489
490 betterDemand :: Demand -> Demand -> Bool
491 -- If d1 `better` d2, and d2 `better` d2, then d1==d2
492 betterDemand d1 d2 = (d1 `lub` d2) == d2
493 \end{code}
494
495
496 %************************************************************************
497 %*                                                                      *
498 \subsection{LUB and BOTH}
499 %*                                                                      *
500 %************************************************************************
501
502 \begin{code}
503 lub :: Demand -> Demand -> Demand
504
505 lub Bot  d = d
506
507 lub Lazy d = Lazy
508
509 lub Err Bot = Err 
510 lub Err d   = d 
511
512 lub Abs Bot          = Abs
513 lub Abs Err          = Abs
514 lub Abs Abs          = Abs    
515 lub Abs (Seq k _ ds) = Seq k Defer ds   -- Very important ('radicals' example)
516 lub Abs d            = Lazy
517
518 lub Eval Abs            = Lazy
519 lub Eval Lazy           = Lazy
520 lub Eval (Seq k Now ds) = Seq Keep Now ds
521 lub Eval d              = Eval
522
523 lub (Call d1) (Call d2) = Call (lub d1 d2)
524
525 lub (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) (l1 `or_defer` l2)
526                                           (zipWithEqual "lub" lub ds1 ds2)
527
528 -- The last clauses deal with the remaining cases for Call and Seq
529 lub d1@(Call _) d2@(Seq _ _ _) = pprPanic "lub" (ppr d1 $$ ppr d2)
530 lub d1 d2                      = lub d2 d1
531
532 or_defer Now Now = Now
533 or_defer _   _   = Defer
534
535 -------------------------
536 -- Consider (if x then y else []) with demand V
537 -- Then the first branch gives {y->V} and the second
538 -- *implicitly* has {y->A}.  So we must put {y->(V `lub` A)}
539 -- in the result env.
540 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
541   = DmdType lub_fv2 (zipWith lub ds1 ds2) (r1 `lubRes` r2)
542   where
543     lub_fv  = plusUFM_C lub fv1 fv2
544     lub_fv1 = modifyEnv (not (isBotRes r1)) (Abs `lub`) fv2 fv1 lub_fv
545     lub_fv2 = modifyEnv (not (isBotRes r2)) (Abs `lub`) fv1 fv2 lub_fv1
546         -- lub is the identity for Bot
547
548 -------------------------
549 lubRes BotRes r      = r
550 lubRes r      BotRes = r
551 lubRes RetCPR RetCPR = RetCPR
552 lubRes r1     r2     = TopRes
553
554 -----------------------------------
555 vee :: Keepity -> Keepity -> Keepity
556 vee Drop Drop = Drop
557 vee k1   k2   = Keep
558
559 -----------------------------------
560 both :: Demand -> Demand -> Demand
561
562 both Bot d = Bot
563
564 both Abs Bot = Bot
565 both Abs d   = d
566
567 both Err Bot = Bot
568 both Err Abs = Err
569 both Err d   = d
570
571 both Lazy Bot            = Bot
572 both Lazy Abs            = Lazy
573 both Lazy Err            = Lazy 
574 both Lazy (Seq k Now ds) = Seq Keep Now ds
575 both Lazy d              = d
576
577 both Eval Bot          = Bot
578 both Eval (Seq k l ds) = Seq Keep Now ds
579 both Eval (Call d)     = Call d
580 both Eval d            = Eval
581
582 both (Seq k1 Defer ds1) (Seq k2 Defer ds2) = Seq (k1 `vee` k2) Defer
583                                                  (zipWithEqual "both" both ds1 ds2)
584 both (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) Now
585                                            (zipWithEqual "both" both ds1' ds2')
586                                      where
587                                         ds1' = case l1 of { Now -> ds1; Defer -> map defer ds1 }
588                                         ds2' = case l2 of { Now -> ds2; Defer -> map defer ds2 }
589
590 both (Call d1) (Call d2) = Call (d1 `both` d2)
591
592 -- The last clauses deal with the remaining cases for Call and Seq
593 both d1@(Call _) d2@(Seq _ _ _) = pprPanic "both" (ppr d1 $$ ppr d2)
594 both d1 d2                      = both d2 d1
595
596 -----------------------------------
597 bothRes :: DmdResult -> DmdResult -> DmdResult
598 -- Left-biased for CPR info
599 bothRes BotRes _ = BotRes
600 bothRes _ BotRes = BotRes
601 bothRes r1 _     = r1
602
603 -----------------------------------
604 -- (t1 `bothType` t2) takes the argument/result info from t1,
605 -- using t2 just for its free-var info
606 bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
607   = DmdType both_fv2 ds1 r1
608   where
609     both_fv  = plusUFM_C both fv1 fv2
610     both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
611     both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
612         -- both is the identity for Abs
613 \end{code}
614
615 \begin{code}
616 modifyEnv :: Bool                       -- No-op if False
617           -> (Demand -> Demand)         -- The zapper
618           -> DmdEnv -> DmdEnv           -- Env1 and Env2
619           -> DmdEnv -> DmdEnv           -- Transform this env
620         -- Zap anything in Env1 but not in Env2
621         -- Assume: dom(env) includes dom(Env1) and dom(Env2)
622
623 modifyEnv need_to_modify zapper env1 env2 env
624   | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2))
625   | otherwise      = env
626   where
627     zap uniq env = addToUFM_Directly env uniq (zapper current_val)
628                  where
629                    current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
630 \end{code}
631
632
633 %************************************************************************
634 %*                                                                      *
635 \subsection{Miscellaneous
636 %*                                                                      *
637 %************************************************************************
638
639
640 \begin{code}
641 -- Move these to Id.lhs
642 idNewStrictness_maybe :: Id -> Maybe StrictSig
643 idNewStrictness :: Id -> StrictSig
644
645 idNewStrictness_maybe id = newStrictnessInfo (idInfo id)
646 idNewStrictness       id = idNewStrictness_maybe id `orElse` topSig
647
648 getNewStrictness :: Id -> StrictSig
649 -- First tries the "new-strictness" field, and then
650 -- reverts to the old one. This is just until we have
651 -- cross-module info for new strictness
652 getNewStrictness id = idNewStrictness_maybe id `orElse` newStrictnessFromOld id
653                       
654 newStrictnessFromOld :: Id -> StrictSig
655 newStrictnessFromOld id = mkNewStrictnessInfo id (idArity id) (idStrictness id) (idCprInfo id)
656
657 setIdNewStrictness :: Id -> StrictSig -> Id
658 setIdNewStrictness id sig = modifyIdInfo (`setNewStrictnessInfo` sig) id
659
660 idNewDemandInfo :: Id -> Demand
661 idNewDemandInfo id = newDemandInfo (idInfo id)
662
663 setIdNewDemandInfo :: Id -> Demand -> Id
664 setIdNewDemandInfo id dmd = modifyIdInfo (`setNewDemandInfo` dmd) id
665 \end{code}
666
667 \begin{code}
668 get_changes binds = vcat (map get_changes_bind binds)
669
670 get_changes_bind (Rec pairs) = vcat (map get_changes_pr pairs)
671 get_changes_bind (NonRec id rhs) = get_changes_pr (id,rhs)
672
673 get_changes_pr (id,rhs) = get_changes_var id $$ get_changes_expr rhs
674
675 get_changes_var var
676   | isId var  = get_changes_str var $$ get_changes_dmd var
677   | otherwise = empty
678
679 get_changes_expr (Type t)     = empty
680 get_changes_expr (Var v)      = empty
681 get_changes_expr (Lit l)      = empty
682 get_changes_expr (Note n e)   = get_changes_expr e
683 get_changes_expr (App e1 e2)  = get_changes_expr e1 $$ get_changes_expr e2
684 get_changes_expr (Lam b e)    = {- get_changes_var b $$ -} get_changes_expr e
685 get_changes_expr (Let b e)    = get_changes_bind b $$ get_changes_expr e
686 get_changes_expr (Case e b a) = get_changes_expr e $$ get_changes_var b $$ vcat (map get_changes_alt a)
687
688 get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs
689
690 get_changes_str id
691   | new_better && old_better = empty
692   | new_better               = message "BETTER"
693   | old_better               = message "WORSE"
694   | otherwise                = message "INCOMPARABLE" 
695   where
696     message word = text word <+> text "strictness for" <+> ppr id <+> info
697     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
698     new = squashDmdEnv (idNewStrictness id)     -- Don't report diffs in the env
699     old = newStrictnessFromOld id
700     old_better = old `betterStrict` new
701     new_better = new `betterStrict` old
702
703 get_changes_dmd id
704   | isUnLiftedType (idType id) = empty  -- Not useful
705   | new_better && old_better = empty
706   | new_better               = message "BETTER"
707   | old_better               = message "WORSE"
708   | otherwise                = message "INCOMPARABLE" 
709   where
710     message word = text word <+> text "demand for" <+> ppr id <+> info
711     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
712     new = lazify (idNewDemandInfo id)   -- Lazify to avoid spurious improvements
713     old = newDemand (idDemandInfo id)
714     new_better = new `betterDemand` old 
715     old_better = old `betterDemand` new
716 #endif  /* DEBUG */
717 \end{code}