[project @ 2000-03-23 17:45:17 by simonpj]
[ghc-hetmet.git] / ghc / compiler / stranal / SaAbsInt.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[SaAbsInt]{Abstract interpreter for strictness analysis}
5
6 \begin{code}
7 module SaAbsInt (
8         findStrictness,
9         findDemand, findDemandAlts,
10         absEval,
11         widen,
12         fixpoint,
13         isBot
14     ) where
15
16 #include "HsVersions.h"
17
18 import CmdLineOpts      ( opt_AllStrict, opt_NumbersStrict )
19 import CoreSyn
20 import CoreUnfold       ( Unfolding, maybeUnfoldingTemplate )
21 import Id               ( Id, idType, idArity, idStrictness, idUnfolding, isDataConId_maybe )
22 import DataCon          ( dataConTyCon, splitProductType_maybe, dataConRepArgTys )
23 import IdInfo           ( StrictnessInfo(..) )
24 import Demand           ( Demand(..), wwPrim, wwStrict, wwEnum, wwUnpackData, wwLazy,
25                           wwUnpackNew )
26 import SaLib
27 import TyCon            ( isProductTyCon, isRecursiveTyCon, isEnumerationTyCon, isNewTyCon )
28 import BasicTypes       ( Arity, NewOrData(..) )
29 import Type             ( splitAlgTyConApp_maybe, 
30                           isUnLiftedType, Type )
31 import TyCon            ( tyConUnique )
32 import PrelInfo         ( numericTyKeys )
33 import Util             ( isIn, nOfThem, zipWithEqual )
34 import Outputable       
35 \end{code}
36
37 %************************************************************************
38 %*                                                                      *
39 \subsection[AbsVal-ops]{Operations on @AbsVals@}
40 %*                                                                      *
41 %************************************************************************
42
43 Least upper bound, greatest lower bound.
44
45 \begin{code}
46 lub, glb :: AbsVal -> AbsVal -> AbsVal
47
48 lub AbsBot val2   = val2        
49 lub val1   AbsBot = val1        
50
51 lub (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual "lub" lub xs ys)
52
53 lub _             _           = AbsTop  -- Crude, but conservative
54                                         -- The crudity only shows up if there
55                                         -- are functions involved
56
57 -- Slightly funny glb; for absence analysis only;
58 -- AbsBot is the safe answer.
59 --
60 -- Using anyBot rather than just testing for AbsBot is important.
61 -- Consider:
62 --
63 --   f = \a b -> ...
64 --
65 --   g = \x y z -> case x of
66 --                   []     -> f x
67 --                   (p:ps) -> f p
68 --
69 -- Now, the abstract value of the branches of the case will be an
70 -- AbsFun, but when testing for z's absence we want to spot that it's
71 -- an AbsFun which can't possibly return AbsBot.  So when glb'ing we
72 -- mustn't be too keen to bale out and return AbsBot; the anyBot test
73 -- spots that (f x) can't possibly return AbsBot.
74
75 -- We have also tripped over the following interesting case:
76 --      case x of
77 --        []     -> \y -> 1
78 --        (p:ps) -> f
79 --
80 -- Now, suppose f is bound to AbsTop.  Does this expression mention z?
81 -- Obviously not.  But the case will take the glb of AbsTop (for f) and
82 -- an AbsFun (for \y->1). We should not bale out and give AbsBot, because
83 -- that would say that it *does* mention z (or anything else for that matter).
84 -- Nor can we always return AbsTop, because the AbsFun might be something
85 -- like (\y->z), which obviously does mention z. The point is that we're
86 -- glbing two functions, and AbsTop is not actually the top of the function
87 -- lattice.  It is more like (\xyz -> x|y|z); that is, AbsTop returns
88 -- poison iff any of its arguments do.
89
90 -- Deal with functions specially, because AbsTop isn't the
91 -- top of their domain.
92
93 glb v1 v2
94   | is_fun v1 || is_fun v2
95   = if not (anyBot v1) && not (anyBot v2)
96     then
97         AbsTop
98     else
99         AbsBot
100   where
101     is_fun (AbsFun _ _)       = True
102     is_fun (AbsApproxFun _ _) = True    -- Not used, but the glb works ok
103     is_fun other              = False
104
105 -- The non-functional cases are quite straightforward
106
107 glb (AbsProd xs) (AbsProd ys) = AbsProd (zipWithEqual "glb" glb xs ys)
108
109 glb AbsTop       v2           = v2
110 glb v1           AbsTop       = v1
111
112 glb _            _            = AbsBot          -- Be pessimistic
113 \end{code}
114
115 @isBot@ returns True if its argument is (a representation of) bottom.  The
116 ``representation'' part is because we need to detect the bottom {\em function}
117 too.  To detect the bottom function, bind its args to top, and see if it
118 returns bottom.
119
120 Used only in strictness analysis:
121 \begin{code}
122 isBot :: AbsVal -> Bool
123
124 isBot AbsBot = True
125 isBot other  = False    -- Functions aren't bottom any more
126 \end{code}
127
128 Used only in absence analysis:
129
130 \begin{code}
131 anyBot :: AbsVal -> Bool
132
133 anyBot AbsBot                  = True   -- poisoned!
134 anyBot AbsTop                  = False
135 anyBot (AbsProd vals)          = any anyBot vals
136 anyBot (AbsFun bndr_ty abs_fn) = anyBot (abs_fn AbsTop)
137 anyBot (AbsApproxFun _ val)    = anyBot val
138 \end{code}
139
140 @widen@ takes an @AbsVal@, $val$, and returns and @AbsVal@ which is
141 approximated by $val$.  Furthermore, the result has no @AbsFun@s in
142 it, so it can be compared for equality by @sameVal@.
143
144 \begin{code}
145 widen :: AnalysisKind -> AbsVal -> AbsVal
146
147 -- Widening is complicated by the fact that funtions are lifted
148 widen StrAnal the_fn@(AbsFun bndr_ty _)
149   = case widened_body of
150         AbsApproxFun ds val -> AbsApproxFun (d : ds) val
151                             where
152                                d = findRecDemand str_fn abs_fn bndr_ty
153                                str_fn val = isBot (foldl (absApply StrAnal) the_fn 
154                                                          (val : [AbsTop | d <- ds]))
155
156         other               -> AbsApproxFun [d] widened_body
157                             where
158                                d = findRecDemand str_fn abs_fn bndr_ty
159                                str_fn val = isBot (absApply StrAnal the_fn val)
160   where
161     widened_body = widen StrAnal (absApply StrAnal the_fn AbsTop)
162     abs_fn val   = False        -- Always says poison; so it looks as if
163                                 -- nothing is absent; safe
164
165 {-      OLD comment... 
166         This stuff is now instead handled neatly by the fact that AbsApproxFun 
167         contains an AbsVal inside it.   SLPJ Jan 97
168
169   | isBot abs_body = AbsBot
170     -- It's worth checking for a function which is unconditionally
171     -- bottom.  Consider
172     --
173     --  f x y = let g y = case x of ...
174     --          in (g ..) + (g ..)
175     --
176     -- Here, when we are considering strictness of f in x, we'll
177     -- evaluate the body of f with x bound to bottom.  The current
178     -- strategy is to bind g to its *widened* value; without the isBot
179     -- (...) test above, we'd bind g to an AbsApproxFun, and deliver
180     -- Top, not Bot as the value of f's rhs.  The test spots the
181     -- unconditional bottom-ness of g when x is bottom.  (Another
182     -- alternative here would be to bind g to its exact abstract
183     -- value, but that entails lots of potential re-computation, at
184     -- every application of g.)
185 -}
186
187 widen StrAnal (AbsProd vals) = AbsProd (map (widen StrAnal) vals)
188 widen StrAnal other_val      = other_val
189
190
191 widen AbsAnal the_fn@(AbsFun bndr_ty _)
192   | anyBot widened_body = AbsBot
193         -- In the absence-analysis case it's *essential* to check
194         -- that the function has no poison in its body.  If it does,
195         -- anywhere, then the whole function is poisonous.
196
197   | otherwise
198   = case widened_body of
199         AbsApproxFun ds val -> AbsApproxFun (d : ds) val
200                             where
201                                d = findRecDemand str_fn abs_fn bndr_ty
202                                abs_fn val = not (anyBot (foldl (absApply AbsAnal) the_fn 
203                                                                 (val : [AbsTop | d <- ds])))
204
205         other               -> AbsApproxFun [d] widened_body
206                             where
207                                d = findRecDemand str_fn abs_fn bndr_ty
208                                abs_fn val = not (anyBot (absApply AbsAnal the_fn val))
209   where
210     widened_body = widen AbsAnal (absApply AbsAnal the_fn AbsTop)
211     str_fn val   = True         -- Always says non-termination;
212                                 -- that'll make findRecDemand peer into the
213                                 -- structure of the value.
214
215 widen AbsAnal (AbsProd vals) = AbsProd (map (widen AbsAnal) vals)
216
217         -- It's desirable to do a good job of widening for product
218         -- values.  Consider
219         --
220         --      let p = (x,y)
221         --      in ...(case p of (x,y) -> x)...
222         --
223         -- Now, is y absent in this expression?  Currently the
224         -- analyser widens p before looking at p's scope, to avoid
225         -- lots of recomputation in the case where p is a function.
226         -- So if widening doesn't have a case for products, we'll
227         -- widen p to AbsBot (since when searching for absence in y we
228         -- bind y to poison ie AbsBot), and now we are lost.
229
230 widen AbsAnal other_val = other_val
231
232 -- WAS:   if anyBot val then AbsBot else AbsTop
233 -- Nowadays widen is doing a better job on functions for absence analysis.
234 \end{code}
235
236 @crudeAbsWiden@ is used just for absence analysis, and always
237 returns AbsTop or AbsBot, so it widens to a two-point domain
238
239 \begin{code}
240 crudeAbsWiden :: AbsVal -> AbsVal
241 crudeAbsWiden val = if anyBot val then AbsBot else AbsTop
242 \end{code}
243
244 @sameVal@ compares two abstract values for equality.  It can't deal with
245 @AbsFun@, but that should have been removed earlier in the day by @widen@.
246
247 \begin{code}
248 sameVal :: AbsVal -> AbsVal -> Bool     -- Can't handle AbsFun!
249
250 #ifdef DEBUG
251 sameVal (AbsFun _ _) _ = panic "sameVal: AbsFun: arg1"
252 sameVal _ (AbsFun _ _) = panic "sameVal: AbsFun: arg2"
253 #endif
254
255 sameVal AbsBot AbsBot = True
256 sameVal AbsBot other  = False   -- widen has reduced AbsFun bots to AbsBot
257
258 sameVal AbsTop AbsTop = True
259 sameVal AbsTop other  = False           -- Right?
260
261 sameVal (AbsProd vals1) (AbsProd vals2) = and (zipWithEqual "sameVal" sameVal vals1 vals2)
262 sameVal (AbsProd _)     AbsTop          = False
263 sameVal (AbsProd _)     AbsBot          = False
264
265 sameVal (AbsApproxFun str1 v1) (AbsApproxFun str2 v2) = str1 == str2 && sameVal v1 v2
266 sameVal (AbsApproxFun _ _)     AbsTop                 = False
267 sameVal (AbsApproxFun _ _)     AbsBot                 = False
268
269 sameVal val1 val2 = panic "sameVal: type mismatch or AbsFun encountered"
270 \end{code}
271
272
273 @evalStrictness@ compares a @Demand@ with an abstract value, returning
274 @True@ iff the abstract value is {\em less defined} than the demand.
275 (@True@ is the exciting answer; @False@ is always safe.)
276
277 \begin{code}
278 evalStrictness :: Demand
279                -> AbsVal
280                -> Bool          -- True iff the value is sure
281                                 -- to be less defined than the Demand
282
283 evalStrictness (WwLazy _) _   = False
284 evalStrictness WwStrict   val = isBot val
285 evalStrictness WwEnum     val = isBot val
286
287 evalStrictness (WwUnpack NewType _ (demand:_)) val
288   = evalStrictness demand val
289
290 evalStrictness (WwUnpack DataType _ demand_info) val
291   = case val of
292       AbsTop       -> False
293       AbsBot       -> True
294       AbsProd vals -> or (zipWithEqual "evalStrictness" evalStrictness demand_info vals)
295       _            -> pprTrace "evalStrictness?" empty False
296
297 evalStrictness WwPrim val
298   = case val of
299       AbsTop -> False
300       AbsBot -> True    -- Can happen: consider f (g x), where g is a 
301                         -- recursive function returning an Int# that diverges
302
303       other  -> pprPanic "evalStrictness: WwPrim:" (ppr other)
304 \end{code}
305
306 For absence analysis, we're interested in whether "poison" in the
307 argument (ie a bottom therein) can propagate to the result of the
308 function call; that is, whether the specified demand can {\em
309 possibly} hit poison.
310
311 \begin{code}
312 evalAbsence (WwLazy True) _ = False     -- Can't possibly hit poison
313                                         -- with Absent demand
314
315 evalAbsence (WwUnpack NewType _ (demand:_)) val
316   = evalAbsence demand val
317
318 evalAbsence (WwUnpack DataType _ demand_info) val
319   = case val of
320         AbsTop       -> False           -- No poison in here
321         AbsBot       -> True            -- Pure poison
322         AbsProd vals -> or (zipWithEqual "evalAbsence" evalAbsence demand_info vals)
323         _            -> panic "evalAbsence: other"
324
325 evalAbsence other val = anyBot val
326   -- The demand is conservative; even "Lazy" *might* evaluate the
327   -- argument arbitrarily so we have to look everywhere for poison
328 \end{code}
329
330 %************************************************************************
331 %*                                                                      *
332 \subsection[absEval]{Evaluate an expression in the abstract domain}
333 %*                                                                      *
334 %************************************************************************
335
336 \begin{code}
337 -- The isBottomingId stuf is now dealt with via the Id's strictness info
338 -- absId anal var env | isBottomingId var
339 --   = case anal of
340 --      StrAnal -> AbsBot       -- See discussion below
341 --      AbsAnal -> AbsTop       -- Just want to see if there's any poison in
342                                 -- error's arg
343
344 absId anal var env
345   = case (lookupAbsValEnv env var, 
346           isDataConId_maybe var, 
347           idStrictness var, 
348           maybeUnfoldingTemplate (idUnfolding var)) of
349
350         (Just abs_val, _, _, _) ->
351                         abs_val -- Bound in the environment
352
353         (_, Just data_con, _, _) | isProductTyCon tycon &&
354                                    not (isRecursiveTyCon tycon)
355                 ->      -- A product.  We get infinite loops if we don't
356                         -- check for recursive products!
357                         -- The strictness info on the constructor 
358                         -- isn't expressive enough to contain its abstract value
359                    productAbsVal (dataConRepArgTys data_con) []
360                 where
361                    tycon = dataConTyCon data_con
362
363         (_, _, NoStrictnessInfo, Just unfolding) ->
364                         -- We have an unfolding for the expr
365                         -- Assume the unfolding has no free variables since it
366                         -- came from inside the Id
367                         absEval anal unfolding env
368                 -- Notice here that we only look in the unfolding if we don't
369                 -- have strictness info (an unusual situation).
370                 -- We could have chosen to look in the unfolding if it exists,
371                 -- and only try the strictness info if it doesn't, and that would
372                 -- give more accurate results, at the cost of re-abstract-interpreting
373                 -- the unfolding every time.
374                 -- We found only one place where the look-at-unfolding-first
375                 -- method gave better results, which is in the definition of
376                 -- showInt in the Prelude.  In its defintion, fromIntegral is
377                 -- not inlined (it's big) but ab-interp-ing its unfolding gave
378                 -- a better result than looking at its strictness only.
379                 --  showInt :: Integral a => a -> [Char] -> [Char]
380                 -- !       {-# GHC_PRAGMA _A_ 1 _U_ 122 _S_
381                 --         "U(U(U(U(SA)AAAAAAAAL)AA)AAAAASAAASA)" {...} _N_ _N_ #-}
382                 -- --- 42,44 ----
383                 --   showInt :: Integral a => a -> [Char] -> [Char]
384                 -- !       {-# GHC_PRAGMA _A_ 1 _U_ 122 _S_
385                 --        "U(U(U(U(SL)LLLLLLLLL)LL)LLLLLSLLLLL)" _N_ _N_ #-}
386
387
388         (_, _, strictness_info, _) ->
389                         -- Includes NoUnfolding
390                         -- Try the strictness info
391                         absValFromStrictness anal strictness_info
392
393 productAbsVal []                 rev_abs_args = AbsProd (reverse rev_abs_args)
394 productAbsVal (arg_ty : arg_tys) rev_abs_args = AbsFun arg_ty (\ abs_arg -> productAbsVal arg_tys (abs_arg : rev_abs_args))
395 \end{code}
396
397 \begin{code}
398 absEval :: AnalysisKind -> CoreExpr -> AbsValEnv -> AbsVal
399
400 absEval anal (Type ty) env = AbsTop
401 absEval anal (Var var) env = absId anal var env
402 \end{code}
403
404 Discussion about error (following/quoting Lennart): Any expression
405 'error e' is regarded as bottom (with HBC, with the -ffail-strict
406 flag, on with -O).
407
408 Regarding it as bottom gives much better strictness properties for
409 some functions.  E.g.
410
411         f [x] y = x+y
412         f (x:xs) y = f xs (x+y)
413 i.e.
414         f [] _ = error "no match"
415         f [x] y = x+y
416         f (x:xs) y = f xs (x+y)
417
418 is strict in y, which you really want.  But, it may lead to
419 transformations that turn a call to \tr{error} into non-termination.
420 (The odds of this happening aren't good.)
421
422 Things are a little different for absence analysis, because we want
423 to make sure that any poison (?????)
424
425 \begin{code}
426 absEval anal (Lit _) env = AbsTop
427         -- Literals terminate (strictness) and are not poison (absence)
428 \end{code}
429
430 \begin{code}
431 absEval anal (Lam bndr body) env
432   | isTyVar bndr = absEval anal body env        -- Type lambda
433   | otherwise    = AbsFun (idType bndr) abs_fn  -- Value lambda
434   where
435     abs_fn arg = absEval anal body (addOneToAbsValEnv env bndr arg)
436
437 absEval anal (App expr (Type ty)) env
438   = absEval anal expr env                       -- Type appplication
439 absEval anal (App f val_arg) env
440   = absApply anal (absEval anal f env)          -- Value applicationn
441                   (absEval anal val_arg env)
442 \end{code}
443
444 \begin{code}
445 absEval anal expr@(Case scrut case_bndr alts) env
446   = let
447         scrut_val  = absEval anal scrut env
448         alts_env   = addOneToAbsValEnv env case_bndr scrut_val
449     in
450     case (scrut_val, alts) of
451         (AbsBot, _) -> AbsBot
452
453         (AbsProd arg_vals, [(con, bndrs, rhs)])
454                 | con /= DEFAULT ->
455                 -- The scrutinee is a product value, so it must be of a single-constr
456                 -- type; so the constructor in this alternative must be the right one
457                 -- so we can go ahead and bind the constructor args to the components
458                 -- of the product value.
459             ASSERT(length arg_vals == length val_bndrs)
460             absEval anal rhs rhs_env
461           where
462             val_bndrs = filter isId bndrs
463             rhs_env   = growAbsValEnvList alts_env (val_bndrs `zip` arg_vals)
464
465         other -> absEvalAlts anal alts alts_env
466 \end{code}
467
468 For @Lets@ we widen the value we get.  This is nothing to
469 do with fixpointing.  The reason is so that we don't get an explosion
470 in the amount of computation.  For example, consider:
471 \begin{verbatim}
472       let
473         g a = case a of
474                 q1 -> ...
475                 q2 -> ...
476         f x = case x of
477                 p1 -> ...g r...
478                 p2 -> ...g s...
479       in
480         f e
481 \end{verbatim}
482 If we bind @f@ and @g@ to their exact abstract value, then we'll
483 ``execute'' one call to @f@ and {\em two} calls to @g@.  This can blow
484 up exponentially.  Widening cuts it off by making a fixed
485 approximation to @f@ and @g@, so that the bodies of @f@ and @g@ are
486 not evaluated again at all when they are called.
487
488 Of course, this can lose useful joint strictness, which is sad.  An
489 alternative approach would be to try with a certain amount of ``fuel''
490 and be prepared to bale out.
491
492 \begin{code}
493 absEval anal (Let (NonRec binder e1) e2) env
494   = let
495         new_env = addOneToAbsValEnv env binder (widen anal (absEval anal e1 env))
496     in
497         -- The binder of a NonRec should *not* be of unboxed type,
498         -- hence no need to strictly evaluate the Rhs.
499     absEval anal e2 new_env
500
501 absEval anal (Let (Rec pairs) body) env
502   = let
503         (binders,rhss) = unzip pairs
504         rhs_vals = cheapFixpoint anal binders rhss env  -- Returns widened values
505         new_env  = growAbsValEnvList env (binders `zip` rhs_vals)
506     in
507     absEval anal body new_env
508
509 absEval anal (Note note expr) env = absEval anal expr env
510 \end{code}
511
512 \begin{code}
513 absEvalAlts :: AnalysisKind -> [CoreAlt] -> AbsValEnv -> AbsVal
514 absEvalAlts anal alts env
515   = combine anal (map go alts)
516   where
517     combine StrAnal = foldr1 lub        -- Diverge only if all diverge
518     combine AbsAnal = foldr1 glb        -- Find any poison
519
520     go (con, bndrs, rhs)
521       = absEval anal rhs rhs_env
522       where
523         rhs_env = growAbsValEnvList env (filter isId bndrs `zip` repeat AbsTop)
524 \end{code}
525
526 %************************************************************************
527 %*                                                                      *
528 \subsection[absApply]{Apply an abstract function to an abstract argument}
529 %*                                                                      *
530 %************************************************************************
531
532 Easy ones first:
533
534 \begin{code}
535 absApply :: AnalysisKind -> AbsVal -> AbsVal -> AbsVal
536
537 absApply anal AbsBot arg = AbsBot
538   -- AbsBot represents the abstract bottom *function* too
539
540 absApply StrAnal AbsTop arg = AbsTop
541 absApply AbsAnal AbsTop arg = if anyBot arg
542                               then AbsBot
543                               else AbsTop
544         -- To be conservative, we have to assume that a function about
545         -- which we know nothing (AbsTop) might look at some part of
546         -- its argument
547 \end{code}
548
549 An @AbsFun@ with only one more argument needed---bind it and eval the
550 result.  A @Lam@ with two or more args: return another @AbsFun@ with
551 an augmented environment.
552
553 \begin{code}
554 absApply anal (AbsFun bndr_ty abs_fn) arg = abs_fn arg
555 \end{code}
556
557 \begin{code}
558 absApply StrAnal (AbsApproxFun (d:ds) val) arg
559   = case ds of 
560         []    -> val'
561         other -> AbsApproxFun ds val'   -- Result is non-bot if there are still args
562   where
563     val' | evalStrictness d arg = AbsBot
564          | otherwise            = val
565
566 absApply AbsAnal (AbsApproxFun (d:ds) val) arg
567   = if evalAbsence d arg
568     then AbsBot         -- Poison in arg means poison in the application
569     else case ds of
570                 []    -> val
571                 other -> AbsApproxFun ds val
572
573 #ifdef DEBUG
574 absApply anal f@(AbsProd _)       arg = pprPanic ("absApply: Duff function: AbsProd." ++ show anal) ((ppr f) <+> (ppr arg))
575 #endif
576 \end{code}
577
578
579
580
581 %************************************************************************
582 %*                                                                      *
583 \subsection[findStrictness]{Determine some binders' strictness}
584 %*                                                                      *
585 %************************************************************************
586
587 \begin{code}
588 findStrictness :: Id
589                -> AbsVal                -- Abstract strictness value of function
590                -> AbsVal                -- Abstract absence value of function
591                -> StrictnessInfo        -- Resulting strictness annotation
592
593 findStrictness id (AbsApproxFun str_ds str_res) (AbsApproxFun abs_ds _)
594         -- You might think there's really no point in describing detailed
595         -- strictness for a divergent function; 
596         -- If it's fully applied we get bottom regardless of the
597         -- argument.  If it's not fully applied we don't get bottom.
598         -- Finally, we don't want to regard the args of a divergent function
599         -- as 'interesting' for inlining purposes (see Simplify.prepareArgs)
600         --
601         -- HOWEVER, if we make diverging functions appear lazy, they
602         -- don't get wrappers, and then we get dreadful reboxing.
603         -- See notes with WwLib.worthSplitting
604   = StrictnessInfo (combineDemands id str_ds abs_ds) (isBot str_res)
605
606 findStrictness id str_val abs_val = NoStrictnessInfo
607
608 -- The list of absence demands passed to combineDemands 
609 -- can be shorter than the list of absence demands
610 --
611 --      lookup = \ dEq -> letrec {
612 --                           lookup = \ key ds -> ...lookup...
613 --                        }
614 --                        in lookup
615 -- Here the strictness value takes three args, but the absence value
616 -- takes only one, for reasons I don't quite understand (see cheapFixpoint)
617
618 combineDemands id orig_str_ds orig_abs_ds
619   = go orig_str_ds orig_abs_ds 
620   where
621     go str_ds abs_ds = zipWith mk_dmd str_ds (abs_ds ++ repeat wwLazy)
622
623     mk_dmd str_dmd (WwLazy True) = WARN( case str_dmd of { WwLazy _ -> False; other -> True },
624                                          ppr id <+> ppr orig_str_ds <+> ppr orig_abs_ds )
625                                    WwLazy True  -- Best of all
626     mk_dmd (WwUnpack nd u str_ds) 
627            (WwUnpack _ _ abs_ds) = WwUnpack nd u (go str_ds abs_ds)
628
629     mk_dmd str_dmd abs_dmd = str_dmd
630 \end{code}
631
632
633 \begin{code}
634 findDemand dmd str_env abs_env expr binder
635   = findRecDemand str_fn abs_fn (idType binder)
636   where
637     str_fn val = evalStrictness   dmd (absEval StrAnal expr (addOneToAbsValEnv str_env binder val))
638     abs_fn val = not (evalAbsence dmd (absEval AbsAnal expr (addOneToAbsValEnv abs_env binder val)))
639
640 findDemandAlts dmd str_env abs_env alts binder
641   = findRecDemand str_fn abs_fn (idType binder)
642   where
643     str_fn val = evalStrictness   dmd (absEvalAlts StrAnal alts (addOneToAbsValEnv str_env binder val))
644     abs_fn val = not (evalAbsence dmd (absEvalAlts AbsAnal alts (addOneToAbsValEnv abs_env binder val)))
645 \end{code}
646
647 @findRecDemand@ is where we finally convert strictness/absence info
648 into ``Demands'' which we can pin on Ids (etc.).
649
650 NOTE: What do we do if something is {\em both} strict and absent?
651 Should \tr{f x y z = error "foo"} says that \tr{f}'s arguments are all
652 strict (because of bottoming effect of \tr{error}) or all absent
653 (because they're not used)?
654
655 Well, for practical reasons, we prefer absence over strictness.  In
656 particular, it makes the ``default defaults'' for class methods (the
657 ones that say \tr{defm.foo dict = error "I don't exist"}) come out
658 nicely [saying ``the dict isn't used''], rather than saying it is
659 strict in every component of the dictionary [massive gratuitious
660 casing to take the dict apart].
661
662 But you could have examples where going for strictness would be better
663 than absence.  Consider:
664 \begin{verbatim}
665         let x = something big
666         in
667         f x y z + g x
668 \end{verbatim}
669
670 If \tr{x} is marked absent in \tr{f}, but not strict, and \tr{g} is
671 lazy, then the thunk for \tr{x} will be built.  If \tr{f} was strict,
672 then we'd let-to-case it:
673 \begin{verbatim}
674         case something big of
675           x -> f x y z + g x
676 \end{verbatim}
677 Ho hum.
678
679 \begin{code}
680 findRecDemand :: (AbsVal -> Bool)       -- True => function applied to this value yields Bot
681               -> (AbsVal -> Bool)       -- True => function applied to this value yields no poison
682               -> Type       -- The type of the argument
683               -> Demand
684
685 findRecDemand str_fn abs_fn ty
686   = if isUnLiftedType ty then -- It's a primitive type!
687        wwPrim
688
689     else if abs_fn AbsBot then -- It's absent
690        -- We prefer absence over strictness: see NOTE above.
691        WwLazy True
692
693     else if not (opt_AllStrict ||
694                  (opt_NumbersStrict && is_numeric_type ty) ||
695                  str_fn AbsBot) then
696         WwLazy False -- It's not strict and we're not pretending
697
698     else -- It's strict (or we're pretending it is)!
699
700        case splitProductType_maybe ty of
701
702          Nothing -> wwStrict    -- Could have a test for wwEnum, but
703                                 -- we don't exploit it yet, so don't bother
704
705          Just (tycon,_,data_con,cmpnt_tys)      -- Single constructor case
706            | isNewTyCon tycon                   -- A newtype!
707            ->   ASSERT( null (tail cmpnt_tys) )
708                 let
709                     demand = findRecDemand str_fn abs_fn (head cmpnt_tys)
710                 in
711                 wwUnpackNew demand
712
713            |  null compt_strict_infos           -- A nullary data type
714            || isRecursiveTyCon tycon            -- Recursive data type; don't unpack
715            ->   wwStrict
716
717            | otherwise                          -- Some other data type
718            ->   wwUnpackData compt_strict_infos
719
720            where
721               prod_len = length cmpnt_tys
722               compt_strict_infos
723                 = [ findRecDemand
724                          (\ cmpnt_val ->
725                                str_fn (mkMainlyTopProd prod_len i cmpnt_val)
726                          )
727                          (\ cmpnt_val ->
728                                abs_fn (mkMainlyTopProd prod_len i cmpnt_val)
729                          )
730                      cmpnt_ty
731                   | (cmpnt_ty, i) <- cmpnt_tys `zip` [1..] ]
732
733   where
734     is_numeric_type ty
735       = case (splitAlgTyConApp_maybe ty) of -- NB: duplicates stuff done above
736           Nothing -> False
737           Just (tycon, _, _)
738             | tyConUnique tycon `is_elem` numericTyKeys
739             -> True
740           _{-something else-} -> False
741       where
742         is_elem = isIn "is_numeric_type"
743
744     -- mkMainlyTopProd: make an AbsProd that is all AbsTops ("n"-1 of
745     -- them) except for a given value in the "i"th position.
746
747     mkMainlyTopProd :: Int -> Int -> AbsVal -> AbsVal
748
749     mkMainlyTopProd n i val
750       = let
751             befores = nOfThem (i-1) AbsTop
752             afters  = nOfThem (n-i) AbsTop
753         in
754         AbsProd (befores ++ (val : afters))
755 \end{code}
756
757 %************************************************************************
758 %*                                                                      *
759 \subsection[fixpoint]{Fixpointer for the strictness analyser}
760 %*                                                                      *
761 %************************************************************************
762
763 The @fixpoint@ functions take a list of \tr{(binder, expr)} pairs, an
764 environment, and returns the abstract value of each binder.
765
766 The @cheapFixpoint@ function makes a conservative approximation,
767 by binding each of the variables to Top in their own right hand sides.
768 That allows us to make rapid progress, at the cost of a less-than-wonderful
769 approximation.
770
771 \begin{code}
772 cheapFixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
773
774 cheapFixpoint AbsAnal [id] [rhs] env
775   = [crudeAbsWiden (absEval AbsAnal rhs new_env)]
776   where
777     new_env = addOneToAbsValEnv env id AbsTop   -- Unsafe starting point!
778                     -- In the just-one-binding case, we guarantee to
779                     -- find a fixed point in just one iteration,
780                     -- because we are using only a two-point domain.
781                     -- This improves matters in cases like:
782                     --
783                     --  f x y = letrec g = ...g...
784                     --          in g x
785                     --
786                     -- Here, y isn't used at all, but if g is bound to
787                     -- AbsBot we simply get AbsBot as the next
788                     -- iteration too.
789
790 cheapFixpoint anal ids rhss env
791   = [widen anal (absEval anal rhs new_env) | rhs <- rhss]
792                 -- We do just one iteration, starting from a safe
793                 -- approximation.  This won't do a good job in situations
794                 -- like:
795                 --      \x -> letrec f = ...g...
796                 --                   g = ...f...x...
797                 --            in
798                 --            ...f...
799                 -- Here, f will end up bound to Top after one iteration,
800                 -- and hence we won't spot the strictness in x.
801                 -- (A second iteration would solve this.  ToDo: try the effect of
802                 --  really searching for a fixed point.)
803   where
804     new_env = growAbsValEnvList env [(id,safe_val) | id <- ids]
805
806     safe_val
807       = case anal of    -- The safe starting point
808           StrAnal -> AbsTop
809           AbsAnal -> AbsBot
810 \end{code}
811
812 \begin{verbatim}
813 mkLookupFun :: (key -> key -> Bool)     -- Equality predicate
814             -> (key -> key -> Bool)     -- Less-than predicate
815             -> [(key,val)]              -- The assoc list
816             -> key                      -- The key
817             -> Maybe val                -- The corresponding value
818
819 mkLookupFun eq lt alist s
820   = case [a | (s',a) <- alist, s' `eq` s] of
821       []    -> Nothing
822       (a:_) -> Just a
823 \end{verbatim}
824
825 \begin{code}
826 fixpoint :: AnalysisKind -> [Id] -> [CoreExpr] -> AbsValEnv -> [AbsVal]
827
828 fixpoint anal [] _ env = []
829
830 fixpoint anal ids rhss env
831   = fix_loop initial_vals
832   where
833     initial_val id
834       = case anal of    -- The (unsafe) starting point
835           AbsAnal -> AbsTop
836           StrAnal -> AbsBot
837                 -- At one stage for StrAnal we said:
838                 --   if (returnsRealWorld (idType id))
839                 --   then AbsTop -- this is a massively horrible hack (SLPJ 95/05)
840                 -- but no one has the foggiest idea what this hack did,
841                 -- and returnsRealWorld was a stub that always returned False
842                 -- So this comment is all that is left of the hack!
843
844     initial_vals = [ initial_val id | id <- ids ]
845
846     fix_loop :: [AbsVal] -> [AbsVal]
847
848     fix_loop current_widened_vals
849       = let
850             new_env  = growAbsValEnvList env (ids `zip` current_widened_vals)
851             new_vals = [ absEval anal rhs new_env | rhs <- rhss ]
852             new_widened_vals = map (widen anal) new_vals
853         in
854         if (and (zipWith sameVal current_widened_vals new_widened_vals)) then
855             current_widened_vals
856
857             -- NB: I was too chicken to make that a zipWithEqual,
858             -- lest I jump into a black hole.  WDP 96/02
859
860             -- Return the widened values.  We might get a slightly
861             -- better value by returning new_vals (which we used to
862             -- do, see below), but alas that means that whenever the
863             -- function is called we have to re-execute it, which is
864             -- expensive.
865
866             -- OLD VERSION
867             -- new_vals
868             -- Return the un-widened values which may be a bit better
869             -- than the widened ones, and are guaranteed safe, since
870             -- they are one iteration beyond current_widened_vals,
871             -- which itself is a fixed point.
872         else
873             fix_loop new_widened_vals
874 \end{code}
875
876 For absence analysis, we make do with a very very simple approach:
877 look for convergence in a two-point domain.
878
879 We used to use just one iteration, starting with the variables bound
880 to @AbsBot@, which is safe.
881
882 Prior to that, we used one iteration starting from @AbsTop@ (which
883 isn't safe).  Why isn't @AbsTop@ safe?  Consider:
884 \begin{verbatim}
885         letrec
886           x = ...p..d...
887           d = (x,y)
888         in
889         ...
890 \end{verbatim}
891 Here, if p is @AbsBot@, then we'd better {\em not} end up with a ``fixed
892 point'' of @d@ being @(AbsTop, AbsTop)@!  An @AbsBot@ initial value is
893 safe because it gives poison more often than really necessary, and
894 thus may miss some absence, but will never claim absence when it ain't
895 so.
896
897 Anyway, one iteration starting with everything bound to @AbsBot@ give
898 bad results for
899
900         f = \ x -> ...f...
901
902 Here, f would always end up bound to @AbsBot@, which ain't very
903 clever, because then it would introduce poison whenever it was
904 applied.  Much better to start with f bound to @AbsTop@, and widen it
905 to @AbsBot@ if any poison shows up. In effect we look for convergence
906 in the two-point @AbsTop@/@AbsBot@ domain.
907
908 What we miss (compared with the cleverer strictness analysis) is
909 spotting that in this case
910
911         f = \ x y -> ...y...(f x y')...
912
913 \tr{x} is actually absent, since it is only passed round the loop, never
914 used.  But who cares about missing that?
915
916 NB: despite only having a two-point domain, we may still have many
917 iterations, because there are several variables involved at once.