1 \section{Update Avoidance Analyser} -*-haskell-literate-*-
3 (c) Simon Marlow, Andre Santos 1992-1993
4 (c) The AQUA Project, Glasgow University, 1995
6 %-----------------------------------------------------------------------------
7 \subsection{Module Interface}
10 #include "HsVersions.h"
13 > module UpdAnal ( updateAnalyse ) where
17 > import AbsUniType ( splitTyArgs, splitType, Class, TyVarTemplate,
23 > import Outputable ( isExported )
25 > import SrcLoc ( mkUnknownSrcLoc )
28 > import Unique ( getBuiltinUniques )
31 %-----------------------------------------------------------------------------
32 \subsection{Reverse application}
34 This is used instead of lazy pattern bindings to avoid space leaks.
39 %-----------------------------------------------------------------------------
42 List of closure references
45 > x `notInRefs` y = not (x `elementOfUniqSet` y)
47 A closure value: environment of closures that are evaluated on entry,
48 a list of closures that are referenced from the result, and an
49 abstract value for the evaluated closure.
51 An IdEnv is used for the reference counts, as these environments are
52 combined often. A generic environment is used for the main environment
53 mapping closure names to values; as a common operation is extension of
54 this environment, this representation should be efficient.
56 > -- partain: funny synonyms to cope w/ the fact
57 > -- that IdEnvs know longer know what their keys are
58 > -- (94/05) ToDo: improve
59 > type IdEnvInt = IdEnv (Id, Int)
60 > type IdEnvClosure = IdEnv (Id, Closure)
62 > -- backward-compat functions
63 > null_IdEnv :: IdEnv (Id, a)
64 > null_IdEnv = nullIdEnv
66 > unit_IdEnv :: Id -> a -> IdEnv (Id, a)
67 > unit_IdEnv k v = unitIdEnv k (k, v)
69 > mk_IdEnv :: [(Id, a)] -> IdEnv (Id, a)
70 > mk_IdEnv pairs = mkIdEnv [ (k, (k,v)) | (k,v) <- pairs ]
72 > grow_IdEnv :: IdEnv (Id, a) -> IdEnv (Id, a) -> IdEnv (Id, a)
73 > grow_IdEnv env1 env2 = growIdEnv env1 env2
75 > addOneTo_IdEnv :: IdEnv (Id, a) -> Id -> a -> IdEnv (Id, a)
76 > addOneTo_IdEnv env k v = addOneToIdEnv env k (k, v)
78 > combine_IdEnvs :: (a->a->a) -> IdEnv (Id, a) -> IdEnv (Id, a) -> IdEnv (Id, a)
79 > combine_IdEnvs combiner env1 env2 = combineIdEnvs new_combiner env1 env2
81 > new_combiner (id, x) (_, y) = (id, combiner x y)
83 > dom_IdEnv :: IdEnv (Id, a) -> Refs
84 > dom_IdEnv env = mkUniqSet [ i | (i,_) <- rngIdEnv env ]
86 > lookup_IdEnv :: IdEnv (Id, a) -> Id -> Maybe a
87 > lookup_IdEnv env key = case lookupIdEnv env key of
89 > Just (_,a) -> Just a
90 > -- end backward compat stuff
92 > type Closure = (IdEnvInt, Refs, AbFun)
94 > type AbVal = IdEnvClosure -> Closure
95 > data AbFun = Fun (Closure -> Closure)
97 > -- partain: speeding-up stuff
99 > type CaseBoundVars = IdSet
100 > noCaseBound = emptyUniqSet
101 > isCaseBound = elementOfUniqSet
102 > x `notCaseBound` y = not (isCaseBound x y)
103 > moreCaseBound :: CaseBoundVars -> [Id] -> CaseBoundVars
104 > moreCaseBound old new = old `unionUniqSets` mkUniqSet new
108 %----------------------------------------------------------------------------
109 \subsection{Environment lookup}
111 If the requested value is not in the environment, we return an unknown
112 value. Lookup is designed to be partially applied to a variable, and
113 repeatedly applied to different environments after that.
117 > = const (case updateInfoMaybe (getIdUpdateInfo v) of
118 > Nothing -> unknownClosure
119 > Just spec -> convertUpdateSpec spec)
121 > = \p -> case lookup_IdEnv p v of
123 > Nothing -> unknownClosure
125 %-----------------------------------------------------------------------------
126 Represent a list of references as an ordered list.
128 > mkRefs :: [Id] -> Refs
132 > noRefs = emptyUniqSet
134 > elemRefs = elementOfUniqSet
136 > merge :: [Refs] -> Refs
137 > merge xs = foldr merge2 emptyUniqSet xs
139 > merge2 :: Refs -> Refs -> Refs
140 > merge2 = unionUniqSets
142 %-----------------------------------------------------------------------------
143 \subsection{Some non-interesting values}
145 bottom will be used for abstract values that are not functions.
146 Hopefully its value will never be required!
149 > bottom = panic "Internal: (Update Analyser) bottom"
151 noClosure is a value that is definitely not a function (i.e. primitive
152 values and constructor applications). unknownClosure is a value about
153 which we have no information at all. This should occur rarely, but
154 could happen when an id is imported and the exporting module was not
155 compiled with the update analyser.
157 > noClosure, unknownClosure :: Closure
158 > noClosure = (null_IdEnv, noRefs, bottom)
159 > unknownClosure = (null_IdEnv, noRefs, dont_know noRefs)
161 dont_know is a black hole: it is something we know nothing about.
162 Applying dont_know to anything will generate a new dont_know that simply
163 contains more buried references.
165 > dont_know :: Refs -> AbFun
167 > = Fun (\(c,b,f) -> let b'' = dom_IdEnv c `merge2` b `merge2` b'
168 > in (null_IdEnv, b'', dont_know b''))
170 %-----------------------------------------------------------------------------
172 > getrefs :: IdEnvClosure -> [AbVal] -> Refs -> Refs
173 > getrefs p vs rest = foldr merge2 rest (getrefs' (map ($ p) vs))
176 > getrefs' ((c,b,_):rs) = dom_IdEnv c : b : getrefs' rs
178 %-----------------------------------------------------------------------------
180 udData is used when we are putting a list of closure references into a
181 data structure, or something else that we know nothing about.
183 > udData :: [PlainStgAtom] -> CaseBoundVars -> AbVal
185 > = \p -> (null_IdEnv, getrefs p local_ids noRefs, bottom)
186 > where local_ids = [ lookup v | (StgVarAtom v) <- vs, v `notCaseBound` cvs ]
188 %-----------------------------------------------------------------------------
189 \subsection{Analysing an atom}
191 > udAtom :: CaseBoundVars -> PlainStgAtom -> AbVal
192 > udAtom cvs (StgVarAtom v)
193 > | v `isCaseBound` cvs = const unknownClosure
194 > | otherwise = lookup v
196 > udAtom cvs _ = const noClosure
198 %-----------------------------------------------------------------------------
199 \subsection{Analysing an STG expression}
201 > ud :: PlainStgExpr -- Expression to be analysed
202 > -> CaseBoundVars -- List of case-bound vars
203 > -> IdEnvClosure -- Current environment
204 > -> (PlainStgExpr, AbVal) -- (New expression, abstract value)
206 > ud e@(StgPrimApp _ vs _) cvs p = (e, udData vs cvs)
207 > ud e@(StgConApp _ vs _) cvs p = (e, udData vs cvs)
208 > ud e@(StgSCC ty lab a) cvs p = ud a cvs p =: \(a', abval_a) ->
209 > (StgSCC ty lab a', abval_a)
211 Here is application. The first thing to do is analyse the head, and
212 get an abstract function. Multiple applications are performed by using
213 a foldl with the function doApp. Closures are actually passed to the
214 abstract function iff the atom is a local variable.
216 I've left the type signature for doApp in to make things a bit clearer.
218 > ud e@(StgApp a atoms lvs) cvs p
221 > abval_atoms = map (udAtom cvs) atoms
222 > abval_a = udAtom cvs a
224 > let doApp :: Closure -> AbVal -> Closure
225 > doApp (c, b, Fun f) abval_atom =
226 > abval_atom p =: \e@(_,_,_) ->
227 > f e =: \(c', b', f') ->
228 > (combine_IdEnvs (+) c' c, b', f')
229 > in foldl doApp (abval_a p) abval_atoms
231 > ud (StgCase expr lve lva uniq alts) cvs p
232 > = ud expr cvs p =: \(expr', abval_selector) ->
233 > udAlt alts p =: \(alts', abval_alts) ->
236 > abval_selector p =: \(c, b, abfun_selector) ->
237 > abval_alts p =: \(cs, bs, abfun_alts) ->
238 > let bs' = b `merge2` bs in
239 > (combine_IdEnvs (+) c cs, bs', dont_know bs')
241 > (StgCase expr' lve lva uniq alts', abval_case)
244 > udAlt :: PlainStgCaseAlternatives
246 > -> (PlainStgCaseAlternatives, AbVal)
248 > udAlt (StgAlgAlts ty [alt] StgNoDefault) p
249 > = udAlgAlt p alt =: \(alt', abval) ->
250 > (StgAlgAlts ty [alt'] StgNoDefault, abval)
251 > udAlt (StgAlgAlts ty [] def) p
252 > = udDef def p =: \(def', abval) ->
253 > (StgAlgAlts ty [] def', abval)
254 > udAlt (StgAlgAlts ty alts def) p
255 > = udManyAlts alts def udAlgAlt (StgAlgAlts ty) p
256 > udAlt (StgPrimAlts ty [alt] StgNoDefault) p
257 > = udPrimAlt p alt =: \(alt', abval) ->
258 > (StgPrimAlts ty [alt'] StgNoDefault, abval)
259 > udAlt (StgPrimAlts ty [] def) p
260 > = udDef def p =: \(def', abval) ->
261 > (StgPrimAlts ty [] def', abval)
262 > udAlt (StgPrimAlts ty alts def) p
263 > = udManyAlts alts def udPrimAlt (StgPrimAlts ty) p
266 > = ud e cvs p =: \(e', v) -> ((l, e'), v)
268 > udAlgAlt p (id, vs, use_mask, e)
269 > = ud e (moreCaseBound cvs vs) p =: \(e', v) -> ((id, vs, use_mask, e'), v)
271 > udDef :: PlainStgCaseDefault
273 > -> (PlainStgCaseDefault, AbVal)
275 > udDef StgNoDefault p
276 > = (StgNoDefault, \p -> (null_IdEnv, noRefs, dont_know noRefs))
277 > udDef (StgBindDefault v is_used expr) p
278 > = ud expr (moreCaseBound cvs [v]) p =: \(expr', abval) ->
279 > (StgBindDefault v is_used expr', abval)
281 > udManyAlts alts def udalt stgalts p
282 > = udDef def p =: \(def', abval_def) ->
283 > unzip (map (udalt p) alts) =: \(alts', abvals_alts) ->
286 > abval_def p =: \(cd, bd, _) ->
287 > unzip3 (map ($ p) abvals_alts) =: \(cs, bs, _) ->
288 > let bs' = merge (bd:bs) in
289 > (foldr (combine_IdEnvs max) cd cs, bs', dont_know bs')
290 > in (stgalts alts' def', abval_alts)
292 The heart of the analysis: here we decide whether to make a specific
293 closure updatable or not, based on the results of analysing the body.
295 > ud (StgLet binds body) cvs p
296 > = udBinding binds cvs p =: \(binds', vs, abval1, abval2) ->
297 > abval1 p =: \(cs, p') ->
298 > grow_IdEnv p p' =: \p ->
299 > ud body cvs p =: \(body', abval_body) ->
300 > abval_body p =: \(c, b, abfun) ->
301 > tag b (combine_IdEnvs (+) cs c) binds' =: \tagged_binds ->
304 > = abval2 p =: \(c1, p') ->
305 > abval_body (grow_IdEnv p p') =: \(c2, b, abfun) ->
306 > (combine_IdEnvs (+) c1 c2, b, abfun)
308 > (StgLet tagged_binds body', abval)
310 %-----------------------------------------------------------------------------
311 \subsection{Analysing bindings}
313 For recursive sets of bindings we perform one iteration of a fixed
314 point algorithm, using (dont_know fv) as a safe approximation to the
315 real fixed point, where fv are the (mappings in the environment of
316 the) free variables of the function.
318 We'll return two new environments, one with the new closures in and
319 one without. There's no point in carrying around closures when their
320 respective bindings have already been analysed.
322 We don't need to find anything out about closures with arguments,
323 constructor closures etc.
325 > udBinding :: PlainStgBinding
328 > -> (PlainStgBinding,
330 > IdEnvClosure -> (IdEnvInt, IdEnvClosure),
331 > IdEnvClosure -> (IdEnvInt, IdEnvClosure))
333 > udBinding (StgNonRec v rhs) cvs p
334 > = udRhs rhs cvs p =: \(rhs', abval) ->
335 > abval p =: \(c, b, abfun) ->
337 > abval_rhs a = \p ->
338 > abval p =: \(c, b, abfun) ->
339 > (c, unit_IdEnv v (a, b, abfun))
341 > StgRhsClosure _ _ _ Updatable [] _ -> unit_IdEnv v 1
343 > in (StgNonRec v rhs', [v], abval_rhs a, abval_rhs null_IdEnv)
345 > udBinding (StgRec ve) cvs p
346 > = (StgRec ve', [], abval_rhs, abval_rhs)
348 > (vs, ve', abvals) = unzip3 (map udBind ve)
349 > fv = (map lookup . filter (`notCaseBound` cvs) . concat . map collectfv) ve
353 > p' = grow_IdEnv (mk_IdEnv (vs `zip` (repeat closure))) p
354 > closure = (null_IdEnv, fv', dont_know fv')
355 > fv' = getrefs p fv vs'
356 > (cs, ps) = unzip (doRec vs abvals)
359 > doRec (v:vs) (abval:as)
360 > = abval p' =: \(c,b,abfun) ->
361 > (c, (v,(null_IdEnv, b, abfun))) : doRec vs as
364 > (foldr (combine_IdEnvs (+)) null_IdEnv cs, mk_IdEnv ps)
367 > = udRhs rhs cvs p =: \(rhs', abval) ->
368 > (v,(v,rhs'), abval)
370 > collectfv (_, StgRhsClosure _ _ fv _ _ _) = fv
371 > collectfv (_, StgRhsCon _ con args) = [ v | (StgVarAtom v) <- args ]
373 %-----------------------------------------------------------------------------
374 \subsection{Analysing Right-Hand Sides}
376 > udRhs e@(StgRhsCon _ _ vs) cvs p = (e, udData vs cvs)
378 > udRhs (StgRhsClosure cc bi fv u [] body) cvs p
379 > = ud body cvs p =: \(body', abval_body) ->
380 > (StgRhsClosure cc bi fv u [] body', abval_body)
382 Here is the code for closures with arguments. A closure has a number
383 of arguments, which correspond to a set of nested lambda expressions.
384 We build up the analysis using foldr with the function doLam to
385 analyse each lambda expression.
387 > udRhs (StgRhsClosure cc bi fv u args body) cvs p
388 > = ud body cvs p =: \(body', abval_body) ->
390 > fv' = map lookup (filter (`notCaseBound` cvs) fv)
392 > foldr doLam (\b -> abval_body) args (getrefs p fv' noRefs) p
394 > (StgRhsClosure cc bi fv u args body', abval_rhs)
397 > doLam :: Id -> (Refs -> AbVal) -> Refs -> AbVal
400 > Fun (\x@(c',b',_) ->
401 > let b'' = dom_IdEnv c' `merge2` b' `merge2` b in
402 > f b'' (addOneTo_IdEnv p i x)))
404 %-----------------------------------------------------------------------------
405 \subsection{Adjusting Update flags}
407 The closure is tagged single entry iff it is used at most once, it is
408 not referenced from inside a data structure or function, and it has no
409 arguments (closures with arguments are re-entrant).
411 > tag :: Refs -> IdEnvInt -> PlainStgBinding -> PlainStgBinding
413 > tag b c r@(StgNonRec v (StgRhsClosure cc bi fv Updatable [] body))
414 > = if (v `notInRefs` b) && (lookupc c v <= 1)
415 > then -- trace "One!" (
416 > StgNonRec v (StgRhsClosure cc bi fv SingleEntry [] body)
419 > tag b c other = other
421 > lookupc c v = case lookup_IdEnv c v of
425 %-----------------------------------------------------------------------------
426 \subsection{Top Level analysis}
428 Should we tag top level closures? This could have good implications
429 for CAFs (i.e. they could be made non-updateable if only used once,
430 thus preventing a space leak).
432 > updateAnalyse :: PlainStgProgram -> PlainStgProgram {- Exported -}
434 > = udProgram bs null_IdEnv
436 > udProgram :: PlainStgProgram -> IdEnvClosure -> PlainStgProgram
437 > udProgram [] p = []
439 > = udBinding d noCaseBound p =: \(d', vs, _, abval_bind) ->
440 > abval_bind p =: \(_, p') ->
441 > grow_IdEnv p p' =: \p'' ->
442 > attachUpdateInfoToBinds d' p'' =: \d'' ->
443 > d'' : udProgram ds p''
445 %-----------------------------------------------------------------------------
446 \subsection{Exporting Update Information}
448 Convert the exported representation of a function's update function
449 into a real Closure value.
451 > convertUpdateSpec :: UpdateSpec -> Closure
452 > convertUpdateSpec = mkClosure null_IdEnv noRefs noRefs
454 > mkClosure :: IdEnvInt -> Refs -> Refs -> UpdateSpec -> Closure
456 > mkClosure c b b' [] = (c, b', dont_know b')
457 > mkClosure c b b' (0 : ns) = (null_IdEnv, b, Fun (\ _ -> mkClosure c b b' ns))
458 > mkClosure c b b' (1 : ns) = (null_IdEnv, b, Fun (\ (c',b'',f) ->
460 > (combine_IdEnvs (+) c c')
461 > (dom_IdEnv c' `merge2` b'' `merge2` b)
464 > mkClosure c b b' (n : ns) = (null_IdEnv, b, Fun (\ (c',b'',f) ->
466 > (dom_IdEnv c' `merge2` b'' `merge2` b)
467 > (dom_IdEnv c' `merge2` b'' `merge2` b')
470 Convert a Closure into a representation that can be placed in a .hi file.
472 > mkUpdateSpec :: Id -> Closure -> UpdateSpec
473 > mkUpdateSpec v f = {- removeSuperfluous2s -} (map countUses ids)
475 > (c,b,_) = foldl doApp f ids
476 > ids = map mkid (getBuiltinUniques arity)
477 > mkid u = mkSysLocal SLIT("upd") u noType mkUnknownSrcLoc
478 > countUses u = if u `elemRefs` b then 2 else min (lookupc c u) 2
479 > noType = panic "UpdAnal: no type!"
481 > doApp (c,b,Fun f) i
482 > = f (unit_IdEnv i 1, noRefs, dont_know noRefs) =: \(c',b',f') ->
483 > (combine_IdEnvs (+) c' c, b', f')
485 > (_,dict_tys,tau_ty) = (splitType . getIdUniType) v
486 > (reg_arg_tys, _) = splitTyArgs tau_ty
487 > arity = length dict_tys + length reg_arg_tys
489 removeSuperfluous2s = reverse . dropWhile (> 1) . reverse
491 %-----------------------------------------------------------------------------
492 \subsection{Attaching the update information to top-level bindings}
494 This is so that the information can later be retrieved for printing
495 out in the .hi file. This is not an ideal solution, however it will
498 > attachUpdateInfoToBinds b p
500 > StgNonRec v rhs -> StgNonRec (attachOne v) rhs
501 > StgRec bs -> StgRec [ (attachOne v, rhs) | (v, rhs) <- bs ]
505 > = let c = lookup v p in
507 > (mkUpdateInfo (mkUpdateSpec v c))
510 %-----------------------------------------------------------------------------