CmmProcPointZ.hs 25 KB
Newer Older
1
module CmmProcPointZ
2
3
    ( ProcPointSet, Status(..)
    , callProcPoints, minimalProcPointSet
4
    , addProcPointProtocols, splitAtProcPoints, procPointAnalysis
5
6
7
    )
where

8
import qualified Prelude as P
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
9
import Prelude hiding (zip, unzip, last)
10

11
import BlockId
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
12
import CLabel
13
14
import Cmm hiding (blockId)
import CmmContFlowOpt
15
16
import CmmExpr
import CmmInfo
17
18
19
import CmmLiveZ
import CmmTx
import DFMonad
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
20
import FiniteMap
21
import List (sortBy)
22
import Maybes
23
import MkZipCfg
24
import MkZipCfgCmm hiding (CmmBlock, CmmGraph, CmmTopZ)
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
25
import Monad
26
27
28
import Outputable
import Panic
import UniqSet
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
29
import UniqSupply
30
import ZipCfg
31
import ZipCfgCmmRep
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
32
import ZipDataflow
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

-- Compute a minimal set of proc points for a control-flow graph.

-- Determine a protocol for each proc point (which live variables will
-- be passed as arguments and which will be on the stack). 

{-
A proc point is a basic block that, after CPS transformation, will
start a new function.  The entry block of the original function is a
proc point, as is the continuation of each function call.
A third kind of proc point arises if we want to avoid copying code.
Suppose we have code like the following:

  f() {
    if (...) { ..1..; call foo(); ..2..}
    else     { ..3..; call bar(); ..4..}
    x = y + z;
    return x;
  }

The statement 'x = y + z' can be reached from two different proc
points: the continuations of foo() and bar().  We would prefer not to
put a copy in each continuation; instead we would like 'x = y + z' to
be the start of a new procedure to which the continuations can jump:

  f_cps () {
    if (...) { ..1..; push k_foo; jump foo_cps(); }
    else     { ..3..; push k_bar; jump bar_cps(); }
  }
  k_foo() { ..2..; jump k_join(y, z); }
  k_bar() { ..4..; jump k_join(y, z); }
  k_join(y, z) { x = y + z; return x; }

You might think then that a criterion to make a node a proc point is
that it is directly reached by two distinct proc points.  (Note
68
[Direct reachability].)  But this criterion is a bit too simple; for
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
example, 'return x' is also reached by two proc points, yet there is
no point in pulling it out of k_join.  A good criterion would be to
say that a node should be made a proc point if it is reached by a set
of proc points that is different than its immediate dominator.  NR
believes this criterion can be shown to produce a minimum set of proc
points, and given a dominator tree, the proc points can be chosen in
time linear in the number of blocks.  Lacking a dominator analysis,
however, we turn instead to an iterative solution, starting with no
proc points and adding them according to these rules:

  1. The entry block is a proc point.
  2. The continuation of a call is a proc point.
  3. A node is a proc point if it is directly reached by more proc
     points than one of its predecessors.

Because we don't understand the problem very well, we apply rule 3 at
most once per iteration, then recompute the reachability information.
(See Note [No simple dataflow].)  The choice of the new proc point is
arbitrary, and I don't know if the choice affects the final solution,
so I don't know if the number of proc points chosen is the
minimum---but the set will be minimal.
-}

type ProcPointSet = BlockSet

data Status
  = ReachedBy ProcPointSet  -- set of proc points that directly reach the block
  | ProcPoint               -- this block is itself a proc point

instance Outputable Status where
  ppr (ReachedBy ps)
100
      | isEmptyBlockSet ps = text "<not-reached>"
101
      | otherwise = text "reached by" <+>
102
                    (hsep $ punctuate comma $ map ppr $ blockSetToList ps)
103
104
105
106
107
108
109
110
111
  ppr ProcPoint = text "<procpt>"


lattice :: DataflowLattice Status
lattice = DataflowLattice "direct proc-point reachability" unreached add_to False
    where unreached = ReachedBy emptyBlockSet
          add_to _ ProcPoint = noTx ProcPoint
          add_to ProcPoint _ = aTx ProcPoint -- aTx because of previous case again
          add_to (ReachedBy p) (ReachedBy p') =
112
113
              let union = unionBlockSets p p'
              in  if sizeBlockSet union > sizeBlockSet p' then
114
115
116
117
118
119
                      aTx (ReachedBy union)
                  else
                      noTx (ReachedBy p')
--------------------------------------------------
-- transfer equations

dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
120
121
forward :: ForwardTransfers Middle Last Status
forward = ForwardTransfers first middle last exit
122
123
124
125
126
    where first id ProcPoint = ReachedBy $ unitBlockSet id
          first  _ x = x
          middle _ x = x
          last (LastCall _ (Just id) _ _ _) _ = LastOutFacts [(id, ProcPoint)]
          last l x = LastOutFacts $ map (\id -> (id, x)) (succs l)
127
          exit x   = x
128
                
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
129
130
131
132
133
134
-- It is worth distinguishing two sets of proc points:
-- those that are induced by calls in the original graph
-- and those that are introduced because they're reachable from multiple proc points.
callProcPoints      :: CmmGraph -> ProcPointSet
minimalProcPointSet :: ProcPointSet -> CmmGraph -> FuelMonad ProcPointSet

135
136
callProcPoints g = fold_blocks add (unitBlockSet (lg_entry g)) g
  where add b set = case last $ unzip b of
137
                      LastOther (LastCall _ (Just k) _ _ _) -> extendBlockSet set k
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
138
139
140
141
142
143
                      _ -> set

minimalProcPointSet callProcPoints g = extendPPSet g (postorder_dfs g) callProcPoints

type PPFix = FuelMonad (ForwardFixedPoint Middle Last Status ())

144
procPointAnalysis :: ProcPointSet -> CmmGraph -> FuelMonad (BlockEnv Status)
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
145
146
procPointAnalysis procPoints g =
  let addPP env id = extendBlockEnv env id ProcPoint
147
      initProcPoints = foldl addPP emptyBlockEnv (blockSetToList procPoints)
148
149
  in liftM zdfFpFacts $
        (zdfSolveFrom initProcPoints "proc-point reachability" lattice
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
150
151
152
                              forward (fact_bot lattice) $ graphOfLGraph g :: PPFix)

extendPPSet :: CmmGraph -> [CmmBlock] -> ProcPointSet -> FuelMonad ProcPointSet
153
extendPPSet g blocks procPoints =
154
    do env <- procPointAnalysis procPoints g
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
155
156
157
158
159
       let add block pps = let id = blockId block
                           in  case lookupBlockEnv env id of
                                 Just ProcPoint -> extendBlockSet pps id
                                 _ -> pps
           procPoints' = fold_blocks add emptyBlockSet g
160
161
           newPoints = mapMaybe ppSuccessor blocks
           newPoint  = listToMaybe newPoints 
162
           ppSuccessor b@(Block bid _) =
163
164
               let nreached id = case lookupBlockEnv env id `orElse`
                                       pprPanic "no ppt" (ppr id <+> ppr b) of
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
165
                                   ProcPoint -> 1
166
167
                                   ReachedBy ps -> sizeBlockSet ps
                   block_procpoints = nreached bid
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
168
169
170
171
                   -- | Looking for a successor of b that is reached by
                   -- more proc points than b and is not already a proc
                   -- point.  If found, it can become a proc point.
                   newId succ_id = not (elemBlockSet succ_id procPoints') &&
172
                                   nreached succ_id > block_procpoints
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
173
               in  listToMaybe $ filter newId $ succs b
174
175
176
177
178
179
{-
       case newPoints of
           []  -> return procPoints'
           pps -> extendPPSet g blocks
                    (foldl extendBlockSet procPoints' pps)
-}
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
180
181
182
183
184
185
       case newPoint of Just id ->
                          if elemBlockSet id procPoints' then panic "added old proc pt"
                          else extendPPSet g blocks (extendBlockSet procPoints' id)
                        Nothing -> return procPoints'


186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
------------------------------------------------------------------------
--                    Computing Proc-Point Protocols                  --
------------------------------------------------------------------------

{-

There is one major trick, discovered by Michael Adams, which is that
we want to choose protocols in a way that enables us to optimize away
some continuations.  The optimization is very much like branch-chain
elimination, except that it involves passing results as well as
control.  The idea is that if a call's continuation k does nothing but
CopyIn its results and then goto proc point P, the call's continuation
may be changed to P, *provided* P's protocol is identical to the
protocol for the CopyIn.  We choose protocols to make this so.

Here's an explanatory example; we begin with the source code (lines
separate basic blocks):

  ..1..;
  x, y = g();
  goto P;
  -------
  P: ..2..;

Zipperization converts this code as follows:

  ..1..;
  call g() returns to k;
  -------
  k: CopyIn(x, y);
     goto P;
  -------
  P: ..2..;

What we'd like to do is assign P the same CopyIn protocol as k, so we
can eliminate k:

  ..1..;
  call g() returns to P;
  -------
  P: CopyIn(x, y); ..2..;

Of course, P may be the target of more than one continuation, and
different continuations may have different protocols.  Michael Adams
implemented a voting mechanism, but he thinks a simple greedy
algorithm would be just as good, so that's what we do.

-}

235
data Protocol = Protocol Convention CmmFormals Area
236
  deriving Eq
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
237
238
instance Outputable Protocol where
  ppr (Protocol c fs a) = text "Protocol" <+> ppr c <+> ppr fs <+> ppr a
239
240
241
242
243

-- | Function 'optimize_calls' chooses protocols only for those proc
-- points that are relevant to the optimization explained above.
-- The others are assigned by 'add_unassigned', which is not yet clever.

244
245
addProcPointProtocols :: ProcPointSet -> ProcPointSet -> CmmGraph -> FuelMonad CmmGraph
addProcPointProtocols callPPs procPoints g =
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
246
  do liveness <- cmmLivenessZ g
247
     (protos, g') <- optimize_calls liveness g
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
248
     blocks'' <- add_CopyOuts protos procPoints g'
249
     return $ LGraph (lg_entry g) blocks''
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
250
    where optimize_calls liveness g =  -- see Note [Separate Adams optimization]
251
252
253
254
            do let (protos, blocks') =
                       fold_blocks maybe_add_call (init_protocols, emptyBlockEnv) g
                   protos' = add_unassigned liveness procPoints protos
               blocks <- add_CopyIns callPPs protos' blocks'
255
256
               let g' = LGraph (lg_entry g) (mkBlockEnv (map withKey (concat blocks)))
                   withKey b@(Block bid _) = (bid, b)
257
               return (protos', runTx removeUnreachableBlocksZ g')
258
259
260
261
262
263
264
          maybe_add_call :: CmmBlock -> (BlockEnv Protocol, BlockEnv CmmBlock)
                         -> (BlockEnv Protocol, BlockEnv CmmBlock)
          -- ^ If the block is a call whose continuation goes to a proc point
          -- whose protocol either matches the continuation's or is not yet set,
          -- redirect the call (cf 'newblock') and set the protocol if necessary
          maybe_add_call block (protos, blocks) =
              case goto_end $ unzip block of
265
                (h, LastOther (LastCall tgt (Just k) args res s))
266
                    | Just proto <- lookupBlockEnv protos k,
267
                      Just pee   <- branchesToProcPoint k
268
269
                    -> let newblock = zipht h (tailOfLast (LastCall tgt (Just pee)
                                                                    args res s))
270
271
272
273
274
275
276
277
278
                           changed_blocks   = insertBlock newblock blocks
                           unchanged_blocks = insertBlock block    blocks
                       in case lookupBlockEnv protos pee of
                            Nothing -> (extendBlockEnv protos pee proto,changed_blocks)
                            Just proto' ->
                              if proto == proto' then (protos, changed_blocks)
                              else (protos, unchanged_blocks)
                _ -> (protos, insertBlock block blocks)

279
280
281
          branchesToProcPoint :: BlockId -> Maybe BlockId
          -- ^ Tells whether the named block is just a branch to a proc point
          branchesToProcPoint id =
282
              let (Block _ t) = lookupBlockEnv (lg_blocks g) id `orElse`
283
                                    panic "branch out of graph"
284
              in case t of
285
                   ZLast (LastOther (LastBranch pee))
286
287
288
289
                       | elemBlockSet pee procPoints -> Just pee
                   _ -> Nothing
          init_protocols = fold_blocks maybe_add_proto emptyBlockEnv g
          maybe_add_proto :: CmmBlock -> BlockEnv Protocol -> BlockEnv Protocol
290
291
          --maybe_add_proto (Block id (ZTail (CopyIn c _ fs _srt) _)) env =
          --    extendBlockEnv env id (Protocol c fs $ toArea id fs)
292
          maybe_add_proto _ env = env
293
294
          -- JD: Is this proto stuff even necessary, now that we have
          -- common blockification?
295
296
297
298
299

-- | For now, following a suggestion by Ben Lippmeier, we pass all
-- live variables as arguments, hoping that a clever register
-- allocator might help.

dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
300
301
add_unassigned :: BlockEnv CmmLive -> ProcPointSet -> BlockEnv Protocol ->
                  BlockEnv Protocol
302
303
add_unassigned = pass_live_vars_as_args

dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
304
305
pass_live_vars_as_args :: BlockEnv CmmLive -> ProcPointSet ->
                          BlockEnv Protocol -> BlockEnv Protocol
306
pass_live_vars_as_args _liveness procPoints protos = protos'
307
  where protos' = foldBlockSet addLiveVars protos procPoints
308
309
310
        addLiveVars :: BlockId -> BlockEnv Protocol -> BlockEnv Protocol
        addLiveVars id protos =
            case lookupBlockEnv protos id of
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
311
              Just _  -> protos
312
              Nothing -> let live = emptyRegSet
313
314
315
316
                                    --lookupBlockEnv _liveness id `orElse`
                                    --panic ("no liveness at block " ++ show id)
                             formals = uniqSetToList live
                             prot = Protocol Private formals $ CallArea $ Young id
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
317
                         in  extendBlockEnv protos id prot
318
319


dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
320
321
-- | Add copy-in instructions to each proc point that did not arise from a call
-- instruction. (Proc-points that arise from calls already have their copy-in instructions.)
322

323
324
325
326
add_CopyIns :: ProcPointSet -> BlockEnv Protocol -> BlockEnv CmmBlock ->
               FuelMonad [[CmmBlock]]
add_CopyIns callPPs protos blocks =
  liftUniq $ mapM maybe_insert_CopyIns (blockEnvToList blocks)
327
    where maybe_insert_CopyIns (_, b@(Block id t))
328
           | not $ elemBlockSet id callPPs
329
330
331
           = case lookupBlockEnv protos id of
               Just (Protocol c fs _area) ->
                 do LGraph _ blocks <-
332
                      lgraphOfAGraph (mkLabel id <*> copyInSlot c fs <*> mkZTail t)
333
                    return (map snd $ blockEnvToList blocks)
334
               Nothing -> return [b]
335
           | otherwise = return [b]
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
336
337

-- | Add a CopyOut node before each procpoint.
338
339
340
341
-- If the predecessor is a call, then the copy outs should already be done by the callee.
-- Note: If we need to add copy-out instructions, they may require stack space,
-- so we accumulate a map from the successors to the necessary stack space,
-- then update the successors after we have finished inserting the copy-outs.
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
342
343
344

add_CopyOuts :: BlockEnv Protocol -> ProcPointSet -> CmmGraph ->
                FuelMonad (BlockEnv CmmBlock)
345
346
347
add_CopyOuts protos procPoints g = fold_blocks mb_copy_out (return emptyBlockEnv) g
    where mb_copy_out :: CmmBlock -> FuelMonad (BlockEnv CmmBlock) ->
                                     FuelMonad (BlockEnv CmmBlock)
348
          mb_copy_out b@(Block bid _) z | bid == lg_entry g = skip b z 
349
          mb_copy_out b z =
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
350
            case last $ unzip b of
351
352
353
              LastOther (LastCall _ _ _ _ _) -> skip b z -- copy out done by callee
              _ -> copy_out b z
          copy_out b z = fold_succs trySucc b init >>= finish
354
            where init = z >>= (\bmap -> return (b, bmap))
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
355
356
357
358
                  trySucc succId z =
                    if elemBlockSet succId procPoints then
                      case lookupBlockEnv protos succId of
                        Nothing -> z
359
                        Just (Protocol c fs _area) -> insert z succId $ copyOutSlot c fs
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
360
361
362
363
                    else z
                  insert z succId m =
                    do (b, bmap) <- z
                       (b, bs)   <- insertBetween b m succId
364
365
                       -- pprTrace "insert for succ" (ppr succId <> ppr m) $ do
                       return $ (b, foldl (flip insertBlock) bmap bs)
366
                  finish (b@(Block bid _), bmap) =
367
                    return $ (extendBlockEnv bmap bid b)
368
          skip b@(Block bid _) bs =
369
370
371
372
373
374
375
376
377
378
379
            bs >>= (\bmap -> return (extendBlockEnv bmap bid b))

-- At this point, we have found a set of procpoints, each of which should be
-- the entry point of a procedure.
-- Now, we create the procedure for each proc point,
-- which requires that we:
-- 1. build a map from proc points to the blocks reachable from the proc point
-- 2. turn each branch to a proc point into a jump
-- 3. turn calls and returns into jumps
-- 4. build info tables for the procedures -- and update the info table for
--    the SRTs in the entry procedure as well.
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
380
-- Input invariant: A block should only be reachable from a single ProcPoint.
381
splitAtProcPoints :: CLabel -> ProcPointSet-> ProcPointSet -> BlockEnv Status ->
382
383
                     CmmTopZ -> FuelMonad [CmmTopZ]
splitAtProcPoints entry_label callPPs procPoints procMap
384
                  (CmmProc (CmmInfo gc upd_fr info_tbl) top_l top_args
385
                           (stackInfo, g@(LGraph entry blocks))) =
386
  do -- Build a map from procpoints to the blocks they reach
387
     let addBlock b@(Block bid _) graphEnv =
388
389
390
           case lookupBlockEnv procMap bid of
             Just ProcPoint -> add graphEnv bid bid b
             Just (ReachedBy set) ->
391
               case blockSetToList set of
392
393
                 []   -> graphEnv
                 [id] -> add graphEnv id bid b 
394
                 _    -> panic "Each block should be reachable from only one ProcPoint"
395
             Nothing -> pprPanic "block not reached by a proc point?" (ppr bid)
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
396
397
398
         add graphEnv procId bid b = extendBlockEnv graphEnv procId graph'
               where graph  = lookupBlockEnv graphEnv procId `orElse` emptyBlockEnv
                     graph' = extendBlockEnv graph bid b
399
     graphEnv <- return $ fold_blocks addBlock emptyBlockEnv g
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
400
     -- Build a map from proc point BlockId to labels for their new procedures
401
     -- Due to common blockification, we may overestimate the set of procpoints.
402
403
     let add_label map pp = return $ addToFM map pp lbl
           where lbl = if pp == entry then entry_label else blockLbl pp
404
405
     procLabels <- foldM add_label emptyFM
                         (filter (elemBlockEnv blocks) (blockSetToList procPoints))
406
407
408
409
410
411
412
413
414
415
416
417
     -- For each procpoint, we need to know the SP offset on entry.
     -- If the procpoint is:
     --  - continuation of a call, the SP offset is in the call
     --  - otherwise, 0 -- no overflow for passing those variables
     let add_sp_off b env =
           case last (unzip b) of
             LastOther (LastCall {cml_cont = Just succ, cml_ret_args = off,
                                  cml_ret_off = updfr_off}) ->
               extendBlockEnv env succ (off, updfr_off)
             _ -> env
         spEntryMap = fold_blocks add_sp_off (mkBlockEnv [(entry, stackInfo)]) g
         getStackInfo id = lookupBlockEnv spEntryMap id `orElse` (0, Nothing)
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
418
419
420
421
     -- In each new graph, add blocks jumping off to the new procedures,
     -- and replace branches to procpoints with branches to the jump-off blocks
     let add_jump_block (env, bs) (pp, l) =
           do bid <- liftM mkBlockId getUniqueM
422
423
424
              let b = Block bid (ZLast (LastOther jump))
                  (argSpace, _) = getStackInfo pp
                  jump = LastCall (CmmLit (CmmLabel l')) Nothing argSpace 0 Nothing
425
426
427
                  l' = if elemBlockSet pp callPPs then entryLblToInfoLbl l else l
              return (extendBlockEnv env pp bid, b : bs)
         add_jumps (newGraphEnv) (ppId, blockEnv) =
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
           do let needed_jumps = -- find which procpoints we currently branch to
                    foldBlockEnv' add_if_branch_to_pp [] blockEnv
                  add_if_branch_to_pp block rst =
                    case last (unzip block) of
                      LastOther (LastBranch id) -> add_if_pp id rst
                      LastOther (LastCondBranch _ ti fi) ->
                        add_if_pp ti (add_if_pp fi rst)
                      LastOther (LastSwitch _ tbl) -> foldr add_if_pp rst (catMaybes tbl)
                      _ -> rst
                  add_if_pp id rst = case lookupFM procLabels id of
                                       Just x -> (id, x) : rst
                                       Nothing -> rst
              (jumpEnv, jumpBlocks) <-
                 foldM add_jump_block (emptyBlockEnv, []) needed_jumps
                  -- update the entry block
443
444
              let b = expectJust "block in env" $ lookupBlockEnv blockEnv ppId
                  off = getStackInfo ppId
445
                  blockEnv' = extendBlockEnv blockEnv ppId b
446
                  -- replace branches to procpoints with branches to jumps
447
                  LGraph _ blockEnv'' = replaceBranches jumpEnv $ LGraph ppId blockEnv'
448
                  -- add the jump blocks to the graph
449
                  blockEnv''' = foldl (flip insertBlock) blockEnv'' jumpBlocks
450
              let g' = (off, LGraph ppId blockEnv''')
451
452
              -- pprTrace "g' pre jumps" (ppr g') $ do
              return (extendBlockEnv newGraphEnv ppId g')
453
     graphEnv <- foldM add_jumps emptyBlockEnv $ blockEnvToList graphEnv
454
     let to_proc (bid, g) | elemBlockSet bid callPPs =
455
           if bid == entry then 
456
             CmmProc (CmmInfo gc upd_fr info_tbl) top_l top_args (replacePPIds g)
457
           else
458
             CmmProc emptyContInfoTable lbl [] (replacePPIds g)
459
460
           where lbl = expectJust "pp label" $ lookupFM procLabels bid
         to_proc (bid, g) =
461
           CmmProc (CmmInfo Nothing Nothing CmmNonInfoTable) lbl [] (replacePPIds g)
462
             where lbl = expectJust "pp label" $ lookupFM procLabels bid
463
464
465
466
467
468
469
         -- References to procpoint IDs can now be replaced with the infotable's label
         replacePPIds (x, g) = (x, map_nodes id (mapExpMiddle repl) (mapExpLast repl) g)
           where repl e@(CmmLit (CmmBlock bid)) =
                   case lookupFM procLabels bid of
                     Just l  -> CmmLit (CmmLabel (entryLblToInfoLbl l))
                     Nothing -> e
                 repl e = e
470
471
472
     -- The C back end expects to see return continuations before the call sites.
     -- Here, we sort them in reverse order -- it gets reversed later.
     let (_, block_order) = foldl add_block_num (0::Int, emptyBlockEnv) (postorder_dfs g)
473
         add_block_num (i, map) (Block bid _) = (i+1, extendBlockEnv map bid i)
474
475
476
477
         sort_fn (bid, _) (bid', _) =
           compare (expectJust "block_order" $ lookupBlockEnv block_order bid)
                   (expectJust "block_order" $ lookupBlockEnv block_order bid')
     procs <- return $ map to_proc $ sortBy sort_fn $ blockEnvToList graphEnv
478
479
480
     return -- pprTrace "procLabels" (ppr procLabels)
            -- pprTrace "splitting graphs" (ppr procs)
            procs
481
splitAtProcPoints _ _ _ _ t@(CmmData _ _) = return [t]
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553

----------------------------------------------------------------

{-
Note [Direct reachability]

Block B is directly reachable from proc point P iff control can flow
from P to B without passing through an intervening proc point.
-}

----------------------------------------------------------------

{-
Note [No simple dataflow]

Sadly, it seems impossible to compute the proc points using a single
dataflow pass.  One might attempt to use this simple lattice:

  data Location = Unknown
                | InProc BlockId -- node is in procedure headed by the named proc point
                | ProcPoint      -- node is itself a proc point   

At a join, a node in two different blocks becomes a proc point.  
The difficulty is that the change of information during iterative
computation may promote a node prematurely.  Here's a program that
illustrates the difficulty:

  f () {
  entry:
    ....
  L1:
    if (...) { ... }
    else { ... }

  L2: if (...) { g(); goto L1; }
      return x + y;
  }

The only proc-point needed (besides the entry) is L1.  But in an
iterative analysis, consider what happens to L2.  On the first pass
through, it rises from Unknown to 'InProc entry', but when L1 is
promoted to a proc point (because it's the successor of g()), L1's
successors will be promoted to 'InProc L1'.  The problem hits when the
new fact 'InProc L1' flows into L2 which is already bound to 'InProc entry'.
The join operation makes it a proc point when in fact it needn't be,
because its immediate dominator L1 is already a proc point and there
are no other proc points that directly reach L2.
-}



{- Note [Separate Adams optimization]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It may be worthwhile to attempt the Adams optimization by rewriting
the graph before the assignment of proc-point protocols.  Here are a
couple of rules:
                                                                  
  g() returns to k;                    g() returns to L;          
  k: CopyIn c ress; goto L:             
   ...                        ==>        ...                       
  L: // no CopyIn node here            L: CopyIn c ress; 

                                                                  
And when c == c' and ress == ress', this also:

  g() returns to k;                    g() returns to L;          
  k: CopyIn c ress; goto L:             
   ...                        ==>        ...                       
  L: CopyIn c' ress'                   L: CopyIn c' ress' ; 

In both cases the goal is to eliminate k.
-}