+ 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
+ lookup id = fmap lookup (lookupBlockEnv env id) `orElse` id
+
+----------------------------------------------------------------
+-- 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)
+ add (G.Block bid _) env b' =
+ extendBlockEnv env b' $
+ extendBlockSet (lookupBlockEnv env b' `orElse` emptyBlockSet) bid
+----------------------------------------------------------------
+-- If a block B branches to a label L, L is not the entry block,
+-- and L has no other predecessors,
+-- then we can splice the block starting with L onto the end of B.
+-- Because this optimization can be inhibited by unreachable blocks,
+-- we first take a pass to drops unreachable blocks.
+-- Order matters, so we work bottom up (reverse postorder DFS).
+--
+-- To ensure correctness, we have to make sure that the BlockId of the block
+-- we are about to eliminate is not named in another instruction.
+--
+-- Note: This optimization does _not_ subsume branch chain elimination.
+blockConcatZ :: Tx CmmGraph
+blockConcatZ = removeUnreachableBlocksZ `seqTx` blockConcatZ'
+blockConcatZ' :: Tx CmmGraph
+blockConcatZ' g@(G.LGraph eid blocks) =
+ tx $ replaceLabelsZ concatMap $ G.LGraph eid blocks'
+ 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)
+ in case G.goto_end $ G.unzip b of
+ (h, G.LastOther (LastBranch b')) ->
+ if canConcatWith b' then
+ (True, extendBlockEnv blocks' bid $ splice blocks' h b',
+ extendBlockEnv concatMap b' bid)
+ else unchanged
+ _ -> unchanged
+ num_preds bid = liftM sizeBlockSet (lookupBlockEnv backEdges bid) `orElse` 0
+ canConcatWith b' = b' /= eid && num_preds b' == 1
+ backEdges = predMap g
+ splice blocks' h bid' =
+ case lookupBlockEnv blocks' bid' of
+ Just (G.Block _ t) -> G.zip $ G.ZBlock h t
+ Nothing -> panic "unknown successor block"
+ tx = if changed then aTx else noTx