1 \section{Update Avoidance Analyser} -*-haskell-literate-*-
3 (c) Simon Marlow, Andre Santos 1992-1993
4 (c) The AQUA Project, Glasgow University, 1995-1996
6 %-----------------------------------------------------------------------------
7 \subsection{Module Interface}
10 #include "HsVersions.h"
13 > module UpdAnal ( updateAnalyse ) where
15 > import Ubiq{-uitous-}
18 > import Util ( panic )
20 > updateAnalyse :: [StgBinding] -> [StgBinding] {- Exported -}
21 > updateAnalyse = panic "UpdAnal.updateAnalyse"
23 > {- LATER: to end of file:
24 > --import Type ( splitFunTy, splitSigmaTy, Class, TyVarTemplate,
29 > --import Outputable ( isExported )
31 > --import SrcLoc ( mkUnknownSrcLoc )
34 > --import Unique ( getBuiltinUniques )
37 %-----------------------------------------------------------------------------
38 \subsection{Reverse application}
40 This is used instead of lazy pattern bindings to avoid space leaks.
45 %-----------------------------------------------------------------------------
48 List of closure references
51 > x `notInRefs` y = not (x `elementOfUniqSet` y)
53 A closure value: environment of closures that are evaluated on entry,
54 a list of closures that are referenced from the result, and an
55 abstract value for the evaluated closure.
57 An IdEnv is used for the reference counts, as these environments are
58 combined often. A generic environment is used for the main environment
59 mapping closure names to values; as a common operation is extension of
60 this environment, this representation should be efficient.
62 > -- partain: funny synonyms to cope w/ the fact
63 > -- that IdEnvs know longer know what their keys are
64 > -- (94/05) ToDo: improve
65 > type IdEnvInt = IdEnv (Id, Int)
66 > type IdEnvClosure = IdEnv (Id, Closure)
68 > -- backward-compat functions
69 > null_IdEnv :: IdEnv (Id, a)
70 > null_IdEnv = nullIdEnv
72 > unit_IdEnv :: Id -> a -> IdEnv (Id, a)
73 > unit_IdEnv k v = unitIdEnv k (k, v)
75 > mk_IdEnv :: [(Id, a)] -> IdEnv (Id, a)
76 > mk_IdEnv pairs = mkIdEnv [ (k, (k,v)) | (k,v) <- pairs ]
78 > grow_IdEnv :: IdEnv (Id, a) -> IdEnv (Id, a) -> IdEnv (Id, a)
79 > grow_IdEnv env1 env2 = growIdEnv env1 env2
81 > addOneTo_IdEnv :: IdEnv (Id, a) -> Id -> a -> IdEnv (Id, a)
82 > addOneTo_IdEnv env k v = addOneToIdEnv env k (k, v)
84 > combine_IdEnvs :: (a->a->a) -> IdEnv (Id, a) -> IdEnv (Id, a) -> IdEnv (Id, a)
85 > combine_IdEnvs combiner env1 env2 = combineIdEnvs new_combiner env1 env2
87 > new_combiner (id, x) (_, y) = (id, combiner x y)
89 > dom_IdEnv :: IdEnv (Id, a) -> Refs
90 > dom_IdEnv env = mkUniqSet [ i | (i,_) <- rngIdEnv env ]
92 > lookup_IdEnv :: IdEnv (Id, a) -> Id -> Maybe a
93 > lookup_IdEnv env key = case lookupIdEnv env key of
95 > Just (_,a) -> Just a
96 > -- end backward compat stuff
98 > type Closure = (IdEnvInt, Refs, AbFun)
100 > type AbVal = IdEnvClosure -> Closure
101 > data AbFun = Fun (Closure -> Closure)
103 > -- partain: speeding-up stuff
105 > type CaseBoundVars = IdSet
106 > noCaseBound = emptyUniqSet
107 > isCaseBound = elementOfUniqSet
108 > x `notCaseBound` y = not (isCaseBound x y)
109 > moreCaseBound :: CaseBoundVars -> [Id] -> CaseBoundVars
110 > moreCaseBound old new = old `unionUniqSets` mkUniqSet new
114 %----------------------------------------------------------------------------
115 \subsection{Environment lookup}
117 If the requested value is not in the environment, we return an unknown
118 value. Lookup is designed to be partially applied to a variable, and
119 repeatedly applied to different environments after that.
123 > = const (case updateInfoMaybe (getIdUpdateInfo v) of
124 > Nothing -> unknownClosure
125 > Just spec -> convertUpdateSpec spec)
127 > = \p -> case lookup_IdEnv p v of
129 > Nothing -> unknownClosure
131 %-----------------------------------------------------------------------------
132 Represent a list of references as an ordered list.
134 > mkRefs :: [Id] -> Refs
138 > noRefs = emptyUniqSet
140 > elemRefs = elementOfUniqSet
142 > merge :: [Refs] -> Refs
143 > merge xs = foldr merge2 emptyUniqSet xs
145 > merge2 :: Refs -> Refs -> Refs
146 > merge2 = unionUniqSets
148 %-----------------------------------------------------------------------------
149 \subsection{Some non-interesting values}
151 bottom will be used for abstract values that are not functions.
152 Hopefully its value will never be required!
155 > bottom = panic "Internal: (Update Analyser) bottom"
157 noClosure is a value that is definitely not a function (i.e. primitive
158 values and constructor applications). unknownClosure is a value about
159 which we have no information at all. This should occur rarely, but
160 could happen when an id is imported and the exporting module was not
161 compiled with the update analyser.
163 > noClosure, unknownClosure :: Closure
164 > noClosure = (null_IdEnv, noRefs, bottom)
165 > unknownClosure = (null_IdEnv, noRefs, dont_know noRefs)
167 dont_know is a black hole: it is something we know nothing about.
168 Applying dont_know to anything will generate a new dont_know that simply
169 contains more buried references.
171 > dont_know :: Refs -> AbFun
173 > = Fun (\(c,b,f) -> let b'' = dom_IdEnv c `merge2` b `merge2` b'
174 > in (null_IdEnv, b'', dont_know b''))
176 %-----------------------------------------------------------------------------
178 > getrefs :: IdEnvClosure -> [AbVal] -> Refs -> Refs
179 > getrefs p vs rest = foldr merge2 rest (getrefs' (map ($ p) vs))
182 > getrefs' ((c,b,_):rs) = dom_IdEnv c : b : getrefs' rs
184 %-----------------------------------------------------------------------------
186 udData is used when we are putting a list of closure references into a
187 data structure, or something else that we know nothing about.
189 > udData :: [StgArg] -> CaseBoundVars -> AbVal
191 > = \p -> (null_IdEnv, getrefs p local_ids noRefs, bottom)
192 > where local_ids = [ lookup v | (StgVarArg v) <- vs, v `notCaseBound` cvs ]
194 %-----------------------------------------------------------------------------
195 \subsection{Analysing an atom}
197 > udAtom :: CaseBoundVars -> StgArg -> AbVal
198 > udAtom cvs (StgVarArg v)
199 > | v `isCaseBound` cvs = const unknownClosure
200 > | otherwise = lookup v
202 > udAtom cvs _ = const noClosure
204 %-----------------------------------------------------------------------------
205 \subsection{Analysing an STG expression}
207 > ud :: StgExpr -- Expression to be analysed
208 > -> CaseBoundVars -- List of case-bound vars
209 > -> IdEnvClosure -- Current environment
210 > -> (StgExpr, AbVal) -- (New expression, abstract value)
212 > ud e@(StgPrim _ vs _) cvs p = (e, udData vs cvs)
213 > ud e@(StgCon _ vs _) cvs p = (e, udData vs cvs)
214 > ud e@(StgSCC ty lab a) cvs p = ud a cvs p =: \(a', abval_a) ->
215 > (StgSCC ty lab a', abval_a)
217 Here is application. The first thing to do is analyse the head, and
218 get an abstract function. Multiple applications are performed by using
219 a foldl with the function doApp. Closures are actually passed to the
220 abstract function iff the atom is a local variable.
222 I've left the type signature for doApp in to make things a bit clearer.
224 > ud e@(StgApp a atoms lvs) cvs p
227 > abval_atoms = map (udAtom cvs) atoms
228 > abval_a = udAtom cvs a
230 > let doApp :: Closure -> AbVal -> Closure
231 > doApp (c, b, Fun f) abval_atom =
232 > abval_atom p =: \e@(_,_,_) ->
233 > f e =: \(c', b', f') ->
234 > (combine_IdEnvs (+) c' c, b', f')
235 > in foldl doApp (abval_a p) abval_atoms
237 > ud (StgCase expr lve lva uniq alts) cvs p
238 > = ud expr cvs p =: \(expr', abval_selector) ->
239 > udAlt alts p =: \(alts', abval_alts) ->
242 > abval_selector p =: \(c, b, abfun_selector) ->
243 > abval_alts p =: \(cs, bs, abfun_alts) ->
244 > let bs' = b `merge2` bs in
245 > (combine_IdEnvs (+) c cs, bs', dont_know bs')
247 > (StgCase expr' lve lva uniq alts', abval_case)
250 > udAlt :: StgCaseAlts
252 > -> (StgCaseAlts, AbVal)
254 > udAlt (StgAlgAlts ty [alt] StgNoDefault) p
255 > = udAlgAlt p alt =: \(alt', abval) ->
256 > (StgAlgAlts ty [alt'] StgNoDefault, abval)
257 > udAlt (StgAlgAlts ty [] def) p
258 > = udDef def p =: \(def', abval) ->
259 > (StgAlgAlts ty [] def', abval)
260 > udAlt (StgAlgAlts ty alts def) p
261 > = udManyAlts alts def udAlgAlt (StgAlgAlts ty) p
262 > udAlt (StgPrimAlts ty [alt] StgNoDefault) p
263 > = udPrimAlt p alt =: \(alt', abval) ->
264 > (StgPrimAlts ty [alt'] StgNoDefault, abval)
265 > udAlt (StgPrimAlts ty [] def) p
266 > = udDef def p =: \(def', abval) ->
267 > (StgPrimAlts ty [] def', abval)
268 > udAlt (StgPrimAlts ty alts def) p
269 > = udManyAlts alts def udPrimAlt (StgPrimAlts ty) p
272 > = ud e cvs p =: \(e', v) -> ((l, e'), v)
274 > udAlgAlt p (id, vs, use_mask, e)
275 > = ud e (moreCaseBound cvs vs) p =: \(e', v) -> ((id, vs, use_mask, e'), v)
277 > udDef :: StgCaseDefault
279 > -> (StgCaseDefault, AbVal)
281 > udDef StgNoDefault p
282 > = (StgNoDefault, \p -> (null_IdEnv, noRefs, dont_know noRefs))
283 > udDef (StgBindDefault v is_used expr) p
284 > = ud expr (moreCaseBound cvs [v]) p =: \(expr', abval) ->
285 > (StgBindDefault v is_used expr', abval)
287 > udManyAlts alts def udalt stgalts p
288 > = udDef def p =: \(def', abval_def) ->
289 > unzip (map (udalt p) alts) =: \(alts', abvals_alts) ->
292 > abval_def p =: \(cd, bd, _) ->
293 > unzip3 (map ($ p) abvals_alts) =: \(cs, bs, _) ->
294 > let bs' = merge (bd:bs) in
295 > (foldr (combine_IdEnvs max) cd cs, bs', dont_know bs')
296 > in (stgalts alts' def', abval_alts)
298 The heart of the analysis: here we decide whether to make a specific
299 closure updatable or not, based on the results of analysing the body.
301 > ud (StgLet binds body) cvs p
302 > = udBinding binds cvs p =: \(binds', vs, abval1, abval2) ->
303 > abval1 p =: \(cs, p') ->
304 > grow_IdEnv p p' =: \p ->
305 > ud body cvs p =: \(body', abval_body) ->
306 > abval_body p =: \(c, b, abfun) ->
307 > tag b (combine_IdEnvs (+) cs c) binds' =: \tagged_binds ->
310 > = abval2 p =: \(c1, p') ->
311 > abval_body (grow_IdEnv p p') =: \(c2, b, abfun) ->
312 > (combine_IdEnvs (+) c1 c2, b, abfun)
314 > (StgLet tagged_binds body', abval)
316 %-----------------------------------------------------------------------------
317 \subsection{Analysing bindings}
319 For recursive sets of bindings we perform one iteration of a fixed
320 point algorithm, using (dont_know fv) as a safe approximation to the
321 real fixed point, where fv are the (mappings in the environment of
322 the) free variables of the function.
324 We'll return two new environments, one with the new closures in and
325 one without. There's no point in carrying around closures when their
326 respective bindings have already been analysed.
328 We don't need to find anything out about closures with arguments,
329 constructor closures etc.
331 > udBinding :: StgBinding
336 > IdEnvClosure -> (IdEnvInt, IdEnvClosure),
337 > IdEnvClosure -> (IdEnvInt, IdEnvClosure))
339 > udBinding (StgNonRec v rhs) cvs p
340 > = udRhs rhs cvs p =: \(rhs', abval) ->
341 > abval p =: \(c, b, abfun) ->
343 > abval_rhs a = \p ->
344 > abval p =: \(c, b, abfun) ->
345 > (c, unit_IdEnv v (a, b, abfun))
347 > StgRhsClosure _ _ _ Updatable [] _ -> unit_IdEnv v 1
349 > in (StgNonRec v rhs', [v], abval_rhs a, abval_rhs null_IdEnv)
351 > udBinding (StgRec ve) cvs p
352 > = (StgRec ve', [], abval_rhs, abval_rhs)
354 > (vs, ve', abvals) = unzip3 (map udBind ve)
355 > fv = (map lookup . filter (`notCaseBound` cvs) . concat . map collectfv) ve
359 > p' = grow_IdEnv (mk_IdEnv (vs `zip` (repeat closure))) p
360 > closure = (null_IdEnv, fv', dont_know fv')
361 > fv' = getrefs p fv vs'
362 > (cs, ps) = unzip (doRec vs abvals)
365 > doRec (v:vs) (abval:as)
366 > = abval p' =: \(c,b,abfun) ->
367 > (c, (v,(null_IdEnv, b, abfun))) : doRec vs as
370 > (foldr (combine_IdEnvs (+)) null_IdEnv cs, mk_IdEnv ps)
373 > = udRhs rhs cvs p =: \(rhs', abval) ->
374 > (v,(v,rhs'), abval)
376 > collectfv (_, StgRhsClosure _ _ fv _ _ _) = fv
377 > collectfv (_, StgRhsCon _ con args) = [ v | (StgVarArg v) <- args ]
379 %-----------------------------------------------------------------------------
380 \subsection{Analysing Right-Hand Sides}
382 > udRhs e@(StgRhsCon _ _ vs) cvs p = (e, udData vs cvs)
384 > udRhs (StgRhsClosure cc bi fv u [] body) cvs p
385 > = ud body cvs p =: \(body', abval_body) ->
386 > (StgRhsClosure cc bi fv u [] body', abval_body)
388 Here is the code for closures with arguments. A closure has a number
389 of arguments, which correspond to a set of nested lambda expressions.
390 We build up the analysis using foldr with the function doLam to
391 analyse each lambda expression.
393 > udRhs (StgRhsClosure cc bi fv u args body) cvs p
394 > = ud body cvs p =: \(body', abval_body) ->
396 > fv' = map lookup (filter (`notCaseBound` cvs) fv)
398 > foldr doLam (\b -> abval_body) args (getrefs p fv' noRefs) p
400 > (StgRhsClosure cc bi fv u args body', abval_rhs)
403 > doLam :: Id -> (Refs -> AbVal) -> Refs -> AbVal
406 > Fun (\x@(c',b',_) ->
407 > let b'' = dom_IdEnv c' `merge2` b' `merge2` b in
408 > f b'' (addOneTo_IdEnv p i x)))
410 %-----------------------------------------------------------------------------
411 \subsection{Adjusting Update flags}
413 The closure is tagged single entry iff it is used at most once, it is
414 not referenced from inside a data structure or function, and it has no
415 arguments (closures with arguments are re-entrant).
417 > tag :: Refs -> IdEnvInt -> StgBinding -> StgBinding
419 > tag b c r@(StgNonRec v (StgRhsClosure cc bi fv Updatable [] body))
420 > = if (v `notInRefs` b) && (lookupc c v <= 1)
421 > then -- trace "One!" (
422 > StgNonRec v (StgRhsClosure cc bi fv SingleEntry [] body)
425 > tag b c other = other
427 > lookupc c v = case lookup_IdEnv c v of
431 %-----------------------------------------------------------------------------
432 \subsection{Top Level analysis}
434 Should we tag top level closures? This could have good implications
435 for CAFs (i.e. they could be made non-updateable if only used once,
436 thus preventing a space leak).
438 > updateAnalyse :: [StgBinding] -> [StgBinding] {- Exported -}
440 > = udProgram bs null_IdEnv
442 > udProgram :: [StgBinding] -> IdEnvClosure -> [StgBinding]
443 > udProgram [] p = []
445 > = udBinding d noCaseBound p =: \(d', vs, _, abval_bind) ->
446 > abval_bind p =: \(_, p') ->
447 > grow_IdEnv p p' =: \p'' ->
448 > attachUpdateInfoToBinds d' p'' =: \d'' ->
449 > d'' : udProgram ds p''
451 %-----------------------------------------------------------------------------
452 \subsection{Exporting Update Information}
454 Convert the exported representation of a function's update function
455 into a real Closure value.
457 > convertUpdateSpec :: UpdateSpec -> Closure
458 > convertUpdateSpec = mkClosure null_IdEnv noRefs noRefs
460 > mkClosure :: IdEnvInt -> Refs -> Refs -> UpdateSpec -> Closure
462 > mkClosure c b b' [] = (c, b', dont_know b')
463 > mkClosure c b b' (0 : ns) = (null_IdEnv, b, Fun (\ _ -> mkClosure c b b' ns))
464 > mkClosure c b b' (1 : ns) = (null_IdEnv, b, Fun (\ (c',b'',f) ->
466 > (combine_IdEnvs (+) c c')
467 > (dom_IdEnv c' `merge2` b'' `merge2` b)
470 > mkClosure c b b' (n : ns) = (null_IdEnv, b, Fun (\ (c',b'',f) ->
472 > (dom_IdEnv c' `merge2` b'' `merge2` b)
473 > (dom_IdEnv c' `merge2` b'' `merge2` b')
476 Convert a Closure into a representation that can be placed in a .hi file.
478 > mkUpdateSpec :: Id -> Closure -> UpdateSpec
479 > mkUpdateSpec v f = {- removeSuperfluous2s -} (map countUses ids)
481 > (c,b,_) = foldl doApp f ids
482 > ids = map mkid (getBuiltinUniques arity)
483 > mkid u = mkSysLocal SLIT("upd") u noType mkUnknownSrcLoc
484 > countUses u = if u `elemRefs` b then 2 else min (lookupc c u) 2
485 > noType = panic "UpdAnal: no type!"
487 > doApp (c,b,Fun f) i
488 > = f (unit_IdEnv i 1, noRefs, dont_know noRefs) =: \(c',b',f') ->
489 > (combine_IdEnvs (+) c' c, b', f')
491 > (_,dict_tys,tau_ty) = (splitSigmaTy . idType) v
492 > (reg_arg_tys, _) = splitFunTy tau_ty
493 > arity = length dict_tys + length reg_arg_tys
495 removeSuperfluous2s = reverse . dropWhile (> 1) . reverse
497 %-----------------------------------------------------------------------------
498 \subsection{Attaching the update information to top-level bindings}
500 This is so that the information can later be retrieved for printing
501 out in the .hi file. This is not an ideal solution, however it will
504 > attachUpdateInfoToBinds b p
506 > StgNonRec v rhs -> StgNonRec (attachOne v) rhs
507 > StgRec bs -> StgRec [ (attachOne v, rhs) | (v, rhs) <- bs ]
511 > = let c = lookup v p in
513 > (mkUpdateInfo (mkUpdateSpec v c))
517 %-----------------------------------------------------------------------------