More codegen refactoring with simonpj
[ghc.git] / compiler / cmm / CmmProcPoint.hs
1 {-# LANGUAGE GADTs, DisambiguateRecordFields #-}
2 {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
3
4 module CmmProcPoint
5 ( ProcPointSet, Status(..)
6 , callProcPoints, minimalProcPointSet
7 , addProcPointProtocols, splitAtProcPoints, procPointAnalysis
8 )
9 where
10
11 import Prelude hiding (last, unzip, succ, zip)
12
13 import BlockId
14 import CLabel
15 import Cmm
16 import CmmUtils
17 import CmmContFlowOpt
18 import CmmInfo
19 import CmmLive
20 import Constants
21 import Data.List (sortBy)
22 import Maybes
23 import MkGraph
24 import Control.Monad
25 import OptimizationFuel
26 import Outputable
27 import Platform
28 import UniqSet
29 import UniqSupply
30
31 import Compiler.Hoopl
32
33 import qualified Data.Map as Map
34
35 -- Compute a minimal set of proc points for a control-flow graph.
36
37 -- Determine a protocol for each proc point (which live variables will
38 -- be passed as arguments and which will be on the stack).
39
40 {-
41 A proc point is a basic block that, after CPS transformation, will
42 start a new function. The entry block of the original function is a
43 proc point, as is the continuation of each function call.
44 A third kind of proc point arises if we want to avoid copying code.
45 Suppose we have code like the following:
46
47 f() {
48 if (...) { ..1..; call foo(); ..2..}
49 else { ..3..; call bar(); ..4..}
50 x = y + z;
51 return x;
52 }
53
54 The statement 'x = y + z' can be reached from two different proc
55 points: the continuations of foo() and bar(). We would prefer not to
56 put a copy in each continuation; instead we would like 'x = y + z' to
57 be the start of a new procedure to which the continuations can jump:
58
59 f_cps () {
60 if (...) { ..1..; push k_foo; jump foo_cps(); }
61 else { ..3..; push k_bar; jump bar_cps(); }
62 }
63 k_foo() { ..2..; jump k_join(y, z); }
64 k_bar() { ..4..; jump k_join(y, z); }
65 k_join(y, z) { x = y + z; return x; }
66
67 You might think then that a criterion to make a node a proc point is
68 that it is directly reached by two distinct proc points. (Note
69 [Direct reachability].) But this criterion is a bit too simple; for
70 example, 'return x' is also reached by two proc points, yet there is
71 no point in pulling it out of k_join. A good criterion would be to
72 say that a node should be made a proc point if it is reached by a set
73 of proc points that is different than its immediate dominator. NR
74 believes this criterion can be shown to produce a minimum set of proc
75 points, and given a dominator tree, the proc points can be chosen in
76 time linear in the number of blocks. Lacking a dominator analysis,
77 however, we turn instead to an iterative solution, starting with no
78 proc points and adding them according to these rules:
79
80 1. The entry block is a proc point.
81 2. The continuation of a call is a proc point.
82 3. A node is a proc point if it is directly reached by more proc
83 points than one of its predecessors.
84
85 Because we don't understand the problem very well, we apply rule 3 at
86 most once per iteration, then recompute the reachability information.
87 (See Note [No simple dataflow].) The choice of the new proc point is
88 arbitrary, and I don't know if the choice affects the final solution,
89 so I don't know if the number of proc points chosen is the
90 minimum---but the set will be minimal.
91 -}
92
93 type ProcPointSet = BlockSet
94
95 data Status
96 = ReachedBy ProcPointSet -- set of proc points that directly reach the block
97 | ProcPoint -- this block is itself a proc point
98
99 instance Outputable Status where
100 ppr (ReachedBy ps)
101 | setNull ps = text "<not-reached>"
102 | otherwise = text "reached by" <+>
103 (hsep $ punctuate comma $ map ppr $ setElems ps)
104 ppr ProcPoint = text "<procpt>"
105
106 --------------------------------------------------
107 -- Proc point analysis
108
109 procPointAnalysis :: ProcPointSet -> CmmGraph -> FuelUniqSM (BlockEnv Status)
110 -- Once you know what the proc-points are, figure out
111 -- what proc-points each block is reachable from
112 procPointAnalysis procPoints g =
113 liftM snd $ dataflowPassFwd g initProcPoints $ analFwd lattice forward
114 where initProcPoints = [(id, ProcPoint) | id <- setElems procPoints]
115
116 -- transfer equations
117
118 forward :: FwdTransfer CmmNode Status
119 forward = mkFTransfer transfer
120 where
121 transfer :: CmmNode e x -> Status -> Fact x Status
122 transfer n s
123 = case shapeX n of
124 Open -> case n of
125 CmmEntry id | ProcPoint <- s
126 -> ReachedBy $ setSingleton id
127 _ -> s
128 Closed ->
129 mkFactBase lattice $ map (\id -> (id, x)) (successors l)
130
131 lattice :: DataflowLattice Status
132 lattice = DataflowLattice "direct proc-point reachability" unreached add_to
133 where unreached = ReachedBy setEmpty
134 add_to _ (OldFact ProcPoint) _ = (NoChange, ProcPoint)
135 add_to _ _ (NewFact ProcPoint) = (SomeChange, ProcPoint)
136 -- because of previous case
137 add_to _ (OldFact (ReachedBy p)) (NewFact (ReachedBy p'))
138 | setSize union > setSize p = (SomeChange, ReachedBy union)
139 | otherwise = (NoChange, ReachedBy p)
140 where
141 union = setUnion p' p
142
143 ----------------------------------------------------------------------
144
145 -- It is worth distinguishing two sets of proc points: those that are
146 -- induced by calls in the original graph and those that are
147 -- introduced because they're reachable from multiple proc points.
148 --
149 -- Extract the set of Continuation BlockIds, see Note [Continuation BlockIds].
150 callProcPoints :: CmmGraph -> ProcPointSet
151 callProcPoints g = foldGraphBlocks add (setSingleton (g_entry g)) g
152 where add :: CmmBlock -> BlockSet -> BlockSet
153 add b set = case lastNode b of
154 CmmCall {cml_cont = Just k} -> setInsert k set
155 CmmForeignCall {succ=k} -> setInsert k set
156 _ -> set
157
158 minimalProcPointSet :: Platform -> ProcPointSet -> CmmGraph
159 -> FuelUniqSM ProcPointSet
160 -- Given the set of successors of calls (which must be proc-points)
161 -- figure out the minimal set of necessary proc-points
162 minimalProcPointSet platform callProcPoints g
163 = extendPPSet platform g (postorderDfs g) callProcPoints
164
165 extendPPSet :: Platform -> CmmGraph -> [CmmBlock] -> ProcPointSet -> FuelUniqSM ProcPointSet
166 extendPPSet platform g blocks procPoints =
167 do env <- procPointAnalysis procPoints g
168 let add block pps = let id = entryLabel block
169 in case mapLookup id env of
170 Just ProcPoint -> setInsert id pps
171 _ -> pps
172 procPoints' = foldGraphBlocks add setEmpty g
173 newPoints = mapMaybe ppSuccessor blocks
174 newPoint = listToMaybe newPoints
175 ppSuccessor b =
176 let nreached id = case mapLookup id env `orElse`
177 pprPanic "no ppt" (ppr id <+> pprPlatform platform b) of
178 ProcPoint -> 1
179 ReachedBy ps -> setSize ps
180 block_procpoints = nreached (entryLabel b)
181 -- | Looking for a successor of b that is reached by
182 -- more proc points than b and is not already a proc
183 -- point. If found, it can become a proc point.
184 newId succ_id = not (setMember succ_id procPoints') &&
185 nreached succ_id > block_procpoints
186 in listToMaybe $ filter newId $ successors b
187 {-
188 case newPoints of
189 [] -> return procPoints'
190 pps -> extendPPSet g blocks
191 (foldl extendBlockSet procPoints' pps)
192 -}
193 case newPoint of
194 Just id ->
195 if setMember id procPoints'
196 then panic "added old proc pt"
197 else extendPPSet platform g blocks (setInsert id procPoints')
198 Nothing -> return procPoints'
199
200
201 ------------------------------------------------------------------------
202 -- Computing Proc-Point Protocols --
203 ------------------------------------------------------------------------
204
205 {-
206
207 There is one major trick, discovered by Michael Adams, which is that
208 we want to choose protocols in a way that enables us to optimize away
209 some continuations. The optimization is very much like branch-chain
210 elimination, except that it involves passing results as well as
211 control. The idea is that if a call's continuation k does nothing but
212 CopyIn its results and then goto proc point P, the call's continuation
213 may be changed to P, *provided* P's protocol is identical to the
214 protocol for the CopyIn. We choose protocols to make this so.
215
216 Here's an explanatory example; we begin with the source code (lines
217 separate basic blocks):
218
219 ..1..;
220 x, y = g();
221 goto P;
222 -------
223 P: ..2..;
224
225 Zipperization converts this code as follows:
226
227 ..1..;
228 call g() returns to k;
229 -------
230 k: CopyIn(x, y);
231 goto P;
232 -------
233 P: ..2..;
234
235 What we'd like to do is assign P the same CopyIn protocol as k, so we
236 can eliminate k:
237
238 ..1..;
239 call g() returns to P;
240 -------
241 P: CopyIn(x, y); ..2..;
242
243 Of course, P may be the target of more than one continuation, and
244 different continuations may have different protocols. Michael Adams
245 implemented a voting mechanism, but he thinks a simple greedy
246 algorithm would be just as good, so that's what we do.
247
248 -}
249
250 data Protocol = Protocol Convention [CmmFormal] Area
251 deriving Eq
252 instance Outputable Protocol where
253 ppr (Protocol c fs a) = text "Protocol" <+> ppr c <+> ppr fs <+> ppr a
254
255 -- | Function 'optimize_calls' chooses protocols only for those proc
256 -- points that are relevant to the optimization explained above.
257 -- The others are assigned by 'add_unassigned', which is not yet clever.
258
259 addProcPointProtocols :: ProcPointSet -> ProcPointSet -> CmmGraph -> FuelUniqSM CmmGraph
260 addProcPointProtocols callPPs procPoints g =
261 do liveness <- cmmLiveness g
262 (protos, g') <- optimize_calls liveness g
263 blocks'' <- add_CopyOuts protos procPoints g'
264 return $ ofBlockMap (g_entry g) blocks''
265 where optimize_calls liveness g = -- see Note [Separate Adams optimization]
266 do let (protos, blocks') =
267 foldGraphBlocks maybe_add_call (mapEmpty, mapEmpty) g
268 protos' = add_unassigned liveness procPoints protos
269 let g' = ofBlockMap (g_entry g) (add_CopyIns callPPs protos' blocks')
270 return (protos', removeUnreachableBlocks g')
271 maybe_add_call :: CmmBlock -> (BlockEnv Protocol, BlockEnv CmmBlock)
272 -> (BlockEnv Protocol, BlockEnv CmmBlock)
273 -- ^ If the block is a call whose continuation goes to a proc point
274 -- whose protocol either matches the continuation's or is not yet set,
275 -- redirect the call (cf 'newblock') and set the protocol if necessary
276 maybe_add_call block (protos, blocks) =
277 case lastNode block of
278 CmmCall tgt (Just k) args res s
279 | Just proto <- mapLookup k protos,
280 Just pee <- branchesToProcPoint k
281 -> let newblock = replaceLastNode block (CmmCall tgt (Just pee)
282 args res s)
283 changed_blocks = insertBlock newblock blocks
284 unchanged_blocks = insertBlock block blocks
285 in case mapLookup pee protos of
286 Nothing -> (mapInsert pee proto protos, changed_blocks)
287 Just proto' ->
288 if proto == proto' then (protos, changed_blocks)
289 else (protos, unchanged_blocks)
290 _ -> (protos, insertBlock block blocks)
291
292 branchesToProcPoint :: BlockId -> Maybe BlockId
293 -- ^ Tells whether the named block is just a branch to a proc point
294 branchesToProcPoint id =
295 let block = mapLookup id (toBlockMap g) `orElse`
296 panic "branch out of graph"
297 in case blockToNodeList block of
298 (_, [], JustC (CmmBranch pee)) | setMember pee procPoints -> Just pee
299 _ -> Nothing
300
301 -- | For now, following a suggestion by Ben Lippmeier, we pass all
302 -- live variables as arguments, hoping that a clever register
303 -- allocator might help.
304
305 add_unassigned :: BlockEnv CmmLive -> ProcPointSet -> BlockEnv Protocol ->
306 BlockEnv Protocol
307 add_unassigned = pass_live_vars_as_args
308
309 pass_live_vars_as_args :: BlockEnv CmmLive -> ProcPointSet ->
310 BlockEnv Protocol -> BlockEnv Protocol
311 pass_live_vars_as_args _liveness procPoints protos = protos'
312 where protos' = setFold addLiveVars protos procPoints
313 addLiveVars :: BlockId -> BlockEnv Protocol -> BlockEnv Protocol
314 addLiveVars id protos =
315 case mapLookup id protos of
316 Just _ -> protos
317 Nothing -> let live = emptyRegSet
318 --lookupBlockEnv _liveness id `orElse`
319 --panic ("no liveness at block " ++ show id)
320 formals = uniqSetToList live
321 prot = Protocol Private formals $ CallArea $ Young id
322 in mapInsert id prot protos
323
324
325 -- | Add copy-in instructions to each proc point that did not arise from a call
326 -- instruction. (Proc-points that arise from calls already have their copy-in instructions.)
327
328 add_CopyIns :: ProcPointSet -> BlockEnv Protocol -> BlockEnv CmmBlock -> BlockEnv CmmBlock
329 add_CopyIns callPPs protos blocks = mapFold maybe_insert_CopyIns mapEmpty blocks
330 where maybe_insert_CopyIns block blocks
331 | not $ setMember bid callPPs
332 , Just (Protocol c fs _area) <- mapLookup bid protos
333 = let nodes = copyInSlot c fs
334 (h, m, l) = blockToNodeList block
335 in insertBlock (blockOfNodeList (h, nodes ++ m, l)) blocks
336 | otherwise = insertBlock block blocks
337 where bid = entryLabel block
338
339
340 -- | Add a CopyOut node before each procpoint.
341 -- If the predecessor is a call, then the copy outs should already be done by the callee.
342 -- Note: If we need to add copy-out instructions, they may require stack space,
343 -- so we accumulate a map from the successors to the necessary stack space,
344 -- then update the successors after we have finished inserting the copy-outs.
345
346 add_CopyOuts :: BlockEnv Protocol -> ProcPointSet -> CmmGraph ->
347 FuelUniqSM (BlockEnv CmmBlock)
348 add_CopyOuts protos procPoints g = foldGraphBlocks mb_copy_out (return mapEmpty) g
349 where mb_copy_out :: CmmBlock -> FuelUniqSM (BlockEnv CmmBlock) ->
350 FuelUniqSM (BlockEnv CmmBlock)
351 mb_copy_out b z | entryLabel b == g_entry g = skip b z
352 mb_copy_out b z =
353 case lastNode b of
354 CmmCall {} -> skip b z -- copy out done by callee
355 CmmForeignCall {} -> skip b z -- copy out done by callee
356 _ -> copy_out b z
357 copy_out b z = foldr trySucc init (successors b) >>= finish
358 where init = (\bmap -> (b, bmap)) `liftM` z
359 trySucc succId z =
360 if setMember succId procPoints then
361 case mapLookup succId protos of
362 Nothing -> z
363 Just (Protocol c fs _area) -> insert z succId $ copyOutSlot c fs
364 else z
365 insert z succId m =
366 do (b, bmap) <- z
367 (b, bs) <- insertBetween b m succId
368 -- pprTrace "insert for succ" (ppr succId <> ppr m) $ do
369 return $ (b, foldl (flip insertBlock) bmap bs)
370 finish (b, bmap) = return $ insertBlock b bmap
371 skip b bs = insertBlock b `liftM` bs
372
373 -- At this point, we have found a set of procpoints, each of which should be
374 -- the entry point of a procedure.
375 -- Now, we create the procedure for each proc point,
376 -- which requires that we:
377 -- 1. build a map from proc points to the blocks reachable from the proc point
378 -- 2. turn each branch to a proc point into a jump
379 -- 3. turn calls and returns into jumps
380 -- 4. build info tables for the procedures -- and update the info table for
381 -- the SRTs in the entry procedure as well.
382 -- Input invariant: A block should only be reachable from a single ProcPoint.
383 -- ToDo: use the _ret naming convention that the old code generator
384 -- used. -- EZY
385 splitAtProcPoints :: CLabel -> ProcPointSet-> ProcPointSet -> BlockEnv Status ->
386 CmmDecl -> FuelUniqSM [CmmDecl]
387 splitAtProcPoints entry_label callPPs procPoints procMap
388 (CmmProc (TopInfo {info_tbl=info_tbl,
389 stack_info=stack_info})
390 top_l g@(CmmGraph {g_entry=entry})) =
391 do -- Build a map from procpoints to the blocks they reach
392 let addBlock b graphEnv =
393 case mapLookup bid procMap of
394 Just ProcPoint -> add graphEnv bid bid b
395 Just (ReachedBy set) ->
396 case setElems set of
397 [] -> graphEnv
398 [id] -> add graphEnv id bid b
399 _ -> panic "Each block should be reachable from only one ProcPoint"
400 Nothing -> pprPanic "block not reached by a proc point?" (ppr bid)
401 where bid = entryLabel b
402 add graphEnv procId bid b = mapInsert procId graph' graphEnv
403 where graph = mapLookup procId graphEnv `orElse` mapEmpty
404 graph' = mapInsert bid b graph
405 graphEnv <- return $ foldGraphBlocks addBlock emptyBlockMap g
406 -- Build a map from proc point BlockId to pairs of:
407 -- * Labels for their new procedures
408 -- * Labels for the info tables of their new procedures (only if the proc point is a callPP)
409 -- Due to common blockification, we may overestimate the set of procpoints.
410 let add_label map pp = Map.insert pp lbls map
411 where lbls | pp == entry = (entry_label, Just entry_info_lbl)
412 | otherwise = (blockLbl pp, guard (setMember pp callPPs) >>
413 Just (infoTblLbl pp))
414 entry_info_lbl = cit_lbl info_tbl
415 procLabels = foldl add_label Map.empty
416 (filter (flip mapMember (toBlockMap g)) (setElems procPoints))
417 -- For each procpoint, we need to know the SP offset on entry.
418 -- If the procpoint is:
419 -- - continuation of a call, the SP offset is in the call
420 -- - otherwise, 0 (and left out of the spEntryMap)
421 let add_sp_off :: CmmBlock -> BlockEnv CmmStackInfo -> BlockEnv CmmStackInfo
422 add_sp_off b env =
423 case lastNode b of
424 CmmCall {cml_cont = Just succ, cml_ret_args = off, cml_ret_off = updfr_off} ->
425 mapInsert succ (StackInfo { arg_space = off, updfr_space = Just updfr_off}) env
426 CmmForeignCall {succ = succ, updfr = updfr_off} ->
427 mapInsert succ (StackInfo { arg_space = wORD_SIZE, updfr_space = Just updfr_off}) env
428 _ -> env
429 spEntryMap = foldGraphBlocks add_sp_off (mapInsert entry stack_info emptyBlockMap) g
430 getStackInfo id = mapLookup id spEntryMap `orElse` StackInfo {arg_space = 0, updfr_space = Nothing}
431 -- In each new graph, add blocks jumping off to the new procedures,
432 -- and replace branches to procpoints with branches to the jump-off blocks
433 let add_jump_block (env, bs) (pp, l) =
434 do bid <- liftM mkBlockId getUniqueM
435 let b = blockOfNodeList (JustC (CmmEntry bid), [], JustC jump)
436 StackInfo {arg_space = argSpace, updfr_space = off} = getStackInfo pp
437 jump = CmmCall (CmmLit (CmmLabel l)) Nothing argSpace 0
438 (off `orElse` 0) -- Jump's shouldn't need the offset...
439 return (mapInsert pp bid env, b : bs)
440 add_jumps (newGraphEnv) (ppId, blockEnv) =
441 do let needed_jumps = -- find which procpoints we currently branch to
442 mapFold add_if_branch_to_pp [] blockEnv
443 add_if_branch_to_pp :: CmmBlock -> [(BlockId, CLabel)] -> [(BlockId, CLabel)]
444 add_if_branch_to_pp block rst =
445 case lastNode block of
446 CmmBranch id -> add_if_pp id rst
447 CmmCondBranch _ ti fi -> add_if_pp ti (add_if_pp fi rst)
448 CmmSwitch _ tbl -> foldr add_if_pp rst (catMaybes tbl)
449 _ -> rst
450 add_if_pp id rst = case Map.lookup id procLabels of
451 Just (lbl, mb_info_lbl) -> (id, mb_info_lbl `orElse` lbl) : rst
452 Nothing -> rst
453 (jumpEnv, jumpBlocks) <-
454 foldM add_jump_block (mapEmpty, []) needed_jumps
455 -- update the entry block
456 let b = expectJust "block in env" $ mapLookup ppId blockEnv
457 off = getStackInfo ppId
458 blockEnv' = mapInsert ppId b blockEnv
459 -- replace branches to procpoints with branches to jumps
460 blockEnv'' = toBlockMap $ replaceBranches jumpEnv $ ofBlockMap ppId blockEnv'
461 -- add the jump blocks to the graph
462 blockEnv''' = foldl (flip insertBlock) blockEnv'' jumpBlocks
463 let g' = (off, ofBlockMap ppId blockEnv''')
464 -- pprTrace "g' pre jumps" (ppr g') $ do
465 return (mapInsert ppId g' newGraphEnv)
466 graphEnv <- foldM add_jumps emptyBlockMap $ mapToList graphEnv
467 let to_proc (bid, (stack_info, g)) = case expectJust "pp label" $ Map.lookup bid procLabels of
468 (lbl, Just info_lbl)
469 | bid == entry
470 -> CmmProc (TopInfo {info_tbl=info_tbl, stack_info=stack_info})
471 top_l (replacePPIds g)
472 | otherwise
473 -> CmmProc (TopInfo {info_tbl=mkEmptyContInfoTable info_lbl, stack_info=stack_info})
474 lbl (replacePPIds g)
475 (lbl, Nothing)
476 -> CmmProc (TopInfo {info_tbl=CmmNonInfoTable, stack_info=stack_info})
477 lbl (replacePPIds g)
478 -- References to procpoint IDs can now be replaced with the infotable's label
479 replacePPIds g = mapGraphNodes (id, mapExp repl, mapExp repl) g
480 where repl e@(CmmLit (CmmBlock bid)) =
481 case Map.lookup bid procLabels of
482 Just (_, Just info_lbl) -> CmmLit (CmmLabel info_lbl)
483 _ -> e
484 repl e = e
485 -- The C back end expects to see return continuations before the call sites.
486 -- Here, we sort them in reverse order -- it gets reversed later.
487 let (_, block_order) = foldl add_block_num (0::Int, emptyBlockMap) (postorderDfs g)
488 add_block_num (i, map) block = (i+1, mapInsert (entryLabel block) i map)
489 sort_fn (bid, _) (bid', _) =
490 compare (expectJust "block_order" $ mapLookup bid block_order)
491 (expectJust "block_order" $ mapLookup bid' block_order)
492 procs <- return $ map to_proc $ sortBy sort_fn $ mapToList graphEnv
493 return -- pprTrace "procLabels" (ppr procLabels)
494 -- pprTrace "splitting graphs" (ppr procs)
495 procs
496 splitAtProcPoints _ _ _ _ t@(CmmData _ _) = return [t]
497
498
499 -- Only called from CmmProcPoint.splitAtProcPoints. NB. does a
500 -- recursive lookup, see comment below.
501 replaceBranches :: BlockEnv BlockId -> CmmGraph -> CmmGraph
502 replaceBranches env g = mapGraphNodes (id, id, last) g
503 where
504 last :: CmmNode O C -> CmmNode O C
505 last (CmmBranch id) = CmmBranch (lookup id)
506 last (CmmCondBranch e ti fi) = CmmCondBranch e (lookup ti) (lookup fi)
507 last (CmmSwitch e tbl) = CmmSwitch e (map (fmap lookup) tbl)
508 last l@(CmmCall {}) = l
509 last l@(CmmForeignCall {}) = l
510 lookup id = fmap lookup (mapLookup id env) `orElse` id
511 -- XXX: this is a recursive lookup, it follows chains
512 -- until the lookup returns Nothing, at which point we
513 -- return the last BlockId
514
515 ----------------------------------------------------------------
516
517 {-
518 Note [Direct reachability]
519
520 Block B is directly reachable from proc point P iff control can flow
521 from P to B without passing through an intervening proc point.
522 -}
523
524 ----------------------------------------------------------------
525
526 {-
527 Note [No simple dataflow]
528
529 Sadly, it seems impossible to compute the proc points using a single
530 dataflow pass. One might attempt to use this simple lattice:
531
532 data Location = Unknown
533 | InProc BlockId -- node is in procedure headed by the named proc point
534 | ProcPoint -- node is itself a proc point
535
536 At a join, a node in two different blocks becomes a proc point.
537 The difficulty is that the change of information during iterative
538 computation may promote a node prematurely. Here's a program that
539 illustrates the difficulty:
540
541 f () {
542 entry:
543 ....
544 L1:
545 if (...) { ... }
546 else { ... }
547
548 L2: if (...) { g(); goto L1; }
549 return x + y;
550 }
551
552 The only proc-point needed (besides the entry) is L1. But in an
553 iterative analysis, consider what happens to L2. On the first pass
554 through, it rises from Unknown to 'InProc entry', but when L1 is
555 promoted to a proc point (because it's the successor of g()), L1's
556 successors will be promoted to 'InProc L1'. The problem hits when the
557 new fact 'InProc L1' flows into L2 which is already bound to 'InProc entry'.
558 The join operation makes it a proc point when in fact it needn't be,
559 because its immediate dominator L1 is already a proc point and there
560 are no other proc points that directly reach L2.
561 -}
562
563
564
565 {- Note [Separate Adams optimization]
566 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
567 It may be worthwhile to attempt the Adams optimization by rewriting
568 the graph before the assignment of proc-point protocols. Here are a
569 couple of rules:
570
571 g() returns to k; g() returns to L;
572 k: CopyIn c ress; goto L:
573 ... ==> ...
574 L: // no CopyIn node here L: CopyIn c ress;
575
576
577 And when c == c' and ress == ress', this also:
578
579 g() returns to k; g() returns to L;
580 k: CopyIn c ress; goto L:
581 ... ==> ...
582 L: CopyIn c' ress' L: CopyIn c' ress' ;
583
584 In both cases the goal is to eliminate k.
585 -}