2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[StrictAnal]{``Simple'' Mycroft-style strictness analyser}
6 The original version(s) of all strictness-analyser code (except the
7 Semantique analyser) was written by Andy Gill.
10 module StrictAnal ( saBinds ) where
12 #include "HsVersions.h"
14 import CmdLineOpts ( DynFlags, DynFlag(..) )
16 import Id ( setIdStrictness, setInlinePragma,
17 idDemandInfo, setIdDemandInfo, isBottomingId,
20 import CoreLint ( showPass, endPass )
21 import ErrUtils ( dumpIfSet_dyn )
24 import Demand ( Demand, wwStrict, isStrict, isLazy )
25 import Util ( zipWith3Equal, stretchZipWith, compareLength )
26 import BasicTypes ( Activation( NeverActive ) )
31 %************************************************************************
33 \subsection[Thoughts]{Random thoughts}
35 %************************************************************************
37 A note about worker-wrappering. If we have
40 f = let v = <expensive>
43 and we deduce that f is strict, it is nevertheless NOT safe to worker-wapper to
45 f = \x -> case x of Int x# -> fw x#
46 fw = \x# -> let x = Int x#
51 because this obviously loses laziness, since now <expensive>
52 is done each time. Alas.
54 WATCH OUT! This can mean that something is unboxed only to be
55 boxed again. For example
59 Here g is strict, and *will* split into worker-wrapper. A call to
60 g, with the wrapper inlined will then be
62 case arg of Int a# -> gw a#
64 Now g calls f, which has no wrapper, so it has to box it.
66 gw = \a# -> f (Int a#)
71 %************************************************************************
73 \subsection[iface-StrictAnal]{Interface to the outside world}
75 %************************************************************************
77 @saBinds@ decorates bindings with strictness info. A later
78 worker-wrapper pass can use this info to create wrappers and
82 saBinds :: DynFlags -> [CoreBind] -> IO [CoreBind]
84 -- Omit strictness analyser if DEBUG is off
86 saBinds dflags binds = return binds
91 showPass dflags "Strictness analysis";
93 -- Mark each binder with its strictness
94 #ifndef OMIT_STRANAL_STATS
95 let { (binds_w_strictness, sa_stats) = saTopBinds binds nullSaStats };
96 dumpIfSet_dyn dflags Opt_D_dump_simpl_stats "Strictness analysis statistics"
99 let { binds_w_strictness = saTopBindsBinds binds };
102 endPass dflags "Strictness analysis" Opt_D_dump_stranal
107 %************************************************************************
109 \subsection[saBinds]{Strictness analysis of bindings}
111 %************************************************************************
113 [Some of the documentation about types, etc., in \tr{SaLib} may be
114 helpful for understanding this module.]
116 @saTopBinds@ tags each binder in the program with its @Demand@.
117 That tells how each binder is {\em used}; if @Strict@, then the binder
118 is sure to be evaluated to HNF; if @NonStrict@ it may or may not be;
119 if @Absent@, then it certainly is not used. [DATED; ToDo: update]
121 (The above info is actually recorded for posterity in each binder's
122 IdInfo, notably its @DemandInfo@.)
124 We proceed by analysing the bindings top-to-bottom, building up an
125 environment which maps @Id@s to their abstract values (i.e., an
126 @AbsValEnv@ maps an @Id@ to its @AbsVal@).
129 saTopBinds :: [CoreBind] -> SaM [CoreBind] -- not exported
133 starting_abs_env = nullAbsValEnv
135 do_it starting_abs_env starting_abs_env binds
137 do_it _ _ [] = returnSa []
138 do_it senv aenv (b:bs)
139 = saTopBind senv aenv b `thenSa` \ (senv2, aenv2, new_b) ->
140 do_it senv2 aenv2 bs `thenSa` \ new_bs ->
141 returnSa (new_b : new_bs)
144 @saTopBind@ is only used for the top level. We don't add any demand
145 info to these ids because we can't work it out. In any case, it
146 doesn't do us any good to know whether top-level binders are sure to
147 be used; we can't turn top-level @let@s into @case@s.
150 saTopBind :: StrictEnv -> AbsenceEnv
152 -> SaM (StrictEnv, AbsenceEnv, CoreBind)
154 saTopBind str_env abs_env (NonRec binder rhs)
155 = saExpr minDemand str_env abs_env rhs `thenSa` \ new_rhs ->
157 str_rhs = absEval StrAnal rhs str_env
158 abs_rhs = absEval AbsAnal rhs abs_env
160 widened_str_rhs = widen StrAnal str_rhs
161 widened_abs_rhs = widen AbsAnal abs_rhs
162 -- The widening above is done for efficiency reasons.
163 -- See notes on Let case in SaAbsInt.lhs
166 = addStrictnessInfoToTopId
167 widened_str_rhs widened_abs_rhs
170 -- Augment environments with a mapping of the
171 -- binder to its abstract values, computed by absEval
172 new_str_env = addOneToAbsValEnv str_env binder widened_str_rhs
173 new_abs_env = addOneToAbsValEnv abs_env binder widened_abs_rhs
175 returnSa (new_str_env, new_abs_env, NonRec new_binder new_rhs)
177 saTopBind str_env abs_env (Rec pairs)
179 (binders,rhss) = unzip pairs
180 str_rhss = fixpoint StrAnal binders rhss str_env
181 abs_rhss = fixpoint AbsAnal binders rhss abs_env
182 -- fixpoint returns widened values
183 new_str_env = growAbsValEnvList str_env (binders `zip` str_rhss)
184 new_abs_env = growAbsValEnvList abs_env (binders `zip` abs_rhss)
185 new_binders = zipWith3Equal "saTopBind" addStrictnessInfoToTopId
186 str_rhss abs_rhss binders
188 mapSa (saExpr minDemand new_str_env new_abs_env) rhss `thenSa` \ new_rhss ->
190 new_pairs = new_binders `zip` new_rhss
192 returnSa (new_str_env, new_abs_env, Rec new_pairs)
195 -- Top level divergent bindings are marked NOINLINE
196 -- This avoids fruitless inlining of top level error functions
197 addStrictnessInfoToTopId str_val abs_val bndr
198 = if isBottomingId new_id then
199 new_id `setInlinePragma` NeverActive
203 new_id = addStrictnessInfoToId str_val abs_val bndr
206 %************************************************************************
208 \subsection[saExpr]{Strictness analysis of an expression}
210 %************************************************************************
212 @saExpr@ computes the strictness of an expression within a given
216 saExpr :: Demand -> StrictEnv -> AbsenceEnv -> CoreExpr -> SaM CoreExpr
217 -- The demand is the least demand we expect on the
218 -- expression. WwStrict is the least, because we're only
219 -- interested in the expression at all if it's being evaluated,
220 -- but the demand may be more. E.g.
222 -- where f has strictness u(LL), will evaluate E with demand u(LL)
225 minDemands = repeat minDemand
227 -- When we find an application, do the arguments
228 -- with demands gotten from the function
229 saApp str_env abs_env (fun, args)
230 = sequenceSa sa_args `thenSa` \ args' ->
231 saExpr minDemand str_env abs_env fun `thenSa` \ fun' ->
232 returnSa (mkApps fun' args')
234 arg_dmds = case fun of
235 Var var -> case lookupAbsValEnv str_env var of
236 Just (AbsApproxFun ds _)
237 | compareLength ds args /= LT
238 -- 'ds' is at least as long as 'args'.
243 sa_args = stretchZipWith isTypeArg (error "saApp:dmd")
245 -- The arg_dmds are for value args only, we need to skip
246 -- over the type args when pairing up with the demands
247 -- Hence the stretchZipWith
249 sa_arg arg dmd = saExpr dmd' str_env abs_env arg
251 -- Bring arg demand up to minDemand
252 dmd' | isLazy dmd = minDemand
255 saExpr _ _ _ e@(Var _) = returnSa e
256 saExpr _ _ _ e@(Lit _) = returnSa e
257 saExpr _ _ _ e@(Type _) = returnSa e
259 saExpr dmd str_env abs_env (Lam bndr body)
260 = -- Don't bother to set the demand-info on a lambda binder
261 -- We do that only for let(rec)-bound functions
262 saExpr minDemand str_env abs_env body `thenSa` \ new_body ->
263 returnSa (Lam bndr new_body)
265 saExpr dmd str_env abs_env e@(App fun arg)
266 = saApp str_env abs_env (collectArgs e)
268 saExpr dmd str_env abs_env (Note note expr)
269 = saExpr dmd str_env abs_env expr `thenSa` \ new_expr ->
270 returnSa (Note note new_expr)
272 saExpr dmd str_env abs_env (Case expr case_bndr alts)
273 = saExpr minDemand str_env abs_env expr `thenSa` \ new_expr ->
274 mapSa sa_alt alts `thenSa` \ new_alts ->
276 new_case_bndr = addDemandInfoToCaseBndr dmd str_env abs_env alts case_bndr
278 returnSa (Case new_expr new_case_bndr new_alts)
280 sa_alt (con, binders, rhs)
281 = saExpr dmd str_env abs_env rhs `thenSa` \ new_rhs ->
283 new_binders = map add_demand_info binders
284 add_demand_info bndr | isTyVar bndr = bndr
285 | otherwise = addDemandInfoToId dmd str_env abs_env rhs bndr
287 tickCases new_binders `thenSa_` -- stats
288 returnSa (con, new_binders, new_rhs)
290 saExpr dmd str_env abs_env (Let (NonRec binder rhs) body)
291 = -- Analyse the RHS in the environment at hand
293 -- Find the demand on the RHS
294 rhs_dmd = findDemand dmd str_env abs_env body binder
296 -- Bind this binder to the abstract value of the RHS; analyse
297 -- the body of the `let' in the extended environment.
298 str_rhs_val = absEval StrAnal rhs str_env
299 abs_rhs_val = absEval AbsAnal rhs abs_env
301 widened_str_rhs = widen StrAnal str_rhs_val
302 widened_abs_rhs = widen AbsAnal abs_rhs_val
303 -- The widening above is done for efficiency reasons.
304 -- See notes on Let case in SaAbsInt.lhs
306 new_str_env = addOneToAbsValEnv str_env binder widened_str_rhs
307 new_abs_env = addOneToAbsValEnv abs_env binder widened_abs_rhs
309 -- Now determine the strictness of this binder; use that info
310 -- to record DemandInfo/StrictnessInfo in the binder.
311 new_binder = addStrictnessInfoToId
312 widened_str_rhs widened_abs_rhs
313 (binder `setIdDemandInfo` rhs_dmd)
315 tickLet new_binder `thenSa_` -- stats
316 saExpr rhs_dmd str_env abs_env rhs `thenSa` \ new_rhs ->
317 saExpr dmd new_str_env new_abs_env body `thenSa` \ new_body ->
318 returnSa (Let (NonRec new_binder new_rhs) new_body)
320 saExpr dmd str_env abs_env (Let (Rec pairs) body)
322 (binders,rhss) = unzip pairs
323 str_vals = fixpoint StrAnal binders rhss str_env
324 abs_vals = fixpoint AbsAnal binders rhss abs_env
325 -- fixpoint returns widened values
326 new_str_env = growAbsValEnvList str_env (binders `zip` str_vals)
327 new_abs_env = growAbsValEnvList abs_env (binders `zip` abs_vals)
329 saExpr dmd new_str_env new_abs_env body `thenSa` \ new_body ->
330 mapSa (saExpr minDemand new_str_env new_abs_env) rhss `thenSa` \ new_rhss ->
332 -- DON'T add demand info in a Rec!
333 -- a) it's useless: we can't do let-to-case
334 -- b) it's incorrect. Consider
335 -- letrec x = ...y...
338 -- When we ask whether y is demanded we'll bind y to bottom and
339 -- evaluate the body of the letrec. But that will result in our
340 -- deciding that y is absent, which is plain wrong!
341 -- It's much easier simply not to do this.
343 improved_binders = zipWith3Equal "saExpr" addStrictnessInfoToId
344 str_vals abs_vals binders
346 new_pairs = improved_binders `zip` new_rhss
348 returnSa (Let (Rec new_pairs) new_body)
352 %************************************************************************
354 \subsection[computeInfos]{Add computed info to binders}
356 %************************************************************************
358 Important note (Sept 93). @addStrictnessInfoToId@ is used only for
359 let(rec) bound variables, and is use to attach the strictness (not
360 demand) info to the binder. We are careful to restrict this
361 strictness info to the lambda-bound arguments which are actually
362 visible, at the top level, lest we accidentally lose laziness by
363 eagerly looking for an "extra" argument. So we "dig for lambdas" in a
364 rather syntactic way.
366 A better idea might be to have some kind of arity analysis to
367 tell how many args could safely be grabbed.
370 addStrictnessInfoToId
371 :: AbsVal -- Abstract strictness value
372 -> AbsVal -- Ditto absence
374 -> Id -- Augmented with strictness
376 addStrictnessInfoToId str_val abs_val binder
377 = binder `setIdStrictness` findStrictness binder str_val abs_val
381 addDemandInfoToId :: Demand -> StrictEnv -> AbsenceEnv
382 -> CoreExpr -- The scope of the id
384 -> Id -- Id augmented with Demand info
386 addDemandInfoToId dmd str_env abs_env expr binder
387 = binder `setIdDemandInfo` (findDemand dmd str_env abs_env expr binder)
389 addDemandInfoToCaseBndr dmd str_env abs_env alts binder
390 = binder `setIdDemandInfo` (findDemandAlts dmd str_env abs_env alts binder)
393 %************************************************************************
395 \subsection{Monad used herein for stats}
397 %************************************************************************
401 = SaStats FastInt FastInt -- total/marked-demanded lambda-bound
402 FastInt FastInt -- total/marked-demanded case-bound
403 FastInt FastInt -- total/marked-demanded let-bound
404 -- (excl. top-level; excl. letrecs)
406 nullSaStats = SaStats (_ILIT 0) (_ILIT 0) (_ILIT 0) (_ILIT 0) (_ILIT 0) (_ILIT 0)
408 thenSa :: SaM a -> (a -> SaM b) -> SaM b
409 thenSa_ :: SaM a -> SaM b -> SaM b
410 returnSa :: a -> SaM a
412 {-# INLINE thenSa #-}
413 {-# INLINE thenSa_ #-}
414 {-# INLINE returnSa #-}
416 tickLambda :: Id -> SaM ()
417 tickCases :: [CoreBndr] -> SaM ()
418 tickLet :: Id -> SaM ()
420 #ifndef OMIT_STRANAL_STATS
421 type SaM a = SaStats -> (a, SaStats)
423 thenSa expr cont stats
424 = case (expr stats) of { (result, stats1) ->
427 thenSa_ expr cont stats
428 = case (expr stats) of { (_, stats1) ->
431 returnSa x stats = (x, stats)
433 tickLambda var (SaStats tlam dlam tc dc tlet dlet)
434 = case (tick_demanded var (0,0)) of { (totB, demandedB) ->
435 let tot = iUnbox totB ; demanded = iUnbox demandedB
437 ((), SaStats (tlam +# tot) (dlam +# demanded) tc dc tlet dlet) }
439 tickCases vars (SaStats tlam dlam tc dc tlet dlet)
440 = case (foldr tick_demanded (0,0) vars) of { (totB, demandedB) ->
441 let tot = iUnbox totB ; demanded = iUnbox demandedB
443 ((), SaStats tlam dlam (tc +# tot) (dc +# demanded) tlet dlet) }
445 tickLet var (SaStats tlam dlam tc dc tlet dlet)
446 = case (tick_demanded var (0,0)) of { (totB, demandedB) ->
447 let tot = iUnbox totB ; demanded = iUnbox demandedB
449 ((), SaStats tlam dlam tc dc (tlet +# tot) (dlet +# demanded)) }
451 tick_demanded var (tot, demanded)
452 | isTyVar var = (tot, demanded)
455 if (isStrict (idDemandInfo var))
459 pp_stats (SaStats tlam dlam tc dc tlet dlet)
460 = hcat [ptext SLIT("Lambda vars: "), int (iBox dlam), char '/', int (iBox tlam),
461 ptext SLIT("; Case vars: "), int (iBox dc), char '/', int (iBox tc),
462 ptext SLIT("; Let vars: "), int (iBox dlet), char '/', int (iBox tlet)
465 #else {-OMIT_STRANAL_STATS-}
469 thenSa expr cont = cont expr
471 thenSa_ expr cont = cont
475 tickLambda var = panic "OMIT_STRANAL_STATS: tickLambda"
476 tickCases vars = panic "OMIT_STRANAL_STATS: tickCases"
477 tickLet var = panic "OMIT_STRANAL_STATS: tickLet"
479 #endif {-OMIT_STRANAL_STATS-}
481 mapSa :: (a -> SaM b) -> [a] -> SaM [b]
483 mapSa f [] = returnSa []
484 mapSa f (x:xs) = f x `thenSa` \ r ->
485 mapSa f xs `thenSa` \ rs ->
488 sequenceSa :: [SaM a] -> SaM [a]
489 sequenceSa [] = returnSa []
490 sequenceSa (m:ms) = m `thenSa` \ r ->
491 sequenceSa ms `thenSa` \ rs ->