CmmContFlowOpt.hs 8.79 KB
Newer Older
1

2 3
module CmmContFlowOpt
    ( runCmmOpts, cmmCfgOpts, cmmCfgOptsZ
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
4
    , branchChainElimZ, removeUnreachableBlocksZ, predMap
5
    , replaceLabelsZ, replaceBranches, runCmmContFlowOptsZs
6 7 8
    )
where

9
import BlockId
10 11 12
import Cmm
import CmmTx
import qualified ZipCfg as G
13
import ZipCfg
14
import ZipCfgCmmRep
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
15

16
import Maybes
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
17
import Monad
18
import Outputable
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
19 20
import Panic
import Prelude hiding (unzip, zip)
21 22 23
import Util

------------------------------------
24 25 26 27
runCmmContFlowOptsZs :: [CmmZ] -> [CmmZ]
runCmmContFlowOptsZs prog
  = [ runTx (runCmmOpts cmmCfgOptsZ) cmm_top
    | cmm_top <- prog ]
28 29 30 31 32

cmmCfgOpts  :: Tx (ListGraph CmmStmt)
cmmCfgOptsZ :: Tx CmmGraph

cmmCfgOpts  = branchChainElim  -- boring, but will get more exciting later
33 34
cmmCfgOptsZ g =
    (branchChainElimZ `seqTx` blockConcatZ `seqTx` removeUnreachableBlocksZ) g
35 36 37 38 39 40 41 42 43 44
        -- Here branchChainElim can ultimately be replaced
        -- with a more exciting combination of optimisations

runCmmOpts :: Tx g -> Tx (GenCmm d h g)
runCmmOpts opt = mapProcs (optGraph opt)

optGraph :: Tx g -> Tx (GenCmmTop d h g)
optGraph _   top@(CmmData {}) = noTx top
optGraph opt (CmmProc info lbl formals g) = fmap (CmmProc info lbl formals) (opt g)

45 46 47 48
------------------------------------
mapProcs :: Tx (GenCmmTop d h s) -> Tx (GenCmm d h s)
mapProcs f (Cmm tops) = fmap Cmm (mapTx f tops)

49 50
----------------------------------------------------------------
branchChainElim :: Tx (ListGraph CmmStmt)
51 52 53
-- If L is not captured in an instruction, we can remove any
-- basic block of the form L: goto L', and replace L with L' everywhere else.
-- How does L get captured? In a CallArea.
54 55 56 57 58 59 60 61 62 63 64 65 66
branchChainElim (ListGraph blocks)
  | null lone_branch_blocks     -- No blocks to remove
  = noTx (ListGraph blocks)
  | otherwise
  = aTx (ListGraph new_blocks)
  where
    (lone_branch_blocks, others) = partitionWith isLoneBranch blocks
    new_blocks = map (replaceLabels env) others
    env = mkClosureBlockEnv lone_branch_blocks

isLoneBranch :: CmmBasicBlock -> Either (BlockId, BlockId) CmmBasicBlock
isLoneBranch (BasicBlock id [CmmBranch target]) | id /= target = Left (id, target)
isLoneBranch other_block                                       = Right other_block
Thomas Schilling's avatar
Thomas Schilling committed
67
   -- An infinite loop is not a link in a branch chain!
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

replaceLabels :: BlockEnv BlockId -> CmmBasicBlock -> CmmBasicBlock
replaceLabels env (BasicBlock id stmts)
  = BasicBlock id (map replace stmts)
  where
    replace (CmmBranch id)       = CmmBranch (lookup id)
    replace (CmmCondBranch e id) = CmmCondBranch e (lookup id)
    replace (CmmSwitch e tbl)    = CmmSwitch e (map (fmap lookup) tbl)
    replace other_stmt           = other_stmt

    lookup id = lookupBlockEnv env id `orElse` id 
----------------------------------------------------------------
branchChainElimZ :: Tx CmmGraph
-- Remove any basic block of the form L: goto L',
-- and replace L with L' everywhere else
83
branchChainElimZ g@(G.LGraph eid args _)
84 85 86
  | null lone_branch_blocks     -- No blocks to remove
  = noTx g
  | otherwise
87
  = aTx $ replaceLabelsZ env $ G.of_block_list eid args (self_branches ++ others)
88 89
  where
    (lone_branch_blocks, others) = partitionWith isLoneBranchZ (G.to_block_list g)
90
    env = mkClosureBlockEnvZ lone_branch_blocks
91
    self_branches =
92 93 94 95 96 97
      let loop_to (id, _) =
            if lookup id == id then
              Just (G.Block id emptyStackInfo (G.ZLast (G.mkBranchNode id)))
            else
              Nothing
      in  mapMaybe loop_to lone_branch_blocks
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
98
    lookup id = lookupBlockEnv env id `orElse` id 
99

100 101
-- Be careful not to mark a block as a lone branch if it carries
-- important information about incoming arguments or the update frame.
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
102
isLoneBranchZ :: CmmBlock -> Either (BlockId, BlockId) CmmBlock
103 104
isLoneBranchZ (G.Block id (StackInfo {argBytes = Nothing, returnOff = Nothing})
              (G.ZLast (G.LastOther (LastBranch target))))
105 106
    | id /= target  = Left (id,target)
isLoneBranchZ other = Right other
Thomas Schilling's avatar
Thomas Schilling committed
107
   -- An infinite loop is not a link in a branch chain!
108

dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
109
replaceLabelsZ :: BlockEnv BlockId -> CmmGraph -> CmmGraph
110
replaceLabelsZ env = replace_eid . G.map_nodes id middle last
111
  where
112
    replace_eid (G.LGraph eid off blocks) = G.LGraph (lookup eid) off blocks
113 114 115 116 117 118 119
    middle = mapExpDeepMiddle exp
    last l = mapExpDeepLast   exp (last' l)
    last' (LastBranch bid) = LastBranch (lookup bid)
    last' (LastCondBranch p t f) = LastCondBranch p (lookup t) (lookup f)
    last' (LastSwitch e arms) = LastSwitch e (map (liftM lookup) arms)
    last' (LastCall t k a r) = LastCall t (liftM lookup k) a r
    exp (CmmLit (CmmBlock bid)) = CmmLit (CmmBlock (lookup bid))
120 121
    exp   (CmmStackSlot (CallArea (Young id)) i) =
      CmmStackSlot (CallArea (Young (lookup id))) i
122 123 124 125 126 127 128 129 130 131
    exp e = e
    lookup id = fmap lookup (lookupBlockEnv env id) `orElse` id 

replaceBranches :: BlockEnv BlockId -> CmmGraph -> CmmGraph
replaceBranches env g = map_nodes id id last g
  where
    last (LastBranch id)          = LastBranch (lookup id)
    last (LastCondBranch e ti fi) = LastCondBranch e (lookup ti) (lookup fi)
    last (LastSwitch e tbl)       = LastSwitch e (map (fmap lookup) tbl)
    last l@(LastCall {})          = l
132
    lookup id = fmap lookup (lookupBlockEnv env id) `orElse` id 
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
133 134 135 136 137 138

----------------------------------------------------------------
-- Build a map from a block to its set of predecessors. Very useful.
predMap :: G.LastNode l => G.LGraph m l -> BlockEnv BlockSet
predMap g = G.fold_blocks add_preds emptyBlockEnv g -- find the back edges
  where add_preds b env = foldl (add b) env (G.succs b)
139
        add (G.Block bid _ _) env b' =
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
140 141 142 143 144 145
          extendBlockEnv env b' $
                extendBlockSet (lookupBlockEnv env b' `orElse` emptyBlockSet) bid
----------------------------------------------------------------
-- If a block B branches to a label L, and L has no other predecessors,
-- then we can splice the block starting with L onto the end of B.
-- Because this optmization can be inhibited by unreachable blocks,
146
-- we first take a pass to drops unreachable blocks.
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
147
-- Order matters, so we work bottom up (reverse postorder DFS).
148 149
--
-- To ensure correctness, we have to make sure that the BlockId of the block
150
-- we are about to eliminate is not named in another instruction.
151
--
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
152
-- Note: This optimization does _not_ subsume branch chain elimination.
153 154
blockConcatZ  :: Tx CmmGraph
blockConcatZ = removeUnreachableBlocksZ `seqTx` blockConcatZ'
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
155
blockConcatZ' :: Tx CmmGraph
156
blockConcatZ' g@(G.LGraph eid off blocks) =
157
  tx $ replaceLabelsZ concatMap $ G.LGraph eid off blocks'
158 159 160 161
  where (changed, blocks', concatMap) =
           foldr maybe_concat (False, blocks, emptyBlockEnv) $ G.postorder_dfs g
        maybe_concat b@(G.Block bid _ _) (changed, blocks', concatMap) =
          let unchanged = (changed, extendBlockEnv blocks' bid b, concatMap)
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
162 163
          in case G.goto_end $ G.unzip b of
               (h, G.LastOther (LastBranch b')) ->
164
                  if canConcatWith b' then
165 166
                    (True, extendBlockEnv blocks' bid $ splice blocks' h b',
                     extendBlockEnv concatMap b' bid)
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
167 168 169
                  else unchanged
               _ -> unchanged
        num_preds bid = liftM sizeBlockSet (lookupBlockEnv backEdges bid) `orElse` 0
170 171 172 173
        canConcatWith b' =
          case lookupBlockEnv blocks b' of
            Just (G.Block _ (StackInfo {returnOff = Nothing}) _) -> num_preds b' == 1
            _ -> False
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
174 175 176
        backEdges = predMap g
        splice blocks' h bid' =
          case lookupBlockEnv blocks' bid' of
177 178 179
            Just (G.Block _ (StackInfo {returnOff = Nothing}) t) ->
              G.zip $ G.ZBlock h t
            Just (G.Block _ _ _) ->
180
              panic "trying to concatenate but successor block has incoming args"
181
            Nothing -> pprPanic "unknown successor block" (ppr bid' <+> ppr blocks' <+> ppr blocks)
dias@eecs.harvard.edu's avatar
dias@eecs.harvard.edu committed
182
        tx = if changed then aTx else noTx
183 184 185 186 187 188 189 190
----------------------------------------------------------------
mkClosureBlockEnv :: [(BlockId, BlockId)] -> BlockEnv BlockId
mkClosureBlockEnv blocks = mkBlockEnv $ map follow blocks
    where singleEnv = mkBlockEnv blocks
          follow (id, next) = (id, endChain id next)
          endChain orig id = case lookupBlockEnv singleEnv id of
                               Just id' | id /= orig -> endChain orig id'
                               _ -> id
191 192 193 194 195 196 197
mkClosureBlockEnvZ :: [(BlockId, BlockId)] -> BlockEnv BlockId
mkClosureBlockEnvZ blocks = mkBlockEnv $ map follow blocks
    where singleEnv = mkBlockEnv blocks
          follow (id, next) = (id, endChain id next)
          endChain orig id = case lookupBlockEnv singleEnv id of
                               Just id' | id /= orig -> endChain orig id'
                               _ -> id
198 199
----------------------------------------------------------------
removeUnreachableBlocksZ :: Tx CmmGraph
200
removeUnreachableBlocksZ g@(G.LGraph id off blocks) =
201 202
  if length blocks' < sizeBEnv blocks then aTx $ G.of_block_list id off blocks'
  else noTx g
203
    where blocks' = G.postorder_dfs g