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