[project @ 2001-07-20 10:09:32 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, filterUFM )
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   | Call body_dmd <- dmd        -- A call demand: good!
152   = let 
153         (body_ty, body') = dmdAnal sigs body_dmd body
154         (lam_ty, var')   = annotateLamIdBndr body_ty var
155     in
156     (lam_ty, Lam var' body')
157
158   | otherwise   -- Not enough demand on the lambda; but do the body
159   = let         -- anyway to annotate it and gather free var info
160         (body_ty, body') = dmdAnal sigs Eval body
161         (lam_ty, var')   = annotateLamIdBndr body_ty var
162     in
163     (deferType lam_ty, Lam var' body')
164
165 dmdAnal sigs dmd (Case scrut case_bndr [alt@(DataAlt dc,bndrs,rhs)])
166   | let tycon = dataConTyCon dc,
167     isProductTyCon tycon,
168     not (isRecursiveTyCon tycon)
169   = let
170         bndr_ids                = filter isId bndrs
171         (alt_ty, alt')          = dmdAnalAlt sigs dmd alt
172         (alt_ty1, case_bndr')   = annotateBndr alt_ty case_bndr
173         (_, bndrs', _)          = alt'
174         scrut_dmd               = Seq Drop Now [idNewDemandInfo b | b <- bndrs', isId b]
175         (scrut_ty, scrut')      = dmdAnal sigs scrut_dmd scrut
176     in
177     (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' [alt'])
178
179 dmdAnal sigs dmd (Case scrut case_bndr alts)
180   = let
181         (alt_tys, alts')        = mapAndUnzip (dmdAnalAlt sigs dmd) alts
182         (scrut_ty, scrut')      = dmdAnal sigs Eval scrut
183         (alt_ty, case_bndr')    = annotateBndr (foldr1 lubType alt_tys) case_bndr
184     in
185 --    pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
186     (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' alts')
187
188 dmdAnal sigs dmd (Let (NonRec id rhs) body) 
189   = let
190         (sigs', lazy_fv, (id1, rhs')) = downRhs NotTopLevel sigs (id, rhs)
191         (body_ty, body')              = dmdAnal sigs' dmd body
192         (body_ty1, id2)               = annotateBndr body_ty id1
193         body_ty2                      = addLazyFVs body_ty1 lazy_fv
194     in
195 --    pprTrace "dmdLet" (ppr id <+> ppr (sig,rhs_env))
196     (body_ty2, Let (NonRec id2 rhs') body')    
197
198 dmdAnal sigs dmd (Let (Rec pairs) body) 
199   = let
200         bndrs                    = map fst pairs
201         (sigs', lazy_fv, pairs') = dmdFix NotTopLevel sigs pairs
202         (body_ty, body')         = dmdAnal sigs' dmd body
203         body_ty1                 = addLazyFVs body_ty lazy_fv
204     in
205     sigs' `seq` body_ty `seq`
206     let
207         (body_ty2, _) = annotateBndrs body_ty1 bndrs
208                 -- Don't bother to add demand info to recursive
209                 -- binders as annotateBndr does; 
210                 -- being recursive, we can't treat them strictly.
211                 -- But we do need to remove the binders from the result demand env
212     in
213     (body_ty2,  Let (Rec pairs') body')
214
215
216 dmdAnalAlt sigs dmd (con,bndrs,rhs) 
217   = let 
218         (rhs_ty, rhs')   = dmdAnal sigs dmd rhs
219         (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs
220     in
221     (alt_ty, (con, bndrs', rhs'))
222 \end{code}
223
224 %************************************************************************
225 %*                                                                      *
226 \subsection{Bindings}
227 %*                                                                      *
228 %************************************************************************
229
230 \begin{code}
231 dmdFix :: TopLevelFlag
232        -> SigEnv                -- Does not include bindings for this binding
233        -> [(Id,CoreExpr)]
234        -> (SigEnv, DmdEnv,
235            [(Id,CoreExpr)])     -- Binders annotated with stricness info
236
237 dmdFix top_lvl sigs pairs
238   = loop 1 initial_sigs pairs
239   where
240     bndrs        = map fst pairs
241     initial_sigs = extendSigEnvList sigs [(id, (initial_sig id, top_lvl)) | id <- bndrs]
242     
243     loop :: Int
244          -> SigEnv                      -- Already contains the current sigs
245          -> [(Id,CoreExpr)]             
246          -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
247     loop n sigs pairs
248       | all (same_sig sigs sigs') bndrs = (sigs', lazy_fv, pairs')
249                 -- Note: use pairs', not pairs.   pairs' is the result of 
250                 -- processing the RHSs with sigs (= sigs'), whereas pairs 
251                 -- is the result of processing the RHSs with the *previous* 
252                 -- iteration of sigs.
253       | n >= 5              = pprTrace "dmdFix" (ppr n <+> ppr pairs)   (loop (n+1) sigs' pairs')
254       | otherwise           = {- pprTrace "dmdFixLoop" (ppr id_sigs) -} (loop (n+1) sigs' pairs')
255       where
256                 -- Use the new signature to do the next pair
257                 -- The occurrence analyser has arranged them in a good order
258                 -- so this can significantly reduce the number of iterations needed
259         ((sigs',lazy_fv), pairs') = mapAccumL (my_downRhs top_lvl) (sigs, emptyDmdEnv) pairs
260         
261     my_downRhs top_lvl (sigs,lazy_fv) (id,rhs)
262         = -- pprTrace "downRhs {" (ppr id <+> (ppr old_sig))
263           -- (new_sig `seq` 
264           --    pprTrace "downRhsEnd" (ppr id <+> ppr new_sig <+> char '}' ) 
265           ((sigs', lazy_fv'), pair')
266           --     )
267         where
268           (sigs', lazy_fv1, pair') = downRhs top_lvl sigs (id,rhs)
269           lazy_fv'                 = plusUFM_C both lazy_fv lazy_fv1   
270           old_sig                  = lookup sigs id
271           new_sig                  = lookup sigs' id
272            
273         -- Get an initial strictness signature from the Id
274         -- itself.  That way we make use of earlier iterations
275         -- of the fixpoint algorithm.  (Cunning plan.)
276         -- Note that the cunning plan extends to the DmdEnv too,
277         -- since it is part of the strictness signature
278     initial_sig id = idNewStrictness_maybe id `orElse` botSig
279
280     same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
281     lookup sigs var = case lookupVarEnv sigs var of
282                         Just (sig,_) -> sig
283
284 downRhs :: TopLevelFlag 
285         -> SigEnv -> (Id, CoreExpr)
286         -> (SigEnv,  DmdEnv, (Id, CoreExpr))
287 -- Process the RHS of the binding, add the strictness signature
288 -- to the Id, and augment the environment with the signature as well.
289
290 downRhs top_lvl sigs (id, rhs)
291  = (sigs', lazy_fv, (id', rhs'))
292  where
293   arity             = exprArity rhs   -- The idArity may not be up to date
294   (rhs_ty, rhs')    = dmdAnal sigs (vanillaCall arity) rhs
295   (lazy_fv, sig_ty) = mkSigTy rhs rhs_ty
296   sig               = mkStrictSig id arity sig_ty
297   id'               = id `setIdNewStrictness` sig
298   sigs'             = extendSigEnv top_lvl sigs id sig
299
300 mkSigTy rhs (DmdType fv dmds res) 
301   = (lazy_fv, DmdType strict_fv lazified_dmds res')
302   where
303     lazy_fv   = filterUFM (not . isStrictDmd) fv
304     strict_fv = filterUFM isStrictDmd         fv
305         -- We put the strict FVs in the DmdType of the Id, so 
306         -- that at its call sites we unleash demands on its strict fvs.
307         -- An example is 'roll' in imaginary/wheel-sieve2
308         -- Something like this:
309         --      roll x = letrec 
310         --                   go y = if ... then roll (x-1) else x+1
311         --               in 
312         --               go ms
313         -- We want to see that roll is strict in x, which is because
314         -- go is called.   So we put the DmdEnv for x in go's DmdType.
315         --
316         -- Another example:
317         --      f :: Int -> Int -> Int
318         --      f x y = let t = x+1
319         --          h z = if z==0 then t else 
320         --                if z==1 then x+1 else
321         --                x + h (z-1)
322         --      in
323         --      h y
324         -- Calling h does indeed evaluate x, but we can only see
325         -- that if we unleash a demand on x at the call site for t.
326         --
327         -- Incidentally, here's a place where lambda-lifting h would
328         -- lose the cigar --- we couldn't see the joint strictness in t/x
329         --
330         --      ON THE OTHER HAND
331         -- We don't want to put *all* the fv's from the RHS into the
332         -- DmdType, because that makes fixpointing very slow --- the 
333         -- DmdType gets full of lazy demands that are slow to converge.
334
335     lazified_dmds = map lazify dmds
336         -- Get rid of defers in the arguments
337
338     res' = case (dmds, res) of
339                 ([], RetCPR) | not (exprIsValue rhs) -> TopRes
340                 other                                -> res
341         -- If the rhs is a thunk, we forget the CPR info, because
342         -- it is presumably shared (else it would have been inlined, and 
343         -- so we'd lose sharing if w/w'd it into a function.
344         --
345         --      DONE IN OLD CPR ANALYSER, BUT NOT YET HERE
346         -- Also, if the strictness analyser has figured out that it's strict,
347         -- the let-to-case transformation will happen, so again it's good.
348         -- (CPR analysis runs before the simplifier has had a chance to do
349         --  the let-to-case transform.)
350         -- This made a big difference to PrelBase.modInt, which had something like
351         --      modInt = \ x -> let r = ... -> I# v in
352         --                      ...body strict in r...
353         -- r's RHS isn't a value yet; but modInt returns r in various branches, so
354         -- if r doesn't have the CPR property then neither does modInt
355 \end{code}
356
357
358 %************************************************************************
359 %*                                                                      *
360 \subsection{Strictness signatures and types}
361 %*                                                                      *
362 %************************************************************************
363
364 \begin{code}
365 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
366
367 addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd
368   | isTopLevel top_lvl = dmd_ty         -- Don't record top level things
369   | otherwise          = DmdType (extendVarEnv fv var dmd) ds res
370
371 addLazyFVs (DmdType fv ds res) lazy_fvs
372   = DmdType (plusUFM_C both fv lazy_fvs) ds res
373
374 annotateBndr :: DmdType -> Var -> (DmdType, Var)
375 -- The returned env has the var deleted
376 -- The returned var is annotated with demand info
377 -- No effect on the argument demands
378 annotateBndr dmd_ty@(DmdType fv ds res) var
379   | isTyVar var = (dmd_ty, var)
380   | otherwise   = (DmdType fv' ds res, setIdNewDemandInfo var dmd)
381   where
382     (fv', dmd) = removeFV fv var res
383
384 annotateBndrs = mapAccumR annotateBndr
385
386 annotateLamIdBndr dmd_ty@(DmdType fv ds res) id
387 -- For lambdas we add the demand to the argument demands
388 -- Only called for Ids
389   = ASSERT( isId id )
390     (DmdType fv' (dmd:ds) res, setIdNewDemandInfo id dmd)
391   where
392     (fv', dmd) = removeFV fv id res
393
394 removeFV fv var res = (fv', dmd)
395                 where
396                   fv' = fv `delVarEnv` var
397                   dmd = lookupVarEnv fv var `orElse` deflt
398                   deflt | isBotRes res = Bot
399                         | otherwise    = Abs
400 \end{code}
401
402 %************************************************************************
403 %*                                                                      *
404 \subsection{Demand types}
405 %*                                                                      *
406 %************************************************************************
407
408 \begin{code}
409 splitDmdTy :: DmdType -> (Demand, DmdType)
410 -- Split off one function argument
411 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
412 splitDmdTy ty@(DmdType fv [] TopRes)         = (topDmd, ty)
413 splitDmdTy ty@(DmdType fv [] BotRes)         = (Abs,    ty)
414         -- We already have a suitable demand on all
415         -- free vars, so no need to add more!
416 splitDmdTy (DmdType fv [] RetCPR)         = panic "splitDmdTy"
417
418 -------------------------
419 dmdTypeRes :: DmdType -> DmdResult
420 dmdTypeRes (DmdType _ _ res_ty) = res_ty
421 \end{code}
422
423
424 %************************************************************************
425 %*                                                                      *
426 \subsection{Strictness signatures}
427 %*                                                                      *
428 %************************************************************************
429
430 \begin{code}
431 type SigEnv  = VarEnv (StrictSig, TopLevelFlag)
432         -- We use the SigEnv to tell us whether to
433         -- record info about a variable in the DmdEnv
434         -- We do so if it's a LocalId, but not top-level
435         --
436         -- The DmdEnv gives the demand on the free vars of the function
437         -- when it is given enough args to satisfy the strictness signature
438
439 emptySigEnv  = emptyVarEnv
440
441 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
442 extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl)
443
444 extendSigEnvList = extendVarEnvList
445
446 dmdTransform :: SigEnv          -- The strictness environment
447              -> Id              -- The function
448              -> Demand          -- The demand on the function
449              -> DmdType         -- The demand type of the function in this context
450         -- Returned DmdEnv includes the demand on 
451         -- this function plus demand on its free variables
452
453 dmdTransform sigs var dmd
454
455 ------  DATA CONSTRUCTOR
456   | isDataConId var,            -- Data constructor
457     Seq k Now ds <- res_dmd,    -- and the demand looks inside its fields
458     let StrictSig arity dmd_ty = idNewStrictness var    -- It must have a strictness sig
459   = if arity == length ds then  -- Saturated, so unleash the demand
460         -- ds can be empty, when we are just seq'ing the thing
461         mkDmdType emptyDmdEnv ds (dmdTypeRes dmd_ty)
462                 -- Need to extract whether it's a product
463     else
464         topDmdType
465
466 ------  IMPORTED FUNCTION
467   | isGlobalId var,             -- Imported function
468     let StrictSig arity dmd_ty = getNewStrictness var
469   = if arity <= depth then      -- Saturated, so unleash the demand
470         dmd_ty
471     else
472         topDmdType
473
474 ------  LOCAL LET/REC BOUND THING
475   | Just (StrictSig arity dmd_ty, top_lvl) <- lookupVarEnv sigs var
476   = let
477         fn_ty | arity <= depth = dmd_ty 
478               | otherwise      = deferType dmd_ty
479         -- NB: it's important to use deferType, and not just return topDmdType
480         -- Consider     let { f x y = p + x } in f 1
481         -- The application isn't saturated, but we must nevertheless propagate 
482         --      a lazy demand for p!  
483     in
484     addVarDmd top_lvl fn_ty var dmd
485
486 ------  LOCAL NON-LET/REC BOUND THING
487   | otherwise                   -- Default case
488   = unitVarDmd var dmd
489
490   where
491     (depth, res_dmd) = splitCallDmd dmd
492 \end{code}
493
494 \begin{code}
495 squashDmdEnv (StrictSig a (DmdType fv ds res)) = StrictSig a (DmdType emptyDmdEnv ds res)
496
497 betterStrict :: StrictSig -> StrictSig -> Bool
498 betterStrict (StrictSig ar1 t1) (StrictSig ar2 t2)
499   = (ar1 >= ar2) && (t1 `betterDmdType` t2)
500
501 betterDmdType t1 t2 = (t1 `lubType` t2) == t2
502 \end{code}
503
504
505 %************************************************************************
506 %*                                                                      *
507 \subsection{Demands}
508 %*                                                                      *
509 %************************************************************************
510
511 \begin{code}
512 splitCallDmd :: Demand -> (Int, Demand)
513 splitCallDmd (Call d) = case splitCallDmd d of
514                           (n, r) -> (n+1, r)
515 splitCallDmd d        = (0, d)
516
517 vanillaCall :: Arity -> Demand
518 vanillaCall 0 = Eval
519 vanillaCall n = Call (vanillaCall (n-1))
520
521 deferType :: DmdType -> DmdType
522 deferType (DmdType fv _ _) = DmdType (mapVarEnv defer fv) [] TopRes
523         -- Notice that we throw away info about both arguments and results
524         -- For example,   f = let ... in \x -> x
525         -- We don't want to get a stricness type V->T for f.
526
527 defer :: Demand -> Demand
528 -- c.f. `lub` Abs
529 defer Abs          = Abs
530 defer (Seq k _ ds) = Seq k Defer ds
531 defer other        = Lazy
532
533 isStrictDmd :: Demand -> Bool
534 isStrictDmd Bot           = True
535 isStrictDmd Err           = True           
536 isStrictDmd (Seq _ Now _) = True
537 isStrictDmd Eval          = True
538 isStrictDmd (Call _)      = True
539 isStrictDmd other         = False
540
541 lazify :: Demand -> Demand
542 -- The 'Defer' demands are just Lazy at function boundaries
543 lazify (Seq k Defer ds) = Lazy
544 lazify (Seq k Now   ds) = Seq k Now (map lazify ds)
545 lazify Bot              = Abs   -- Don't pass args that are consumed by bottom
546 lazify d                = d
547
548 betterDemand :: Demand -> Demand -> Bool
549 -- If d1 `better` d2, and d2 `better` d2, then d1==d2
550 betterDemand d1 d2 = (d1 `lub` d2) == d2
551 \end{code}
552
553
554 %************************************************************************
555 %*                                                                      *
556 \subsection{LUB and BOTH}
557 %*                                                                      *
558 %************************************************************************
559
560 \begin{code}
561 lub :: Demand -> Demand -> Demand
562
563 lub Bot  d = d
564
565 lub Lazy d = Lazy
566
567 lub Err Bot = Err 
568 lub Err d   = d 
569
570 lub Abs Bot          = Abs
571 lub Abs Err          = Abs
572 lub Abs Abs          = Abs    
573 lub Abs (Seq k _ ds) = Seq k Defer ds   -- Very important ('radicals' example)
574 lub Abs d            = Lazy
575
576 lub Eval Abs            = Lazy
577 lub Eval Lazy           = Lazy
578 lub Eval (Seq k Now ds) = Seq Keep Now ds
579 lub Eval d              = Eval
580
581 lub (Call d1) (Call d2) = Call (lub d1 d2)
582
583 lub (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) (l1 `or_defer` l2)
584                                           (zipWithEqual "lub" lub ds1 ds2)
585
586 -- The last clauses deal with the remaining cases for Call and Seq
587 lub d1@(Call _) d2@(Seq _ _ _) = pprPanic "lub" (ppr d1 $$ ppr d2)
588 lub d1 d2                      = lub d2 d1
589
590 or_defer Now Now = Now
591 or_defer _   _   = Defer
592
593 -------------------------
594 -- Consider (if x then y else []) with demand V
595 -- Then the first branch gives {y->V} and the second
596 -- *implicitly* has {y->A}.  So we must put {y->(V `lub` A)}
597 -- in the result env.
598 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
599   = DmdType lub_fv2 (zipWith lub ds1 ds2) (r1 `lubRes` r2)
600   where
601     lub_fv  = plusUFM_C lub fv1 fv2
602     lub_fv1 = modifyEnv (not (isBotRes r1)) (Abs `lub`) fv2 fv1 lub_fv
603     lub_fv2 = modifyEnv (not (isBotRes r2)) (Abs `lub`) fv1 fv2 lub_fv1
604         -- lub is the identity for Bot
605
606 -------------------------
607 lubRes BotRes r      = r
608 lubRes r      BotRes = r
609 lubRes RetCPR RetCPR = RetCPR
610 lubRes r1     r2     = TopRes
611
612 -----------------------------------
613 vee :: Keepity -> Keepity -> Keepity
614 vee Drop Drop = Drop
615 vee k1   k2   = Keep
616
617 -----------------------------------
618 both :: Demand -> Demand -> Demand
619
620 -- The normal one
621 -- both Bot d = Bot
622
623 -- The experimental one
624 both Bot Bot = Bot
625 both Bot Abs = Bot
626 both Bot d   = d
627
628
629 both Abs Bot = Bot
630 both Abs d   = d
631
632 both Err Bot = Bot
633 both Err Abs = Err
634 both Err d   = d
635
636 both Lazy Bot            = Bot
637 both Lazy Abs            = Lazy
638 both Lazy Err            = Lazy 
639 both Lazy (Seq k Now ds) = Seq Keep Now ds
640 both Lazy d              = d
641
642 -- Part of the Bot like Err experiment
643 -- both Eval Bot               = Bot
644 both Eval (Seq k l ds) = Seq Keep Now ds
645 both Eval (Call d)     = Call d
646 both Eval d            = Eval
647
648 both (Seq k1 Defer ds1) (Seq k2 Defer ds2) = Seq (k1 `vee` k2) Defer
649                                                  (zipWithEqual "both" both ds1 ds2)
650 both (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) Now
651                                            (zipWithEqual "both" both ds1' ds2')
652                                      where
653                                         ds1' = case l1 of { Now -> ds1; Defer -> map defer ds1 }
654                                         ds2' = case l2 of { Now -> ds2; Defer -> map defer ds2 }
655
656 both (Call d1) (Call d2) = Call (d1 `both` d2)
657
658 -- The last clauses deal with the remaining cases for Call and Seq
659 both d1@(Call _) d2@(Seq _ _ _) = pprPanic "both" (ppr d1 $$ ppr d2)
660 both d1 d2                      = both d2 d1
661
662 -----------------------------------
663 bothRes :: DmdResult -> DmdResult -> DmdResult
664 -- Left-biased for CPR info
665 bothRes BotRes _ = BotRes
666 bothRes _ BotRes = BotRes
667 bothRes r1 _     = r1
668
669 -----------------------------------
670 -- (t1 `bothType` t2) takes the argument/result info from t1,
671 -- using t2 just for its free-var info
672 bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
673   = DmdType both_fv2 ds1 r1
674   where
675     both_fv  = plusUFM_C both fv1 fv2
676     both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
677     both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
678         -- both is the identity for Abs
679 \end{code}
680
681 \begin{code}
682 modifyEnv :: Bool                       -- No-op if False
683           -> (Demand -> Demand)         -- The zapper
684           -> DmdEnv -> DmdEnv           -- Env1 and Env2
685           -> DmdEnv -> DmdEnv           -- Transform this env
686         -- Zap anything in Env1 but not in Env2
687         -- Assume: dom(env) includes dom(Env1) and dom(Env2)
688
689 modifyEnv need_to_modify zapper env1 env2 env
690   | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2))
691   | otherwise      = env
692   where
693     zap uniq env = addToUFM_Directly env uniq (zapper current_val)
694                  where
695                    current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
696 \end{code}
697
698
699 %************************************************************************
700 %*                                                                      *
701 \subsection{Miscellaneous
702 %*                                                                      *
703 %************************************************************************
704
705
706 \begin{code}
707 -- Move these to Id.lhs
708 idNewStrictness_maybe :: Id -> Maybe StrictSig
709 idNewStrictness :: Id -> StrictSig
710
711 idNewStrictness_maybe id = newStrictnessInfo (idInfo id)
712 idNewStrictness       id = idNewStrictness_maybe id `orElse` topSig
713
714 getNewStrictness :: Id -> StrictSig
715 -- First tries the "new-strictness" field, and then
716 -- reverts to the old one. This is just until we have
717 -- cross-module info for new strictness
718 getNewStrictness id = idNewStrictness_maybe id `orElse` newStrictnessFromOld id
719                       
720 newStrictnessFromOld :: Id -> StrictSig
721 newStrictnessFromOld id = mkNewStrictnessInfo id (idArity id) (idStrictness id) (idCprInfo id)
722
723 setIdNewStrictness :: Id -> StrictSig -> Id
724 setIdNewStrictness id sig = modifyIdInfo (`setNewStrictnessInfo` sig) id
725
726 idNewDemandInfo :: Id -> Demand
727 idNewDemandInfo id = newDemandInfo (idInfo id)
728
729 setIdNewDemandInfo :: Id -> Demand -> Id
730 setIdNewDemandInfo id dmd = modifyIdInfo (`setNewDemandInfo` dmd) id
731 \end{code}
732
733 \begin{code}
734 get_changes binds = vcat (map get_changes_bind binds)
735
736 get_changes_bind (Rec pairs) = vcat (map get_changes_pr pairs)
737 get_changes_bind (NonRec id rhs) = get_changes_pr (id,rhs)
738
739 get_changes_pr (id,rhs) 
740   | isImplicitId id = empty  -- We don't look inside these
741   | otherwise       = get_changes_var id $$ get_changes_expr rhs
742
743 get_changes_var var
744   | isId var  = get_changes_str var $$ get_changes_dmd var
745   | otherwise = empty
746
747 get_changes_expr (Type t)     = empty
748 get_changes_expr (Var v)      = empty
749 get_changes_expr (Lit l)      = empty
750 get_changes_expr (Note n e)   = get_changes_expr e
751 get_changes_expr (App e1 e2)  = get_changes_expr e1 $$ get_changes_expr e2
752 get_changes_expr (Lam b e)    = {- get_changes_var b $$ -} get_changes_expr e
753 get_changes_expr (Let b e)    = get_changes_bind b $$ get_changes_expr e
754 get_changes_expr (Case e b a) = get_changes_expr e $$ get_changes_var b $$ vcat (map get_changes_alt a)
755
756 get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs
757
758 get_changes_str id
759   | new_better && old_better = empty
760   | new_better               = message "BETTER"
761   | old_better               = message "WORSE"
762   | otherwise                = message "INCOMPARABLE" 
763   where
764     message word = text word <+> text "strictness for" <+> ppr id <+> info
765     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
766     new = squashDmdEnv (idNewStrictness id)     -- Don't report diffs in the env
767     old = newStrictnessFromOld id
768     old_better = old `betterStrict` new
769     new_better = new `betterStrict` old
770
771 get_changes_dmd id
772   | isUnLiftedType (idType id) = empty  -- Not useful
773   | new_better && old_better = empty
774   | new_better               = message "BETTER"
775   | old_better               = message "WORSE"
776   | otherwise                = message "INCOMPARABLE" 
777   where
778     message word = text word <+> text "demand for" <+> ppr id <+> info
779     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
780     new = lazify (idNewDemandInfo id)   -- Lazify to avoid spurious improvements
781     old = newDemand (idDemandInfo id)
782     new_better = new `betterDemand` old 
783     old_better = old `betterDemand` new
784 #endif  /* DEBUG */
785 \end{code}