Remove GHC's haskell98 dependency
[ghc-hetmet.git] / compiler / cmm / CmmContFlowOpt.hs
1
2 module CmmContFlowOpt
3     ( runCmmOpts, cmmCfgOpts, cmmCfgOptsZ
4     , branchChainElimZ, removeUnreachableBlocksZ, predMap
5     , replaceLabelsZ, replaceBranches, runCmmContFlowOptsZs
6     )
7 where
8
9 import BlockId
10 import Cmm
11 import CmmTx
12 import qualified ZipCfg as G
13 import ZipCfg
14 import ZipCfgCmmRep
15
16 import Maybes
17 import Control.Monad
18 import Outputable
19 import Prelude hiding (unzip, zip)
20 import Util
21
22 ------------------------------------
23 runCmmContFlowOptsZs :: [CmmZ] -> [CmmZ]
24 runCmmContFlowOptsZs prog
25   = [ runTx (runCmmOpts cmmCfgOptsZ) cmm_top
26     | cmm_top <- prog ]
27
28 cmmCfgOpts  :: Tx (ListGraph CmmStmt)
29 cmmCfgOptsZ :: Tx (a, CmmGraph)
30
31 cmmCfgOpts  = branchChainElim  -- boring, but will get more exciting later
32 cmmCfgOptsZ g =
33   optGraph
34     (branchChainElimZ `seqTx` blockConcatZ `seqTx` removeUnreachableBlocksZ) g
35         -- Here branchChainElim can ultimately be replaced
36         -- with a more exciting combination of optimisations
37
38 runCmmOpts :: Tx g -> Tx (GenCmm d h g)
39 runCmmOpts opt = mapProcs (optProc opt)
40
41 optProc :: Tx g -> Tx (GenCmmTop d h g)
42 optProc _   top@(CmmData {}) = noTx top
43 optProc opt (CmmProc info lbl formals g) =
44   fmap (CmmProc info lbl formals) (opt g)
45
46 optGraph :: Tx g -> Tx (a, g)
47 optGraph opt (a, g) = fmap (\g' -> (a, g')) (opt g)
48
49 ------------------------------------
50 mapProcs :: Tx (GenCmmTop d h s) -> Tx (GenCmm d h s)
51 mapProcs f (Cmm tops) = fmap Cmm (mapTx f tops)
52
53 ----------------------------------------------------------------
54 branchChainElim :: Tx (ListGraph CmmStmt)
55 -- If L is not captured in an instruction, we can remove any
56 -- basic block of the form L: goto L', and replace L with L' everywhere else.
57 -- How does L get captured? In a CallArea.
58 branchChainElim (ListGraph blocks)
59   | null lone_branch_blocks     -- No blocks to remove
60   = noTx (ListGraph blocks)
61   | otherwise
62   = aTx (ListGraph new_blocks)
63   where
64     (lone_branch_blocks, others) = partitionWith isLoneBranch blocks
65     new_blocks = map (replaceLabels env) others
66     env = mkClosureBlockEnv lone_branch_blocks
67
68 isLoneBranch :: CmmBasicBlock -> Either (BlockId, BlockId) CmmBasicBlock
69 isLoneBranch (BasicBlock id [CmmBranch target]) | id /= target = Left (id, target)
70 isLoneBranch other_block                                       = Right other_block
71    -- An infinite loop is not a link in a branch chain!
72
73 replaceLabels :: BlockEnv BlockId -> CmmBasicBlock -> CmmBasicBlock
74 replaceLabels env (BasicBlock id stmts)
75   = BasicBlock id (map replace stmts)
76   where
77     replace (CmmBranch id)       = CmmBranch (lookup id)
78     replace (CmmCondBranch e id) = CmmCondBranch e (lookup id)
79     replace (CmmSwitch e tbl)    = CmmSwitch e (map (fmap lookup) tbl)
80     replace other_stmt           = other_stmt
81
82     lookup id = lookupBlockEnv env id `orElse` id 
83 ----------------------------------------------------------------
84 branchChainElimZ :: Tx CmmGraph
85 -- Remove any basic block of the form L: goto L',
86 -- and replace L with L' everywhere else,
87 -- unless L is the successor of a call instruction and L'
88 -- is the entry block. You don't want to set the successor
89 -- of a function call to the entry block because there is no good way
90 -- to store both the infotables for the call and from the callee,
91 -- while putting the stack pointer in a consistent place.
92 --
93 -- JD isn't quite sure when it's safe to share continuations for different
94 -- function calls -- have to think about where the SP will be,
95 -- so we'll table that problem for now by leaving all call successors alone.
96 branchChainElimZ g@(G.LGraph eid _)
97   | null lone_branch_blocks     -- No blocks to remove
98   = noTx g
99   | otherwise
100   = aTx $ replaceLabelsZ env $ G.of_block_list eid (self_branches ++ others)
101   where
102     blocks = G.to_block_list g
103     (lone_branch_blocks, others) = partitionWith isLoneBranchZ blocks
104     env = mkClosureBlockEnvZ lone_branch_blocks
105     self_branches =
106       let loop_to (id, _) =
107             if lookup id == id then
108               Just (G.Block id (G.ZLast (G.mkBranchNode id)))
109             else
110               Nothing
111       in  mapMaybe loop_to lone_branch_blocks
112     lookup id = lookupBlockEnv env id `orElse` id 
113
114     call_succs = foldl add emptyBlockSet blocks
115       where add succs b =
116               case G.last (G.unzip b) of
117                 LastOther (LastCall _ (Just k) _ _ _) -> extendBlockSet succs k
118                 _ -> succs
119     isLoneBranchZ :: CmmBlock -> Either (BlockId, BlockId) CmmBlock
120     isLoneBranchZ (G.Block id (G.ZLast (G.LastOther (LastBranch target))))
121         | id /= target && not (elemBlockSet id call_succs) = Left (id,target)
122     isLoneBranchZ other = Right other
123        -- An infinite loop is not a link in a branch chain!
124
125 maybeReplaceLabels :: (Last -> Bool) -> BlockEnv BlockId -> CmmGraph -> CmmGraph
126 maybeReplaceLabels lpred env =
127   replace_eid . G.map_nodes id middle last
128    where
129      replace_eid (G.LGraph eid blocks) = G.LGraph (lookup eid) blocks
130      middle = mapExpDeepMiddle exp
131      last l = if lpred l then mapExpDeepLast exp (last' l) else l
132      last' (LastBranch bid) = LastBranch (lookup bid)
133      last' (LastCondBranch p t f) = LastCondBranch p (lookup t) (lookup f)
134      last' (LastSwitch e arms) = LastSwitch e (map (liftM lookup) arms)
135      last' (LastCall t k a res r) = LastCall t (liftM lookup k) a res r
136      exp (CmmLit (CmmBlock bid)) = CmmLit (CmmBlock (lookup bid))
137      exp   (CmmStackSlot (CallArea (Young id)) i) =
138        CmmStackSlot (CallArea (Young (lookup id))) i
139      exp e = e
140      lookup id = fmap lookup (lookupBlockEnv env id) `orElse` id 
141
142 replaceLabelsZ :: BlockEnv BlockId -> CmmGraph -> CmmGraph
143 replaceLabelsZ = maybeReplaceLabels (const True)
144
145 -- replaceBranchLabels :: BlockEnv BlockId -> CmmGraph -> CmmGraph
146 -- replaceBranchLabels env g@(LGraph _ _) = maybeReplaceLabels lpred env g
147 --   where lpred (LastBranch _) = True
148 --         lpred _ = False
149
150 replaceBranches :: BlockEnv BlockId -> CmmGraph -> CmmGraph
151 replaceBranches env g = map_nodes id id last g
152   where
153     last (LastBranch id)          = LastBranch (lookup id)
154     last (LastCondBranch e ti fi) = LastCondBranch e (lookup ti) (lookup fi)
155     last (LastSwitch e tbl)       = LastSwitch e (map (fmap lookup) tbl)
156     last l@(LastCall {})          = l
157     lookup id = fmap lookup (lookupBlockEnv env id) `orElse` id 
158
159 ----------------------------------------------------------------
160 -- Build a map from a block to its set of predecessors. Very useful.
161 predMap :: G.LastNode l => G.LGraph m l -> BlockEnv BlockSet
162 predMap g = G.fold_blocks add_preds emptyBlockEnv g -- find the back edges
163   where add_preds b env = foldl (add b) env (G.succs b)
164         add (G.Block bid _) env b' =
165           extendBlockEnv env b' $
166                 extendBlockSet (lookupBlockEnv env b' `orElse` emptyBlockSet) bid
167 ----------------------------------------------------------------
168 -- If a block B branches to a label L, L is not the entry block,
169 -- and L has no other predecessors,
170 -- then we can splice the block starting with L onto the end of B.
171 -- Because this optimization can be inhibited by unreachable blocks,
172 -- we first take a pass to drops unreachable blocks.
173 -- Order matters, so we work bottom up (reverse postorder DFS).
174 --
175 -- To ensure correctness, we have to make sure that the BlockId of the block
176 -- we are about to eliminate is not named in another instruction.
177 --
178 -- Note: This optimization does _not_ subsume branch chain elimination.
179 blockConcatZ  :: Tx CmmGraph
180 blockConcatZ = removeUnreachableBlocksZ `seqTx` blockConcatZ'
181 blockConcatZ' :: Tx CmmGraph
182 blockConcatZ' g@(G.LGraph eid blocks) =
183   tx $ replaceLabelsZ concatMap $ G.LGraph eid blocks'
184   where (changed, blocks', concatMap) =
185            foldr maybe_concat (False, blocks, emptyBlockEnv) $ G.postorder_dfs g
186         maybe_concat b@(G.Block bid _) (changed, blocks', concatMap) =
187           let unchanged = (changed, extendBlockEnv blocks' bid b, concatMap)
188           in case G.goto_end $ G.unzip b of
189                (h, G.LastOther (LastBranch b')) ->
190                   if canConcatWith b' then
191                     (True, extendBlockEnv blocks' bid $ splice blocks' h b',
192                      extendBlockEnv concatMap b' bid)
193                   else unchanged
194                _ -> unchanged
195         num_preds bid = liftM sizeBlockSet (lookupBlockEnv backEdges bid) `orElse` 0
196         canConcatWith b' = b' /= eid && num_preds b' == 1
197         backEdges = predMap g
198         splice blocks' h bid' =
199           case lookupBlockEnv blocks' bid' of
200             Just (G.Block _ t) -> G.zip $ G.ZBlock h t
201             Nothing -> panic "unknown successor block"
202         tx = if changed then aTx else noTx
203 ----------------------------------------------------------------
204 mkClosureBlockEnv :: [(BlockId, BlockId)] -> BlockEnv BlockId
205 mkClosureBlockEnv blocks = mkBlockEnv $ map follow blocks
206     where singleEnv = mkBlockEnv blocks
207           follow (id, next) = (id, endChain id next)
208           endChain orig id = case lookupBlockEnv singleEnv id of
209                                Just id' | id /= orig -> endChain orig id'
210                                _ -> id
211 mkClosureBlockEnvZ :: [(BlockId, BlockId)] -> BlockEnv BlockId
212 mkClosureBlockEnvZ blocks = mkBlockEnv $ map follow blocks
213     where singleEnv = mkBlockEnv blocks
214           follow (id, next) = (id, endChain id next)
215           endChain orig id = case lookupBlockEnv singleEnv id of
216                                Just id' | id /= orig -> endChain orig id'
217                                _ -> id
218 ----------------------------------------------------------------
219 removeUnreachableBlocksZ :: Tx CmmGraph
220 removeUnreachableBlocksZ g@(G.LGraph id blocks) =
221   if length blocks' < sizeBEnv blocks then aTx $ G.of_block_list id blocks'
222   else noTx g
223     where blocks' = G.postorder_dfs g