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