[project @ 2001-07-31 10:06:25 by sewardj]
[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(..), opt_MaxWorkerArgs )
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, idCprInfo, idDemandInfo,
21                           modifyIdInfo, isDataConId, isImplicitId, isGlobalId,
22                           idNewStrictness, idNewStrictness_maybe, getNewStrictness, setIdNewStrictness,
23                           idNewDemandInfo, setIdNewDemandInfo, newStrictnessFromOld )
24 import IdInfo           ( newDemand )
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 To think about
40
41 * set a noinline pragma on bottoming Ids
42
43 * Consider f x = x+1 `fatbar` error (show x)
44   We'd like to unbox x, even if that means reboxing it in the error case.
45
46 \begin{code}
47 instance Outputable TopLevelFlag where
48   ppr flag = empty
49 \end{code}
50
51 %************************************************************************
52 %*                                                                      *
53 \subsection{Top level stuff}
54 %*                                                                      *
55 %************************************************************************
56
57 \begin{code}
58 dmdAnalPgm :: DynFlags -> [CoreBind] -> IO [CoreBind]
59 dmdAnalPgm dflags binds
60   = panic "dmdAnalPgm called"
61 dmdAnalPgm dflags binds
62   = do {
63         showPass dflags "Demand analysis" ;
64         let { binds_plus_dmds = do_prog binds ;
65               dmd_changes = get_changes binds_plus_dmds } ;
66         endPass dflags "Demand analysis" 
67                 Opt_D_dump_stranal binds_plus_dmds ;
68 #ifdef DEBUG
69         -- Only if DEBUG is on, because only then is the old strictness analyser run
70         printDump (text "Changes in demands" $$ dmd_changes) ;
71 #endif
72         return binds_plus_dmds
73     }
74   where
75     do_prog :: [CoreBind] -> [CoreBind]
76     do_prog binds = snd $ mapAccumL dmdAnalTopBind emptySigEnv binds
77
78 dmdAnalTopBind :: SigEnv
79                -> CoreBind 
80                -> (SigEnv, CoreBind)
81 dmdAnalTopBind sigs (NonRec id rhs)
82   | isImplicitId id             -- Don't touch the info on constructors, selectors etc
83   = (sigs, NonRec id rhs)       -- It's pre-computed in MkId.lhs
84   | otherwise
85   = let
86         (sigs', _, (id', rhs')) = downRhs TopLevel sigs (id, rhs)
87     in
88     (sigs', NonRec id' rhs')    
89
90 dmdAnalTopBind sigs (Rec pairs)
91   = let
92         (sigs', _, pairs')  = dmdFix TopLevel sigs pairs
93     in
94     (sigs', Rec pairs')
95 \end{code}
96
97
98 %************************************************************************
99 %*                                                                      *
100 \subsection{The analyser itself}        
101 %*                                                                      *
102 %************************************************************************
103
104 \begin{code}
105 dmdAnal :: SigEnv -> Demand -> CoreExpr -> (DmdType, CoreExpr)
106
107 dmdAnal sigs Abs  e = (topDmdType, e)
108
109 dmdAnal sigs Lazy e = let 
110                         (res_ty, e') = dmdAnal sigs Eval e
111                       in
112                       (deferType res_ty, e')
113         -- It's important not to analyse e with a lazy demand because
114         -- a) When we encounter   case s of (a,b) -> 
115         --      we demand s with U(d1d2)... but if the overall demand is lazy
116         --      that is wrong, and we'd need to reduce the demand on s,
117         --      which is inconvenient
118         -- b) More important, consider
119         --      f (let x = R in x+x), where f is lazy
120         --    We still want to mark x as demanded, because it will be when we
121         --    enter the let.  If we analyse f's arg with a Lazy demand, we'll
122         --    just mark x as Lazy
123
124
125 dmdAnal sigs dmd (Lit lit)
126   = (topDmdType, Lit lit)
127
128 dmdAnal sigs dmd (Var var)
129   = (dmdTransform sigs var dmd, Var var)
130
131 dmdAnal sigs dmd (Note n e)
132   = (dmd_ty, Note n e')
133   where
134     (dmd_ty, e') = dmdAnal sigs dmd' e  
135     dmd' = case n of
136              Coerce _ _ -> Eval   -- This coerce usually arises from a recursive
137              other      -> dmd    -- newtype, and we don't want to look inside them
138                                   -- for exactly the same reason that we don't look
139                                   -- inside recursive products -- we might not reach
140                                   -- a fixpoint.  So revert to a vanilla Eval demand
141
142 dmdAnal sigs dmd (App fun (Type ty))
143   = (fun_ty, App fun' (Type ty))
144   where
145     (fun_ty, fun') = dmdAnal sigs dmd fun
146
147 dmdAnal sigs dmd (App fun arg)  -- Non-type arguments
148   = let                         -- [Type arg handled above]
149         (fun_ty, fun')    = dmdAnal sigs (Call dmd) fun
150         (arg_ty, arg')    = dmdAnal sigs arg_dmd arg
151         (arg_dmd, res_ty) = splitDmdTy fun_ty
152     in
153     (res_ty `bothType` arg_ty, App fun' arg')
154
155 dmdAnal sigs dmd (Lam var body)
156   | isTyVar var
157   = let   
158         (body_ty, body') = dmdAnal sigs dmd body
159     in
160     (body_ty, Lam var body')
161
162   | Call body_dmd <- dmd        -- A call demand: good!
163   = let 
164         (body_ty, body') = dmdAnal sigs body_dmd body
165         (lam_ty, var')   = annotateLamIdBndr body_ty var
166     in
167     (lam_ty, Lam var' body')
168
169   | otherwise   -- Not enough demand on the lambda; but do the body
170   = let         -- anyway to annotate it and gather free var info
171         (body_ty, body') = dmdAnal sigs Eval body
172         (lam_ty, var')   = annotateLamIdBndr body_ty var
173     in
174     (deferType lam_ty, Lam var' body')
175
176 dmdAnal sigs dmd (Case scrut case_bndr [alt@(DataAlt dc,bndrs,rhs)])
177   | let tycon = dataConTyCon dc,
178     isProductTyCon tycon,
179     not (isRecursiveTyCon tycon)
180   = let
181         bndr_ids                 = filter isId bndrs
182         (alt_ty, alt')           = dmdAnalAlt sigs dmd alt
183         (alt_ty1, case_bndr')    = annotateBndr alt_ty case_bndr
184         (_, bndrs', _)           = alt'
185
186         -- Figure out whether the case binder is used, and use
187         -- that to set the keepity of the demand.  This is utterly essential.
188         -- Consider     f x = case x of y { (a,b) -> k y a }
189         -- If we just take scrut_demand = U(L,A), then we won't pass x to the
190         -- worker, so the worker will rebuild 
191         --      x = (a, absent-error)
192         -- and that'll crash.
193         dead_case_bndr           = isAbsentDmd (idNewDemandInfo case_bndr')
194         keepity | dead_case_bndr = Drop
195                 | otherwise      = Keep         
196
197         scrut_dmd                = Seq keepity Now [idNewDemandInfo b | b <- bndrs', isId b]
198         (scrut_ty, scrut')       = dmdAnal sigs scrut_dmd scrut
199     in
200     (alt_ty1 `bothType` scrut_ty, Case scrut' case_bndr' [alt'])
201
202 dmdAnal sigs dmd (Case scrut case_bndr alts)
203   = let
204         (alt_tys, alts')        = mapAndUnzip (dmdAnalAlt sigs dmd) alts
205         (scrut_ty, scrut')      = dmdAnal sigs Eval scrut
206         (alt_ty, case_bndr')    = annotateBndr (foldr1 lubType alt_tys) case_bndr
207     in
208 --    pprTrace "dmdAnal:Case" (ppr alts $$ ppr alt_tys)
209     (alt_ty `bothType` scrut_ty, Case scrut' case_bndr' alts')
210
211 dmdAnal sigs dmd (Let (NonRec id rhs) body) 
212   = let
213         (sigs', lazy_fv, (id1, rhs')) = downRhs NotTopLevel sigs (id, rhs)
214         (body_ty, body')              = dmdAnal sigs' dmd body
215         (body_ty1, id2)               = annotateBndr body_ty id1
216         body_ty2                      = addLazyFVs body_ty1 lazy_fv
217     in
218 --    pprTrace "dmdLet" (ppr id <+> ppr (sig,rhs_env))
219     (body_ty2, Let (NonRec id2 rhs') body')    
220
221 dmdAnal sigs dmd (Let (Rec pairs) body) 
222   = let
223         bndrs                    = map fst pairs
224         (sigs', lazy_fv, pairs') = dmdFix NotTopLevel sigs pairs
225         (body_ty, body')         = dmdAnal sigs' dmd body
226         body_ty1                 = addLazyFVs body_ty lazy_fv
227     in
228     sigs' `seq` body_ty `seq`
229     let
230         (body_ty2, _) = annotateBndrs body_ty1 bndrs
231                 -- Don't bother to add demand info to recursive
232                 -- binders as annotateBndr does; 
233                 -- being recursive, we can't treat them strictly.
234                 -- But we do need to remove the binders from the result demand env
235     in
236     (body_ty2,  Let (Rec pairs') body')
237
238
239 dmdAnalAlt sigs dmd (con,bndrs,rhs) 
240   = let 
241         (rhs_ty, rhs')   = dmdAnal sigs dmd rhs
242         (alt_ty, bndrs') = annotateBndrs rhs_ty bndrs
243     in
244     (alt_ty, (con, bndrs', rhs'))
245 \end{code}
246
247 %************************************************************************
248 %*                                                                      *
249 \subsection{Bindings}
250 %*                                                                      *
251 %************************************************************************
252
253 \begin{code}
254 dmdFix :: TopLevelFlag
255        -> SigEnv                -- Does not include bindings for this binding
256        -> [(Id,CoreExpr)]
257        -> (SigEnv, DmdEnv,
258            [(Id,CoreExpr)])     -- Binders annotated with stricness info
259
260 dmdFix top_lvl sigs pairs
261   = loop 1 initial_sigs pairs
262   where
263     bndrs        = map fst pairs
264     initial_sigs = extendSigEnvList sigs [(id, (initial_sig id, top_lvl)) | id <- bndrs]
265     
266     loop :: Int
267          -> SigEnv                      -- Already contains the current sigs
268          -> [(Id,CoreExpr)]             
269          -> (SigEnv, DmdEnv, [(Id,CoreExpr)])
270     loop n sigs pairs
271       | all (same_sig sigs sigs') bndrs = (sigs', lazy_fv, pairs')
272                 -- Note: use pairs', not pairs.   pairs' is the result of 
273                 -- processing the RHSs with sigs (= sigs'), whereas pairs 
274                 -- is the result of processing the RHSs with the *previous* 
275                 -- iteration of sigs.
276       | n >= 5              = pprTrace "dmdFix" (ppr n <+> (vcat 
277                                 [ text "Sigs:" <+> ppr [(id,lookup sigs id, lookup sigs' id) | (id,_) <- pairs],
278                                   text "env:" <+> ppr (ufmToList sigs),
279                                   text "binds:" <+> ppr pairs]))
280                               (loop (n+1) sigs' pairs')
281       | otherwise           = {- pprTrace "dmdFixLoop" (ppr id_sigs) -} (loop (n+1) sigs' pairs')
282       where
283                 -- Use the new signature to do the next pair
284                 -- The occurrence analyser has arranged them in a good order
285                 -- so this can significantly reduce the number of iterations needed
286         ((sigs',lazy_fv), pairs') = mapAccumL (my_downRhs top_lvl) (sigs, emptyDmdEnv) pairs
287         
288     my_downRhs top_lvl (sigs,lazy_fv) (id,rhs)
289         = -- pprTrace "downRhs {" (ppr id <+> (ppr old_sig))
290           -- (new_sig `seq` 
291           --    pprTrace "downRhsEnd" (ppr id <+> ppr new_sig <+> char '}' ) 
292           ((sigs', lazy_fv'), pair')
293           --     )
294         where
295           (sigs', lazy_fv1, pair') = downRhs top_lvl sigs (id,rhs)
296           lazy_fv'                 = plusUFM_C both lazy_fv lazy_fv1   
297           old_sig                  = lookup sigs id
298           new_sig                  = lookup sigs' id
299            
300         -- Get an initial strictness signature from the Id
301         -- itself.  That way we make use of earlier iterations
302         -- of the fixpoint algorithm.  (Cunning plan.)
303         -- Note that the cunning plan extends to the DmdEnv too,
304         -- since it is part of the strictness signature
305     initial_sig id = idNewStrictness_maybe id `orElse` botSig
306
307     same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
308     lookup sigs var = case lookupVarEnv sigs var of
309                         Just (sig,_) -> sig
310
311 downRhs :: TopLevelFlag 
312         -> SigEnv -> (Id, CoreExpr)
313         -> (SigEnv,  DmdEnv, (Id, CoreExpr))
314 -- Process the RHS of the binding, add the strictness signature
315 -- to the Id, and augment the environment with the signature as well.
316
317 downRhs top_lvl sigs (id, rhs)
318  = (sigs', lazy_fv, (id', rhs'))
319  where
320   arity             = exprArity rhs   -- The idArity may not be up to date
321   (rhs_ty, rhs')    = dmdAnal sigs (vanillaCall arity) rhs
322   (lazy_fv, sig_ty) = mkSigTy id arity rhs rhs_ty
323   id'               = id `setIdNewStrictness` sig_ty
324   sigs'             = extendSigEnv top_lvl sigs id sig_ty
325 \end{code}
326
327 %************************************************************************
328 %*                                                                      *
329 \subsection{Strictness signatures and types}
330 %*                                                                      *
331 %************************************************************************
332
333 \begin{code}
334 mkSigTy :: Id -> Arity -> CoreExpr -> DmdType -> (DmdEnv, StrictSig)
335 -- Take a DmdType and turn it into a StrictSig
336 mkSigTy id arity rhs (DmdType fv dmds res) 
337   = (lazy_fv, mkStrictSig id arity dmd_ty)
338   where
339     dmd_ty = DmdType strict_fv lazified_dmds res'
340
341     lazy_fv   = filterUFM (not . isStrictDmd) fv
342     strict_fv = filterUFM isStrictDmd         fv
343         -- We put the strict FVs in the DmdType of the Id, so 
344         -- that at its call sites we unleash demands on its strict fvs.
345         -- An example is 'roll' in imaginary/wheel-sieve2
346         -- Something like this:
347         --      roll x = letrec 
348         --                   go y = if ... then roll (x-1) else x+1
349         --               in 
350         --               go ms
351         -- We want to see that roll is strict in x, which is because
352         -- go is called.   So we put the DmdEnv for x in go's DmdType.
353         --
354         -- Another example:
355         --      f :: Int -> Int -> Int
356         --      f x y = let t = x+1
357         --          h z = if z==0 then t else 
358         --                if z==1 then x+1 else
359         --                x + h (z-1)
360         --      in
361         --      h y
362         -- Calling h does indeed evaluate x, but we can only see
363         -- that if we unleash a demand on x at the call site for t.
364         --
365         -- Incidentally, here's a place where lambda-lifting h would
366         -- lose the cigar --- we couldn't see the joint strictness in t/x
367         --
368         --      ON THE OTHER HAND
369         -- We don't want to put *all* the fv's from the RHS into the
370         -- DmdType, because that makes fixpointing very slow --- the 
371         -- DmdType gets full of lazy demands that are slow to converge.
372
373     lazified_dmds = map lazify dmds
374         -- Get rid of defers in the arguments
375     final_dmds = setUnpackStrategy lazified_dmds
376         -- Set the unpacking strategy
377         
378     res' = case (dmds, res) of
379                 ([], RetCPR) | not (exprIsValue rhs) -> TopRes
380                 other                                -> res
381         -- If the rhs is a thunk, we forget the CPR info, because
382         -- it is presumably shared (else it would have been inlined, and 
383         -- so we'd lose sharing if w/w'd it into a function.
384         --
385         --      DONE IN OLD CPR ANALYSER, BUT NOT YET HERE
386         -- Also, if the strictness analyser has figured out that it's strict,
387         -- the let-to-case transformation will happen, so again it's good.
388         -- (CPR analysis runs before the simplifier has had a chance to do
389         --  the let-to-case transform.)
390         -- This made a big difference to PrelBase.modInt, which had something like
391         --      modInt = \ x -> let r = ... -> I# v in
392         --                      ...body strict in r...
393         -- r's RHS isn't a value yet; but modInt returns r in various branches, so
394         -- if r doesn't have the CPR property then neither does modInt
395 \end{code}
396
397 The unpack strategy determines whether we'll *really* unpack the argument,
398 or whether we'll just remember its strictness.  If unpacking would give
399 rise to a *lot* of worker args, we may decide not to unpack after all.
400
401 \begin{code}
402 setUnpackStrategy :: [Demand] -> [Demand]
403 setUnpackStrategy ds
404   = snd (go (opt_MaxWorkerArgs - nonAbsentArgs ds) ds)
405   where
406     go :: Int                   -- Max number of args available for sub-components of [Demand]
407        -> [Demand]
408        -> (Int, [Demand])       -- Args remaining after subcomponents of [Demand] are unpacked
409
410     go n (Seq keep _ cs : ds) 
411         | n' >= 0    = Seq keep Now cs' `cons` go n'' ds
412         | otherwise  = Eval `cons` go n ds
413         where
414           (n'',cs') = go n' cs
415           n' = n + box - non_abs_args
416           box = case keep of
417                    Keep -> 0
418                    Drop -> 1    -- Add one to the budget if we drop the top-level arg
419           non_abs_args = nonAbsentArgs cs
420                 -- Delete # of non-absent args to which we'll now be committed
421                                 
422     go n (d:ds) = d `cons` go n ds
423     go n []     = (n,[])
424
425     cons d (n,ds) = (n, d:ds)
426
427 nonAbsentArgs :: [Demand] -> Int
428 nonAbsentArgs []         = 0
429 nonAbsentArgs (Abs : ds) = nonAbsentArgs ds
430 nonAbsentArgs (d   : ds) = 1 + nonAbsentArgs ds
431 \end{code}
432
433
434 %************************************************************************
435 %*                                                                      *
436 \subsection{Strictness signatures and types}
437 %*                                                                      *
438 %************************************************************************
439
440 \begin{code}
441 splitDmdTy :: DmdType -> (Demand, DmdType)
442 -- Split off one function argument
443 splitDmdTy (DmdType fv (dmd:dmds) res_ty) = (dmd, DmdType fv dmds res_ty)
444 splitDmdTy ty@(DmdType fv [] TopRes)         = (topDmd, ty)
445 splitDmdTy ty@(DmdType fv [] BotRes)         = (Abs,    ty)
446         -- We already have a suitable demand on all
447         -- free vars, so no need to add more!
448 splitDmdTy (DmdType fv [] RetCPR)         = panic "splitDmdTy"
449 \end{code}
450
451 \begin{code}
452 unitVarDmd var dmd = DmdType (unitVarEnv var dmd) [] TopRes
453
454 addVarDmd top_lvl dmd_ty@(DmdType fv ds res) var dmd
455   | isTopLevel top_lvl = dmd_ty         -- Don't record top level things
456   | otherwise          = DmdType (extendVarEnv fv var dmd) ds res
457
458 addLazyFVs (DmdType fv ds res) lazy_fvs
459   = DmdType (plusUFM_C both fv lazy_fvs) ds res
460
461 annotateBndr :: DmdType -> Var -> (DmdType, Var)
462 -- The returned env has the var deleted
463 -- The returned var is annotated with demand info
464 -- No effect on the argument demands
465 annotateBndr dmd_ty@(DmdType fv ds res) var
466   | isTyVar var = (dmd_ty, var)
467   | otherwise   = (DmdType fv' ds res, setIdNewDemandInfo var dmd)
468   where
469     (fv', dmd) = removeFV fv var res
470
471 annotateBndrs = mapAccumR annotateBndr
472
473 annotateLamIdBndr dmd_ty@(DmdType fv ds res) id
474 -- For lambdas we add the demand to the argument demands
475 -- Only called for Ids
476   = ASSERT( isId id )
477     (DmdType fv' (dmd:ds) res, setIdNewDemandInfo id dmd)
478   where
479     (fv', dmd) = removeFV fv id res
480
481 removeFV fv var res = (fv', dmd)
482                 where
483                   fv' = fv `delVarEnv` var
484                   dmd = lookupVarEnv fv var `orElse` deflt
485                   deflt | isBotRes res = Bot
486                         | otherwise    = Abs
487 \end{code}
488
489 %************************************************************************
490 %*                                                                      *
491 \subsection{Strictness signatures}
492 %*                                                                      *
493 %************************************************************************
494
495 \begin{code}
496 type SigEnv  = VarEnv (StrictSig, TopLevelFlag)
497         -- We use the SigEnv to tell us whether to
498         -- record info about a variable in the DmdEnv
499         -- We do so if it's a LocalId, but not top-level
500         --
501         -- The DmdEnv gives the demand on the free vars of the function
502         -- when it is given enough args to satisfy the strictness signature
503
504 emptySigEnv  = emptyVarEnv
505
506 extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
507 extendSigEnv top_lvl env var sig = extendVarEnv env var (sig, top_lvl)
508
509 extendSigEnvList = extendVarEnvList
510
511 dmdTransform :: SigEnv          -- The strictness environment
512              -> Id              -- The function
513              -> Demand          -- The demand on the function
514              -> DmdType         -- The demand type of the function in this context
515         -- Returned DmdEnv includes the demand on 
516         -- this function plus demand on its free variables
517
518 dmdTransform sigs var dmd
519
520 ------  DATA CONSTRUCTOR
521   | isDataConId var,            -- Data constructor
522     Seq k Now ds <- res_dmd,    -- and the demand looks inside its fields
523     let StrictSig dmd_ty = idNewStrictness var  -- It must have a strictness sig
524   = if dmdTypeDepth dmd_ty == length ds then    -- Saturated, so unleash the demand
525         -- ds can be empty, when we are just seq'ing the thing
526         mkDmdType emptyDmdEnv ds (dmdTypeRes dmd_ty)
527                 -- Need to extract whether it's a product, hence dmdTypeRes
528     else
529         topDmdType
530
531 ------  IMPORTED FUNCTION
532   | isGlobalId var,             -- Imported function
533     let StrictSig dmd_ty = getNewStrictness var
534   = if dmdTypeDepth dmd_ty <= call_depth then   -- Saturated, so unleash the demand
535         dmd_ty
536     else
537         topDmdType
538
539 ------  LOCAL LET/REC BOUND THING
540   | Just (StrictSig dmd_ty, top_lvl) <- lookupVarEnv sigs var
541   = let
542         fn_ty | dmdTypeDepth dmd_ty <= call_depth = dmd_ty 
543               | otherwise                         = deferType dmd_ty
544         -- NB: it's important to use deferType, and not just return topDmdType
545         -- Consider     let { f x y = p + x } in f 1
546         -- The application isn't saturated, but we must nevertheless propagate 
547         --      a lazy demand for p!  
548     in
549     addVarDmd top_lvl fn_ty var dmd
550
551 ------  LOCAL NON-LET/REC BOUND THING
552   | otherwise                   -- Default case
553   = unitVarDmd var dmd
554
555   where
556     (call_depth, res_dmd) = splitCallDmd dmd
557 \end{code}
558
559
560 %************************************************************************
561 %*                                                                      *
562 \subsection{Demands}
563 %*                                                                      *
564 %************************************************************************
565
566 \begin{code}
567 splitCallDmd :: Demand -> (Int, Demand)
568 splitCallDmd (Call d) = case splitCallDmd d of
569                           (n, r) -> (n+1, r)
570 splitCallDmd d        = (0, d)
571
572 vanillaCall :: Arity -> Demand
573 vanillaCall 0 = Eval
574 vanillaCall n = Call (vanillaCall (n-1))
575
576 deferType :: DmdType -> DmdType
577 deferType (DmdType fv _ _) = DmdType (mapVarEnv defer fv) [] TopRes
578         -- Notice that we throw away info about both arguments and results
579         -- For example,   f = let ... in \x -> x
580         -- We don't want to get a stricness type V->T for f.
581
582 defer :: Demand -> Demand
583 -- c.f. `lub` Abs
584 defer Abs          = Abs
585 defer (Seq k _ ds) = Seq k Defer ds
586 defer other        = Lazy
587
588 lazify :: Demand -> Demand
589 -- The 'Defer' demands are just Lazy at function boundaries
590 lazify (Seq k Defer ds) = Lazy
591 lazify (Seq k Now   ds) = Seq k Now (map lazify ds)
592 lazify Bot              = Abs   -- Don't pass args that are consumed by bottom
593 lazify d                = d
594 \end{code}
595
596 \begin{code}
597 betterStrictness :: StrictSig -> StrictSig -> Bool
598 betterStrictness (StrictSig t1) (StrictSig t2) = betterDmdType t1 t2
599
600 betterDmdType t1 t2 = (t1 `lubType` t2) == t2
601
602 betterDemand :: Demand -> Demand -> Bool
603 -- If d1 `better` d2, and d2 `better` d2, then d1==d2
604 betterDemand d1 d2 = (d1 `lub` d2) == d2
605
606 squashDmdEnv (StrictSig (DmdType fv ds res)) = StrictSig (DmdType emptyDmdEnv ds res)
607 \end{code}
608
609
610 %************************************************************************
611 %*                                                                      *
612 \subsection{LUB and BOTH}
613 %*                                                                      *
614 %************************************************************************
615
616 \begin{code}
617 lub :: Demand -> Demand -> Demand
618
619 lub Bot  d = d
620
621 lub Lazy d = Lazy
622
623 lub Err Bot = Err 
624 lub Err d   = d 
625
626 lub Abs Bot          = Abs
627 lub Abs Err          = Abs
628 lub Abs Abs          = Abs    
629 lub Abs (Seq k _ ds) = Seq k Defer ds   -- Very important ('radicals' example)
630 lub Abs d            = Lazy
631
632 lub Eval Abs              = Lazy
633 lub Eval Lazy             = Lazy
634 lub Eval (Seq k Now   ds) = Seq Keep Now ds
635 lub Eval (Seq k Defer ds) = Lazy
636 lub Eval d                = Eval
637
638 lub (Call d1) (Call d2) = Call (lub d1 d2)
639
640 lub (Seq k1 l1 ds1) (Seq k2 l2 ds2) = Seq (k1 `vee` k2) (l1 `or_defer` l2) (lubs ds1 ds2)
641
642 -- The last clauses deal with the remaining cases for Call and Seq
643 lub d1@(Call _) d2@(Seq _ _ _) = pprPanic "lub" (ppr d1 $$ ppr d2)
644 lub d1 d2                      = lub d2 d1
645
646 -- A Seq can have an empty list of demands, in the polymorphic case.
647 lubs [] ds2 = ds2
648 lubs ds1 [] = ds1
649 lubs ds1 ds2 = ASSERT( length ds1 == length ds2 ) zipWith lub ds1 ds2
650
651 or_defer Now Now = Now
652 or_defer _   _   = Defer
653
654 -------------------------
655 -- Consider (if x then y else []) with demand V
656 -- Then the first branch gives {y->V} and the second
657 -- *implicitly* has {y->A}.  So we must put {y->(V `lub` A)}
658 -- in the result env.
659 lubType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
660   = DmdType lub_fv2 (zipWith lub ds1 ds2) (r1 `lubRes` r2)
661   where
662     lub_fv  = plusUFM_C lub fv1 fv2
663     lub_fv1 = modifyEnv (not (isBotRes r1)) (Abs `lub`) fv2 fv1 lub_fv
664     lub_fv2 = modifyEnv (not (isBotRes r2)) (Abs `lub`) fv1 fv2 lub_fv1
665         -- lub is the identity for Bot
666
667 -------------------------
668 lubRes BotRes r      = r
669 lubRes r      BotRes = r
670 lubRes RetCPR RetCPR = RetCPR
671 lubRes r1     r2     = TopRes
672
673 -----------------------------------
674 vee :: Keepity -> Keepity -> Keepity
675 vee Drop Drop = Drop
676 vee k1   k2   = Keep
677
678 -----------------------------------
679 both :: Demand -> Demand -> Demand
680
681 -- The normal one
682 -- both Bot d = Bot
683
684 -- The experimental one
685 -- The idea is that (error x) places on x
686 --      both demand Bot (like on all free vars)
687 --      and demand Eval (for the arg to error)
688 -- and we want the result to be Eval.
689 both Bot Bot = Bot
690 both Bot Abs = Bot
691 both Bot d   = d
692
693 both Abs d   = d
694
695 both Err Bot = Err
696 both Err Abs = Err
697 both Err d   = d
698
699 both Lazy Bot          = Lazy
700 both Lazy Abs          = Lazy
701 both Lazy Err          = Lazy 
702 both Lazy (Seq k l ds) = Seq Keep l ds
703 both Lazy d            = d
704   -- Notice that the Seq case ensures that we have the
705   -- boxed value.  The equation originally said
706   --    both (Seq k Now ds) = Seq Keep Now ds
707   -- but it's important that the Keep is switched on even
708   -- for a deferred demand.  Otherwise a (Seq Drop Now [])
709   -- might both'd with the result, and then we won't pass
710   -- the boxed value.  Here's an example:
711   --    (x-1) `seq` (x+1, x)
712   -- From the (x+1, x) we get (U*(V) `both` L), which must give S*(V)
713   -- From (x-1) we get U(V). Combining, we must get S(V).
714   -- If we got U*(V) from the pair, we'd end up with U(V), and that
715   -- can be a disaster if a component of the data structure is absent.
716   -- [Disaster = enter an absent argument.]
717
718 both Eval (Seq k l ds) = Seq Keep Now ds
719 both Eval (Call d)     = Call d
720 both Eval d            = Eval
721
722 both (Seq k1 Defer ds1) (Seq k2 Defer ds2) = Seq (k1 `vee` k2) Defer (boths ds1  ds2)
723 both (Seq k1 l1 ds1)    (Seq k2 l2 ds2)    = Seq (k1 `vee` k2) Now   (boths ds1' ds2')
724                                            where
725                                              ds1' = case l1 of { Now -> ds1; Defer -> map defer ds1 }
726                                              ds2' = case l2 of { Now -> ds2; Defer -> map defer ds2 }
727
728 both (Call d1) (Call d2) = Call (d1 `both` d2)
729
730 -- The last clauses deal with the remaining cases for Call and Seq
731 both d1@(Call _) d2@(Seq _ _ _) = pprPanic "both" (ppr d1 $$ ppr d2)
732 both d1 d2                      = both d2 d1
733
734 -----------------------------------
735 -- A Seq can have an empty list of demands, in the polymorphic case.
736 boths [] ds2  = ds2
737 boths ds1 []  = ds1
738 boths ds1 ds2 = ASSERT( length ds1 == length ds2 ) zipWith both ds1 ds2
739
740 -----------------------------------
741 bothRes :: DmdResult -> DmdResult -> DmdResult
742 -- Left-biased for CPR info
743 bothRes BotRes _ = BotRes
744 bothRes _ BotRes = BotRes
745 bothRes r1 _     = r1
746
747 -----------------------------------
748 -- (t1 `bothType` t2) takes the argument/result info from t1,
749 -- using t2 just for its free-var info
750 bothType (DmdType fv1 ds1 r1) (DmdType fv2 ds2 r2)
751   = DmdType both_fv2 ds1 r1
752   where
753     both_fv  = plusUFM_C both fv1 fv2
754     both_fv1 = modifyEnv (isBotRes r1) (`both` Bot) fv2 fv1 both_fv
755     both_fv2 = modifyEnv (isBotRes r2) (`both` Bot) fv1 fv2 both_fv1
756         -- both is the identity for Abs
757 \end{code}
758
759 \begin{code}
760 modifyEnv :: Bool                       -- No-op if False
761           -> (Demand -> Demand)         -- The zapper
762           -> DmdEnv -> DmdEnv           -- Env1 and Env2
763           -> DmdEnv -> DmdEnv           -- Transform this env
764         -- Zap anything in Env1 but not in Env2
765         -- Assume: dom(env) includes dom(Env1) and dom(Env2)
766
767 modifyEnv need_to_modify zapper env1 env2 env
768   | need_to_modify = foldr zap env (keysUFM (env1 `minusUFM` env2))
769   | otherwise      = env
770   where
771     zap uniq env = addToUFM_Directly env uniq (zapper current_val)
772                  where
773                    current_val = expectJust "modifyEnv" (lookupUFM_Directly env uniq)
774 \end{code}
775
776
777 %************************************************************************
778 %*                                                                      *
779 \subsection{Miscellaneous
780 %*                                                                      *
781 %************************************************************************
782
783
784 \begin{code}
785 get_changes binds = vcat (map get_changes_bind binds)
786
787 get_changes_bind (Rec pairs) = vcat (map get_changes_pr pairs)
788 get_changes_bind (NonRec id rhs) = get_changes_pr (id,rhs)
789
790 get_changes_pr (id,rhs) 
791   | isImplicitId id = empty  -- We don't look inside these
792   | otherwise       = get_changes_var id $$ get_changes_expr rhs
793
794 get_changes_var var
795   | isId var  = get_changes_str var $$ get_changes_dmd var
796   | otherwise = empty
797
798 get_changes_expr (Type t)     = empty
799 get_changes_expr (Var v)      = empty
800 get_changes_expr (Lit l)      = empty
801 get_changes_expr (Note n e)   = get_changes_expr e
802 get_changes_expr (App e1 e2)  = get_changes_expr e1 $$ get_changes_expr e2
803 get_changes_expr (Lam b e)    = {- get_changes_var b $$ -} get_changes_expr e
804 get_changes_expr (Let b e)    = get_changes_bind b $$ get_changes_expr e
805 get_changes_expr (Case e b a) = get_changes_expr e $$ {- get_changes_var b $$ -} vcat (map get_changes_alt a)
806
807 get_changes_alt (con,bs,rhs) = {- vcat (map get_changes_var bs) $$ -} get_changes_expr rhs
808
809 get_changes_str id
810   | new_better && old_better = empty
811   | new_better               = message "BETTER"
812   | old_better               = message "WORSE"
813   | otherwise                = message "INCOMPARABLE" 
814   where
815     message word = text word <+> text "strictness for" <+> ppr id <+> info
816     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
817     new = squashDmdEnv (idNewStrictness id)     -- Don't report diffs in the env
818     old = newStrictnessFromOld id
819     old_better = old `betterStrictness` new
820     new_better = new `betterStrictness` old
821
822 get_changes_dmd id
823   | isUnLiftedType (idType id) = empty  -- Not useful
824   | new_better && old_better = empty
825   | new_better               = message "BETTER"
826   | old_better               = message "WORSE"
827   | otherwise                = message "INCOMPARABLE" 
828   where
829     message word = text word <+> text "demand for" <+> ppr id <+> info
830     info = (text "Old" <+> ppr old) $$ (text "New" <+> ppr new)
831     new = lazify (idNewDemandInfo id)   -- Lazify to avoid spurious improvements
832     old = newDemand (idDemandInfo id)
833     new_better = new `betterDemand` old 
834     old_better = old `betterDemand` new
835 \end{code}