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 > IMP_Ubiq(){-uitous-}
18 > import Id ( SYN_IE(IdEnv), growIdEnv, addOneToIdEnv, combineIdEnvs, nullIdEnv,
19 > unitIdEnv, mkIdEnv, rngIdEnv, lookupIdEnv,
21 > getIdUpdateInfo, addIdUpdateInfo, mkSysLocal, idType, isImportedId,
22 > externallyVisibleId,
25 > import IdInfo ( UpdateInfo, SYN_IE(UpdateSpec), mkUpdateInfo, updateInfoMaybe )
26 > import Type ( splitFunTy, splitSigmaTy )
28 > import Unique ( getBuiltinUniques )
29 > import SrcLoc ( noSrcLoc )
30 > import Util ( panic )
33 %-----------------------------------------------------------------------------
34 \subsection{Reverse application}
36 This is used instead of lazy pattern bindings to avoid space leaks.
41 %-----------------------------------------------------------------------------
44 List of closure references
47 > x `notInRefs` y = not (x `elementOfUniqSet` y)
49 A closure value: environment of closures that are evaluated on entry,
50 a list of closures that are referenced from the result, and an
51 abstract value for the evaluated closure.
53 An IdEnv is used for the reference counts, as these environments are
54 combined often. A generic environment is used for the main environment
55 mapping closure names to values; as a common operation is extension of
56 this environment, this representation should be efficient.
58 > -- partain: funny synonyms to cope w/ the fact
59 > -- that IdEnvs know longer know what their keys are
60 > -- (94/05) ToDo: improve
61 > type IdEnvInt = IdEnv (Id, Int)
62 > type IdEnvClosure = IdEnv (Id, Closure)
64 > -- backward-compat functions
65 > null_IdEnv :: IdEnv (Id, a)
66 > null_IdEnv = nullIdEnv
68 > unit_IdEnv :: Id -> a -> IdEnv (Id, a)
69 > unit_IdEnv k v = unitIdEnv k (k, v)
71 > mk_IdEnv :: [(Id, a)] -> IdEnv (Id, a)
72 > mk_IdEnv pairs = mkIdEnv [ (k, (k,v)) | (k,v) <- pairs ]
74 > grow_IdEnv :: IdEnv (Id, a) -> IdEnv (Id, a) -> IdEnv (Id, a)
75 > grow_IdEnv env1 env2 = growIdEnv env1 env2
77 > addOneTo_IdEnv :: IdEnv (Id, a) -> Id -> a -> IdEnv (Id, a)
78 > addOneTo_IdEnv env k v = addOneToIdEnv env k (k, v)
80 > combine_IdEnvs :: (a->a->a) -> IdEnv (Id, a) -> IdEnv (Id, a) -> IdEnv (Id, a)
81 > combine_IdEnvs combiner env1 env2 = combineIdEnvs new_combiner env1 env2
83 > new_combiner (id, x) (_, y) = (id, combiner x y)
85 > dom_IdEnv :: IdEnv (Id, a) -> Refs
86 > dom_IdEnv env = mkUniqSet [ i | (i,_) <- rngIdEnv env ]
88 > lookup_IdEnv :: IdEnv (Id, a) -> Id -> Maybe a
89 > lookup_IdEnv env key = case lookupIdEnv env key of
91 > Just (_,a) -> Just a
92 > -- end backward compat stuff
94 > type Closure = (IdEnvInt, Refs, AbFun)
96 > type AbVal = IdEnvClosure -> Closure
97 > data AbFun = Fun (Closure -> Closure)
99 > -- partain: speeding-up stuff
101 > type CaseBoundVars = IdSet
102 > noCaseBound = emptyUniqSet
103 > isCaseBound = elementOfUniqSet
104 > x `notCaseBound` y = not (isCaseBound x y)
105 > moreCaseBound :: CaseBoundVars -> [Id] -> CaseBoundVars
106 > moreCaseBound old new = old `unionUniqSets` mkUniqSet new
110 %----------------------------------------------------------------------------
111 \subsection{Environment lookup}
113 If the requested value is not in the environment, we return an unknown
114 value. Lookup is designed to be partially applied to a variable, and
115 repeatedly applied to different environments after that.
119 > = const (case updateInfoMaybe (getIdUpdateInfo v) of
120 > Nothing -> unknownClosure
121 > Just spec -> convertUpdateSpec spec)
123 > = \p -> case lookup_IdEnv p v of
125 > Nothing -> unknownClosure
127 %-----------------------------------------------------------------------------
128 Represent a list of references as an ordered list.
130 > mkRefs :: [Id] -> Refs
134 > noRefs = emptyUniqSet
136 > elemRefs = elementOfUniqSet
138 > merge :: [Refs] -> Refs
139 > merge xs = foldr merge2 emptyUniqSet xs
141 > merge2 :: Refs -> Refs -> Refs
142 > merge2 = unionUniqSets
144 %-----------------------------------------------------------------------------
145 \subsection{Some non-interesting values}
147 bottom will be used for abstract values that are not functions.
148 Hopefully its value will never be required!
151 > bottom = panic "Internal: (Update Analyser) bottom"
153 noClosure is a value that is definitely not a function (i.e. primitive
154 values and constructor applications). unknownClosure is a value about
155 which we have no information at all. This should occur rarely, but
156 could happen when an id is imported and the exporting module was not
157 compiled with the update analyser.
159 > noClosure, unknownClosure :: Closure
160 > noClosure = (null_IdEnv, noRefs, bottom)
161 > unknownClosure = (null_IdEnv, noRefs, dont_know noRefs)
163 dont_know is a black hole: it is something we know nothing about.
164 Applying dont_know to anything will generate a new dont_know that simply
165 contains more buried references.
167 > dont_know :: Refs -> AbFun
169 > = Fun (\(c,b,f) -> let b'' = dom_IdEnv c `merge2` b `merge2` b'
170 > in (null_IdEnv, b'', dont_know b''))
172 %-----------------------------------------------------------------------------
174 > getrefs :: IdEnvClosure -> [AbVal] -> Refs -> Refs
175 > getrefs p vs rest = foldr merge2 rest (getrefs' (map ($ p) vs))
178 > getrefs' ((c,b,_):rs) = dom_IdEnv c : b : getrefs' rs
180 %-----------------------------------------------------------------------------
182 udData is used when we are putting a list of closure references into a
183 data structure, or something else that we know nothing about.
185 > udData :: [StgArg] -> CaseBoundVars -> AbVal
187 > = \p -> (null_IdEnv, getrefs p local_ids noRefs, bottom)
188 > where local_ids = [ lookup v | (StgVarArg v) <- vs, v `notCaseBound` cvs ]
190 %-----------------------------------------------------------------------------
191 \subsection{Analysing an atom}
193 > udAtom :: CaseBoundVars -> StgArg -> AbVal
194 > udAtom cvs (StgVarArg v)
195 > | v `isCaseBound` cvs = const unknownClosure
196 > | otherwise = lookup v
198 > udAtom cvs _ = const noClosure
200 %-----------------------------------------------------------------------------
201 \subsection{Analysing an STG expression}
203 > ud :: StgExpr -- Expression to be analysed
204 > -> CaseBoundVars -- List of case-bound vars
205 > -> IdEnvClosure -- Current environment
206 > -> (StgExpr, AbVal) -- (New expression, abstract value)
208 > ud e@(StgPrim _ vs _) cvs p = (e, udData vs cvs)
209 > ud e@(StgCon _ vs _) cvs p = (e, udData vs cvs)
210 > ud e@(StgSCC ty lab a) cvs p = ud a cvs p =: \(a', abval_a) ->
211 > (StgSCC ty lab a', abval_a)
213 Here is application. The first thing to do is analyse the head, and
214 get an abstract function. Multiple applications are performed by using
215 a foldl with the function doApp. Closures are actually passed to the
216 abstract function iff the atom is a local variable.
218 I've left the type signature for doApp in to make things a bit clearer.
220 > ud e@(StgApp a atoms lvs) cvs p
223 > abval_atoms = map (udAtom cvs) atoms
224 > abval_a = udAtom cvs a
226 > let doApp :: Closure -> AbVal -> Closure
227 > doApp (c, b, Fun f) abval_atom =
228 > abval_atom p =: \e@(_,_,_) ->
229 > f e =: \(c', b', f') ->
230 > (combine_IdEnvs (+) c' c, b', f')
231 > in foldl doApp (abval_a p) abval_atoms
233 > ud (StgCase expr lve lva uniq alts) cvs p
234 > = ud expr cvs p =: \(expr', abval_selector) ->
235 > udAlt alts p =: \(alts', abval_alts) ->
238 > abval_selector p =: \(c, b, abfun_selector) ->
239 > abval_alts p =: \(cs, bs, abfun_alts) ->
240 > let bs' = b `merge2` bs in
241 > (combine_IdEnvs (+) c cs, bs', dont_know bs')
243 > (StgCase expr' lve lva uniq alts', abval_case)
246 > udAlt :: StgCaseAlts
248 > -> (StgCaseAlts, AbVal)
250 > udAlt (StgAlgAlts ty [alt] StgNoDefault) p
251 > = udAlgAlt p alt =: \(alt', abval) ->
252 > (StgAlgAlts ty [alt'] StgNoDefault, abval)
253 > udAlt (StgAlgAlts ty [] def) p
254 > = udDef def p =: \(def', abval) ->
255 > (StgAlgAlts ty [] def', abval)
256 > udAlt (StgAlgAlts ty alts def) p
257 > = udManyAlts alts def udAlgAlt (StgAlgAlts ty) p
258 > udAlt (StgPrimAlts ty [alt] StgNoDefault) p
259 > = udPrimAlt p alt =: \(alt', abval) ->
260 > (StgPrimAlts ty [alt'] StgNoDefault, abval)
261 > udAlt (StgPrimAlts ty [] def) p
262 > = udDef def p =: \(def', abval) ->
263 > (StgPrimAlts ty [] def', abval)
264 > udAlt (StgPrimAlts ty alts def) p
265 > = udManyAlts alts def udPrimAlt (StgPrimAlts ty) p
268 > = ud e cvs p =: \(e', v) -> ((l, e'), v)
270 > udAlgAlt p (id, vs, use_mask, e)
271 > = ud e (moreCaseBound cvs vs) p =: \(e', v) -> ((id, vs, use_mask, e'), v)
273 > udDef :: StgCaseDefault
275 > -> (StgCaseDefault, AbVal)
277 > udDef StgNoDefault p
278 > = (StgNoDefault, \p -> (null_IdEnv, noRefs, dont_know noRefs))
279 > udDef (StgBindDefault v is_used expr) p
280 > = ud expr (moreCaseBound cvs [v]) p =: \(expr', abval) ->
281 > (StgBindDefault v is_used expr', abval)
283 > udManyAlts alts def udalt stgalts p
284 > = udDef def p =: \(def', abval_def) ->
285 > unzip (map (udalt p) alts) =: \(alts', abvals_alts) ->
288 > abval_def p =: \(cd, bd, _) ->
289 > unzip3 (map ($ p) abvals_alts) =: \(cs, bs, _) ->
290 > let bs' = merge (bd:bs) in
291 > (foldr (combine_IdEnvs max) cd cs, bs', dont_know bs')
292 > in (stgalts alts' def', abval_alts)
294 The heart of the analysis: here we decide whether to make a specific
295 closure updatable or not, based on the results of analysing the body.
297 > ud (StgLet binds body) cvs p
298 > = udBinding binds cvs p =: \(binds', vs, abval1, abval2) ->
299 > abval1 p =: \(cs, p') ->
300 > grow_IdEnv p p' =: \p ->
301 > ud body cvs p =: \(body', abval_body) ->
302 > abval_body p =: \(c, b, abfun) ->
303 > tag b (combine_IdEnvs (+) cs c) binds' =: \tagged_binds ->
306 > = abval2 p =: \(c1, p') ->
307 > abval_body (grow_IdEnv p p') =: \(c2, b, abfun) ->
308 > (combine_IdEnvs (+) c1 c2, b, abfun)
310 > (StgLet tagged_binds body', abval)
312 %-----------------------------------------------------------------------------
313 \subsection{Analysing bindings}
315 For recursive sets of bindings we perform one iteration of a fixed
316 point algorithm, using (dont_know fv) as a safe approximation to the
317 real fixed point, where fv are the (mappings in the environment of
318 the) free variables of the function.
320 We'll return two new environments, one with the new closures in and
321 one without. There's no point in carrying around closures when their
322 respective bindings have already been analysed.
324 We don't need to find anything out about closures with arguments,
325 constructor closures etc.
327 > udBinding :: StgBinding
332 > IdEnvClosure -> (IdEnvInt, IdEnvClosure),
333 > IdEnvClosure -> (IdEnvInt, IdEnvClosure))
335 > udBinding (StgNonRec v rhs) cvs p
336 > = udRhs rhs cvs p =: \(rhs', abval) ->
337 > abval p =: \(c, b, abfun) ->
339 > abval_rhs a = \p ->
340 > abval p =: \(c, b, abfun) ->
341 > (c, unit_IdEnv v (a, b, abfun))
343 > StgRhsClosure _ _ _ Updatable [] _ -> unit_IdEnv v 1
345 > in (StgNonRec v rhs', [v], abval_rhs a, abval_rhs null_IdEnv)
347 > udBinding (StgRec ve) cvs p
348 > = (StgRec ve', [], abval_rhs, abval_rhs)
350 > (vs, ve', abvals) = unzip3 (map udBind ve)
351 > fv = (map lookup . filter (`notCaseBound` cvs) . concat . map collectfv) ve
355 > p' = grow_IdEnv (mk_IdEnv (vs `zip` (repeat closure))) p
356 > closure = (null_IdEnv, fv', dont_know fv')
357 > fv' = getrefs p fv vs'
358 > (cs, ps) = unzip (doRec vs abvals)
361 > doRec (v:vs) (abval:as)
362 > = abval p' =: \(c,b,abfun) ->
363 > (c, (v,(null_IdEnv, b, abfun))) : doRec vs as
366 > (foldr (combine_IdEnvs (+)) null_IdEnv cs, mk_IdEnv ps)
369 > = udRhs rhs cvs p =: \(rhs', abval) ->
370 > (v,(v,rhs'), abval)
372 > collectfv (_, StgRhsClosure _ _ fv _ _ _) = fv
373 > collectfv (_, StgRhsCon _ con args) = [ v | (StgVarArg v) <- args ]
375 %-----------------------------------------------------------------------------
376 \subsection{Analysing Right-Hand Sides}
378 > udRhs e@(StgRhsCon _ _ vs) cvs p = (e, udData vs cvs)
380 > udRhs (StgRhsClosure cc bi fv u [] body) cvs p
381 > = ud body cvs p =: \(body', abval_body) ->
382 > (StgRhsClosure cc bi fv u [] body', abval_body)
384 Here is the code for closures with arguments. A closure has a number
385 of arguments, which correspond to a set of nested lambda expressions.
386 We build up the analysis using foldr with the function doLam to
387 analyse each lambda expression.
389 > udRhs (StgRhsClosure cc bi fv u args body) cvs p
390 > = ud body cvs p =: \(body', abval_body) ->
392 > fv' = map lookup (filter (`notCaseBound` cvs) fv)
394 > foldr doLam (\b -> abval_body) args (getrefs p fv' noRefs) p
396 > (StgRhsClosure cc bi fv u args body', abval_rhs)
399 > doLam :: Id -> (Refs -> AbVal) -> Refs -> AbVal
402 > Fun (\x@(c',b',_) ->
403 > let b'' = dom_IdEnv c' `merge2` b' `merge2` b in
404 > f b'' (addOneTo_IdEnv p i x)))
406 %-----------------------------------------------------------------------------
407 \subsection{Adjusting Update flags}
409 The closure is tagged single entry iff it is used at most once, it is
410 not referenced from inside a data structure or function, and it has no
411 arguments (closures with arguments are re-entrant).
413 > tag :: Refs -> IdEnvInt -> StgBinding -> StgBinding
415 > tag b c r@(StgNonRec v (StgRhsClosure cc bi fv Updatable [] body))
416 > = if (v `notInRefs` b) && (lookupc c v <= 1)
417 > then -- trace "One!" (
418 > StgNonRec v (StgRhsClosure cc bi fv SingleEntry [] body)
421 > tag b c other = other
423 > lookupc c v = case lookup_IdEnv c v of
427 %-----------------------------------------------------------------------------
428 \subsection{Top Level analysis}
430 Should we tag top level closures? This could have good implications
431 for CAFs (i.e. they could be made non-updateable if only used once,
432 thus preventing a space leak).
434 > updateAnalyse :: [StgBinding] -> [StgBinding] {- Exported -}
436 > = udProgram bs null_IdEnv
438 > udProgram :: [StgBinding] -> IdEnvClosure -> [StgBinding]
439 > udProgram [] p = []
441 > = udBinding d noCaseBound p =: \(d', vs, _, abval_bind) ->
442 > abval_bind p =: \(_, p') ->
443 > grow_IdEnv p p' =: \p'' ->
444 > attachUpdateInfoToBinds d' p'' =: \d'' ->
445 > d'' : udProgram ds p''
447 %-----------------------------------------------------------------------------
448 \subsection{Exporting Update Information}
450 Convert the exported representation of a function's update function
451 into a real Closure value.
453 > convertUpdateSpec :: UpdateSpec -> Closure
454 > convertUpdateSpec = mkClosure null_IdEnv noRefs noRefs
456 > mkClosure :: IdEnvInt -> Refs -> Refs -> UpdateSpec -> Closure
458 > mkClosure c b b' [] = (c, b', dont_know b')
459 > mkClosure c b b' (0 : ns) = (null_IdEnv, b, Fun (\ _ -> mkClosure c b b' ns))
460 > mkClosure c b b' (1 : ns) = (null_IdEnv, b, Fun (\ (c',b'',f) ->
462 > (combine_IdEnvs (+) c c')
463 > (dom_IdEnv c' `merge2` b'' `merge2` b)
466 > mkClosure c b b' (n : ns) = (null_IdEnv, b, Fun (\ (c',b'',f) ->
468 > (dom_IdEnv c' `merge2` b'' `merge2` b)
469 > (dom_IdEnv c' `merge2` b'' `merge2` b')
472 Convert a Closure into a representation that can be placed in a .hi file.
474 > mkUpdateSpec :: Id -> Closure -> UpdateSpec
475 > mkUpdateSpec v f = {- removeSuperfluous2s -} (map countUses ids)
477 > (c,b,_) = foldl doApp f ids
478 > ids = map mkid (getBuiltinUniques arity)
479 > mkid u = mkSysLocal SLIT("upd") u noType noSrcLoc
480 > countUses u = if u `elemRefs` b then 2 else min (lookupc c u) 2
481 > noType = panic "UpdAnal: no type!"
483 > doApp (c,b,Fun f) i
484 > = f (unit_IdEnv i 1, noRefs, dont_know noRefs) =: \(c',b',f') ->
485 > (combine_IdEnvs (+) c' c, b', f')
487 > (_,dict_tys,tau_ty) = (splitSigmaTy . idType) v
488 > (reg_arg_tys, _) = splitFunTy tau_ty
489 > arity = length dict_tys + length reg_arg_tys
491 removeSuperfluous2s = reverse . dropWhile (> 1) . reverse
493 %-----------------------------------------------------------------------------
494 \subsection{Attaching the update information to top-level bindings}
496 This is so that the information can later be retrieved for printing
497 out in the .hi file. This is not an ideal solution, however it will
500 > attachUpdateInfoToBinds b p
502 > StgNonRec v rhs -> StgNonRec (attachOne v) rhs
503 > StgRec bs -> StgRec [ (attachOne v, rhs) | (v, rhs) <- bs ]
506 > | externallyVisibleId v
507 > = let c = lookup v p in
509 > (mkUpdateInfo (mkUpdateSpec v c))
512 %-----------------------------------------------------------------------------