1 module Exitify ( exitifyProgram ) where
3 {-
4 Note [Exitification]
5 ~~~~~~~~~~~~~~~~~~~~
7 This module implements Exitification. The goal is to pull as much code out of
8 recursive functions as possible, as the simplifier is better at inlining into
9 call-sites that are not in recursive functions.
11 Example:
13 let t = foo bar
14 joinrec go 0 x y = t (x*x)
15 go (n-1) x y = jump go (n-1) (x+y)
16 in …
18 We’d like to inline `t`, but that does not happen: Because t is a thunk and is
19 used in a recursive function, doing so might lose sharing in general. In
20 this case, however, `t` is on the _exit path_ of `go`, so called at most once.
21 How do we make this clearly visible to the simplifier?
23 A code path (i.e., an expression in a tail-recursive position) in a recursive
24 function is an exit path if it does not contain a recursive call. We can bind
25 this expression outside the recursive function, as a join-point.
27 Example result:
29 let t = foo bar
30 join exit x = t (x*x)
31 joinrec go 0 x y = jump exit x
32 go (n-1) x y = jump go (n-1) (x+y)
33 in …
35 Now `t` is no longer in a recursive function, and good things happen!
36 -}
38 import GhcPrelude
39 import Var
40 import Id
41 import IdInfo
42 import CoreSyn
43 import CoreUtils
44 import State
45 import Unique
46 import VarSet
47 import VarEnv
48 import CoreFVs
49 import FastString
50 import Type
52 import Data.Bifunctor
55 -- | Traverses the AST, simply to find all joinrecs and call 'exitify' on them.
56 exitifyProgram :: CoreProgram -> CoreProgram
57 exitifyProgram binds = map goTopLvl binds
58 where
59 goTopLvl (NonRec v e) = NonRec v (go in_scope_toplvl e)
60 goTopLvl (Rec pairs) = Rec (map (second (go in_scope_toplvl)) pairs)
62 in_scope_toplvl = emptyInScopeSet `extendInScopeSetList` bindersOfBinds binds
64 go :: InScopeSet -> CoreExpr -> CoreExpr
65 go _ e@(Var{}) = e
66 go _ e@(Lit {}) = e
67 go _ e@(Type {}) = e
68 go _ e@(Coercion {}) = e
70 go in_scope (Lam v e') = Lam v (go in_scope' e')
71 where in_scope' = in_scope `extendInScopeSet` v
72 go in_scope (App e1 e2) = App (go in_scope e1) (go in_scope e2)
73 go in_scope (Case scrut bndr ty alts)
74 = Case (go in_scope scrut) bndr ty (map (goAlt in_scope') alts)
75 where in_scope' = in_scope `extendInScopeSet` bndr
76 go in_scope (Cast e' c) = Cast (go in_scope e') c
77 go in_scope (Tick t e') = Tick t (go in_scope e')
78 go in_scope (Let bind body) = goBind in_scope bind (go in_scope' body)
79 where in_scope' = in_scope `extendInScopeSetList` bindersOf bind
81 goAlt :: InScopeSet -> CoreAlt -> CoreAlt
82 goAlt in_scope (dc, pats, rhs) = (dc, pats, go in_scope' rhs)
83 where in_scope' = in_scope `extendInScopeSetList` pats
85 goBind :: InScopeSet -> CoreBind -> (CoreExpr -> CoreExpr)
86 goBind in_scope (NonRec v rhs) = Let (NonRec v (go in_scope rhs))
87 goBind in_scope (Rec pairs)
88 | is_join_rec = exitify in_scope' pairs'
89 | otherwise = Let (Rec pairs')
90 where pairs' = map (second (go in_scope')) pairs
91 is_join_rec = any (isJoinId . fst) pairs
92 in_scope' = in_scope `extendInScopeSetList` bindersOf (Rec pairs)
94 -- | Given a recursive group of a joinrec, identifies “exit paths” and binds them as
95 -- join-points outside the joinrec.
96 exitify :: InScopeSet -> [(Var,CoreExpr)] -> (CoreExpr -> CoreExpr)
97 exitify in_scope pairs =
98 \body ->mkExitLets exits (mkLetRec pairs' body)
99 where
100 mkExitLets ((exitId, exitRhs):exits') = mkLetNonRec exitId exitRhs . mkExitLets exits'
101 mkExitLets [] = id
103 -- We need the set of free variables of many subexpressions here, so
104 -- annotate the AST with them
105 -- see Note [Calculating free variables]
106 ann_pairs = map (second freeVars) pairs
108 -- Which are the recursive calls?
109 recursive_calls = mkVarSet \$ map fst pairs
111 (pairs',exits) = (`runState` []) \$ do
112 forM ann_pairs \$ \(x,rhs) -> do
113 -- go past the lambdas of the join point
114 let (args, body) = collectNAnnBndrs (idJoinArity x) rhs
115 body' <- go args body
116 let rhs' = mkLams args body'
117 return (x, rhs')
119 -- main working function. Goes through the RHS (tail-call positions only),
120 -- checks if there are no more recursive calls, if so, abstracts over
121 -- variables bound on the way and lifts it out as a join point.
122 --
123 -- It uses a state monad to keep track of floated binds
124 go :: [Var] -- ^ variables to abstract over
125 -> CoreExprWithFVs -- ^ current expression in tail position
126 -> State [(Id, CoreExpr)] CoreExpr
128 go captured ann_e
129 -- Do not touch an expression that is already a join jump where all arguments
130 -- are captured variables. See Note [Idempotency]
131 -- But _do_ float join jumps with interesting arguments.
132 -- See Note [Jumps can be interesting]
133 | (Var f, args) <- collectArgs e
134 , isJoinId f
135 , all isCapturedVarArg args
136 = return e
138 -- Do not touch a boring expression (see Note [Interesting expression])
139 | is_exit, not is_interesting = return e
141 -- Cannot float out if local join points are used, as
142 -- we cannot abstract over them
143 | is_exit, captures_join_points = return e
145 -- We have something to float out!
146 | is_exit = do
147 -- Assemble the RHS of the exit join point
148 let rhs = mkLams args e
149 ty = exprType rhs
150 let avoid = in_scope `extendInScopeSetList` captured
151 -- Remember this binding under a suitable name
152 v <- addExit avoid ty (length args) rhs
154 return \$ mkVarApps (Var v) args
155 where
156 -- An exit expression has no recursive calls
157 is_exit = disjointVarSet fvs recursive_calls
159 -- Used to detect exit expressoins that are already proper exit jumps
160 isCapturedVarArg (Var v) = v `elem` captured
161 isCapturedVarArg _ = False
163 -- An interesting exit expression has free, non-imported
164 -- variables from outside the recursive group
165 -- See Note [Interesting expression]
166 is_interesting = anyVarSet isLocalId (fvs `minusVarSet` mkVarSet captured)
168 -- The possible arguments of this exit join point
169 args = filter (`elemVarSet` fvs) captured
171 -- We cannot abstract over join points
172 captures_join_points = any isJoinId args
174 e = deAnnotate ann_e
175 fvs = dVarSetToVarSet (freeVarsOf ann_e)
178 -- Case right hand sides are in tail-call position
179 go captured (_, AnnCase scrut bndr ty alts) = do
180 alts' <- forM alts \$ \(dc, pats, rhs) -> do
181 rhs' <- go (captured ++ [bndr] ++ pats) rhs
182 return (dc, pats, rhs')
183 return \$ Case (deAnnotate scrut) bndr ty alts'
185 go captured (_, AnnLet ann_bind body)
186 -- join point, RHS and body are in tail-call position
187 | AnnNonRec j rhs <- ann_bind
188 , Just join_arity <- isJoinId_maybe j
189 = do let (params, join_body) = collectNAnnBndrs join_arity rhs
190 join_body' <- go (captured ++ params) join_body
191 let rhs' = mkLams params join_body'
192 body' <- go (captured ++ [j]) body
193 return \$ Let (NonRec j rhs') body'
195 -- rec join point, RHSs and body are in tail-call position
196 | AnnRec pairs <- ann_bind
197 , isJoinId (fst (head pairs))
198 = do let js = map fst pairs
199 pairs' <- forM pairs \$ \(j,rhs) -> do
200 let join_arity = idJoinArity j
201 (params, join_body) = collectNAnnBndrs join_arity rhs
202 join_body' <- go (captured ++ js ++ params) join_body
203 let rhs' = mkLams params join_body'
204 return (j, rhs')
205 body' <- go (captured ++ js) body
206 return \$ Let (Rec pairs') body'
208 -- normal Let, only the body is in tail-call position
209 | otherwise
210 = do body' <- go (captured ++ bindersOf bind ) body
211 return \$ Let bind body'
212 where bind = deAnnBind ann_bind
214 go _ ann_e = return (deAnnotate ann_e)
217 -- Picks a new unique, which is disjoint from
218 -- * the free variables of the whole joinrec
219 -- * any bound variables (captured)
220 -- * any exit join points created so far.
221 mkExitJoinId :: InScopeSet -> Type -> JoinArity -> ExitifyM JoinId
222 mkExitJoinId in_scope ty join_arity = do
223 fs <- get
224 let avoid = in_scope `extendInScopeSetList` (map fst fs)
225 `extendInScopeSet` exit_id_tmpl -- just cosmetics
226 return (uniqAway avoid exit_id_tmpl)
227 where
228 exit_id_tmpl = mkSysLocal (fsLit "exit") initExitJoinUnique ty
229 `asJoinId` join_arity
230 `setIdOccInfo` exit_occ_info
232 -- See Note [Do not inline exit join points]
233 exit_occ_info =
234 OneOcc { occ_in_lam = True
235 , occ_one_br = True
236 , occ_int_cxt = False
237 , occ_tail = AlwaysTailCalled join_arity }
239 addExit :: InScopeSet -> Type -> JoinArity -> CoreExpr -> ExitifyM JoinId
240 addExit in_scope ty join_arity rhs = do
241 -- Pick a suitable name
242 v <- mkExitJoinId in_scope ty join_arity
243 fs <- get
244 put ((v,rhs):fs)
245 return v
248 type ExitifyM = State [(JoinId, CoreExpr)]
250 {-
251 Note [Interesting expression]
252 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
253 We do not want this to happen:
255 joinrec go 0 x y = x
256 go (n-1) x y = jump go (n-1) (x+y)
257 in …
258 ==>
259 join exit x = x
260 joinrec go 0 x y = jump exit x
261 go (n-1) x y = jump go (n-1) (x+y)
262 in …
264 because the floated exit path (`x`) is simply a parameter of `go`; there are
265 not useful interactions exposed this way.
267 Neither do we want this to happen
269 joinrec go 0 x y = x+x
270 go (n-1) x y = jump go (n-1) (x+y)
271 in …
272 ==>
273 join exit x = x+x
274 joinrec go 0 x y = jump exit x
275 go (n-1) x y = jump go (n-1) (x+y)
276 in …
278 where the floated expression `x+x` is a bit more complicated, but still not
279 intersting.
281 Expressions are interesting when they move an occurrence of a variable outside
282 the recursive `go` that can benefit from being obviously called once, for example:
283 * a local thunk that can then be inlined (see example in note [Exitification])
284 * the parameter of a function, where the demand analyzer then can then
285 see that it is called at most once, and hence improve the function’s
286 strictness signature
288 So we only hoist an exit expression out if it mentiones at least one free,
289 non-imported variable.
291 Note [Jumps can be interesting]
292 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
293 A jump to a join point can be interesting, if its arguments contain free
294 non-exported variables (z in the following example):
296 joinrec go 0 x y = jump j (x+z)
297 go (n-1) x y = jump go (n-1) (x+y)
298 in …
299 ==>
300 join exit x y = jump j (x+z)
301 joinrec go 0 x y = jump exit x
302 go (n-1) x y = jump go (n-1) (x+y)
305 The join point itself can be interesting, even if none if its
306 arguments have free variables free in the joinrec. For example
308 join j p = case p of (x,y) -> x+y
309 joinrec go 0 x y = jump j (x,y)
310 go (n-1) x y = jump go (n-1) (x+y) y
311 in …
313 Here, `j` would not be inlined because we do not inline something that looks
314 like an exit join point (see Note [Do not inline exit join points]). But
315 if we exitify the 'jump j (x,y)' we get
317 join j p = case p of (x,y) -> x+y
318 join exit x y = jump j (x,y)
319 joinrec go 0 x y = jump exit x y
320 go (n-1) x y = jump go (n-1) (x+y) y
321 in …
323 and now 'j' can inline, and we get rid of the pair. Here's another
324 example (assume `g` to be an imported function that, on its own,
325 does not make this interesting):
327 join j y = map f y
328 joinrec go 0 x y = jump j (map g x)
329 go (n-1) x y = jump go (n-1) (x+y)
330 in …
332 Again, `j` would not be inlined because we do not inline something that looks
333 like an exit join point (see Note [Do not inline exit join points]).
335 But after exitification we have
337 join j y = map f y
338 join exit x = jump j (map g x)
339 joinrec go 0 x y = jump j (map g x)
340 go (n-1) x y = jump go (n-1) (x+y)
341 in …
343 and now we can inline `j` and this will allow `map/map` to fire.
346 Note [Idempotency]
347 ~~~~~~~~~~~~~~~~~~
349 We do not want this to happen, where we replace the floated expression with
350 essentially the same expression:
352 join exit x = t (x*x)
353 joinrec go 0 x y = jump exit x
354 go (n-1) x y = jump go (n-1) (x+y)
355 in …
356 ==>
357 join exit x = t (x*x)
358 join exit' x = jump exit x
359 joinrec go 0 x y = jump exit' x
360 go (n-1) x y = jump go (n-1) (x+y)
361 in …
363 So when the RHS is a join jump, and all of its arguments are captured variables,
364 then we leave it in place.
366 Note that `jump exit x` in this example looks interesting, as `exit` is a free
367 variable. Therefore, idempotency does not simply follow from floating only
368 interesting expressions.
370 Note [Calculating free variables]
371 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
372 We have two options where to annotate the tree with free variables:
374 A) The whole tree.
375 B) Each individual joinrec as we come across it.
377 Downside of A: We pay the price on the whole module, even outside any joinrecs.
378 Downside of B: We pay the price per joinrec, possibly multiple times when
379 joinrecs are nested.
381 Further downside of A: If the exitify function returns annotated expressions,
382 it would have to ensure that the annotations are correct.
385 Note [Do not inline exit join points]
386 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
387 When we have
389 let t = foo bar
390 join exit x = t (x*x)
391 joinrec go 0 x y = jump exit x
392 go (n-1) x y = jump go (n-1) (x+y)
393 in …
395 we do not want the simplifier to simply inline `exit` back in (which it happily
396 would).
398 To prevent this, we need to recognize exit join points, and then disable
399 inlining.
401 Exit join points, recognizeable using `isExitJoinId` are join points with an
402 occurence in a recursive group, and can be recognized using `isExitJoinId`.
403 This function detects joinpoints with `occ_in_lam (idOccinfo id) == True`,
404 because the lambdas of a non-recursive join point are not considered for
405 `occ_in_lam`. For example, in the following code, `j1` is /not/ marked
406 occ_in_lam, because `j2` is called only once.
408 join j1 x = x+1
409 join j2 y = join j1 (y+2)
411 We create exit join point ids with such an `OccInfo`, see `exit_occ_info`.
413 To prevent inlining, we check for isExitJoinId
414 * In `preInlineUnconditionally` directly.
415 * In `simplLetUnfolding` we simply give exit join points no unfolding, which
416 prevents inlining in `postInlineUnconditionally` and call sites.
418 Note [Placement of the exitification pass]
419 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
420 I (Joachim) experimented with multiple positions for the Exitification pass in
421 the Core2Core pipeline:
423 A) Before the `simpl_phases`
424 B) Between the `simpl_phases` and the "main" simplifier pass
425 C) After demand_analyser
426 D) Before the final simplification phase
428 Here is the table (this is without inlining join exit points in the final
429 simplifier run):
431 Program | Allocs | Instrs
432 | ABCD.log A.log B.log C.log D.log | ABCD.log A.log B.log C.log D.log
433 ----------------|---------------------------------------------------|-------------------------------------------------
434 fannkuch-redux | -99.9% +0.0% -99.9% -99.9% -99.9% | -3.9% +0.5% -3.0% -3.9% -3.9%
435 fasta | -0.0% +0.0% +0.0% -0.0% -0.0% | -8.5% +0.0% +0.0% -0.0% -8.5%
436 fem | 0.0% 0.0% 0.0% 0.0% +0.0% | -2.2% -0.1% -0.1% -2.1% -2.1%
437 fish | 0.0% 0.0% 0.0% 0.0% +0.0% | -3.1% +0.0% -1.1% -1.1% -0.0%
438 k-nucleotide | -91.3% -91.0% -91.0% -91.3% -91.3% | -6.3% +11.4% +11.4% -6.3% -6.2%
439 scs | -0.0% -0.0% -0.0% -0.0% -0.0% | -3.4% -3.0% -3.1% -3.3% -3.3%
440 simple | -6.0% 0.0% -6.0% -6.0% +0.0% | -3.4% +0.0% -5.2% -3.4% -0.1%
441 spectral-norm | -0.0% 0.0% 0.0% -0.0% +0.0% | -2.7% +0.0% -2.7% -5.4% -5.4%
442 ----------------|---------------------------------------------------|-------------------------------------------------
443 Min | -95.0% -91.0% -95.0% -95.0% -95.0% | -8.5% -3.0% -5.2% -6.3% -8.5%
444 Max | +0.2% +0.2% +0.2% +0.2% +1.5% | +0.4% +11.4% +11.4% +0.4% +1.5%
445 Geometric Mean | -4.7% -2.1% -4.7% -4.7% -4.6% | -0.4% +0.1% -0.1% -0.3% -0.2%
447 Position A is disqualified, as it does not get rid of the allocations in
448 fannkuch-redux.
449 Position A and B are disqualified because it increases instructions in k-nucleotide.
450 Positions C and D have their advantages: C decreases allocations in simpl, but D instructions in fasta.
452 Assuming we have a budget of _one_ run of Exitification, then C wins (but we
453 could get more from running it multiple times, as seen in fish).
455 -}