1 //===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This pass is an extremely simple version of the SimplifyCFG pass. Its sole
10 // job is to delete LLVM basic blocks that are not reachable from the entry
11 // node. To do this, it performs a simple depth first traversal of the CFG,
12 // then deletes any unvisited nodes.
14 // Note that this pass is really a hack. In particular, the instruction
15 // selectors for various targets should just not generate code for unreachable
16 // blocks. Until LLVM has a more systematic way of defining instruction
17 // selectors, however, we cannot really expect them to handle additional
20 //===----------------------------------------------------------------------===//
22 #include "llvm/CodeGen/UnreachableBlockElim.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/TargetInstrInfo.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 class UnreachableBlockElimLegacyPass
: public FunctionPass
{
40 bool runOnFunction(Function
&F
) override
{
41 return llvm::EliminateUnreachableBlocks(F
);
45 static char ID
; // Pass identification, replacement for typeid
46 UnreachableBlockElimLegacyPass() : FunctionPass(ID
) {
47 initializeUnreachableBlockElimLegacyPassPass(
48 *PassRegistry::getPassRegistry());
51 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
52 AU
.addPreserved
<DominatorTreeWrapperPass
>();
56 char UnreachableBlockElimLegacyPass::ID
= 0;
57 INITIALIZE_PASS(UnreachableBlockElimLegacyPass
, "unreachableblockelim",
58 "Remove unreachable blocks from the CFG", false, false)
60 FunctionPass
*llvm::createUnreachableBlockEliminationPass() {
61 return new UnreachableBlockElimLegacyPass();
64 PreservedAnalyses
UnreachableBlockElimPass::run(Function
&F
,
65 FunctionAnalysisManager
&AM
) {
66 bool Changed
= llvm::EliminateUnreachableBlocks(F
);
68 return PreservedAnalyses::all();
70 PA
.preserve
<DominatorTreeAnalysis
>();
75 class UnreachableMachineBlockElim
: public MachineFunctionPass
{
76 bool runOnMachineFunction(MachineFunction
&F
) override
;
77 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
80 static char ID
; // Pass identification, replacement for typeid
81 UnreachableMachineBlockElim() : MachineFunctionPass(ID
) {}
84 char UnreachableMachineBlockElim::ID
= 0;
86 INITIALIZE_PASS(UnreachableMachineBlockElim
, "unreachable-mbb-elimination",
87 "Remove unreachable machine basic blocks", false, false)
89 char &llvm::UnreachableMachineBlockElimID
= UnreachableMachineBlockElim::ID
;
91 void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage
&AU
) const {
92 AU
.addPreserved
<MachineLoopInfo
>();
93 AU
.addPreserved
<MachineDominatorTree
>();
94 MachineFunctionPass::getAnalysisUsage(AU
);
97 bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction
&F
) {
98 df_iterator_default_set
<MachineBasicBlock
*> Reachable
;
99 bool ModifiedPHI
= false;
101 MachineDominatorTree
*MDT
= getAnalysisIfAvailable
<MachineDominatorTree
>();
102 MachineLoopInfo
*MLI
= getAnalysisIfAvailable
<MachineLoopInfo
>();
104 // Mark all reachable blocks.
105 for (MachineBasicBlock
*BB
: depth_first_ext(&F
, Reachable
))
106 (void)BB
/* Mark all reachable blocks */;
108 // Loop over all dead blocks, remembering them and deleting all instructions
110 std::vector
<MachineBasicBlock
*> DeadBlocks
;
111 for (MachineBasicBlock
&BB
: F
) {
112 // Test for deadness.
113 if (!Reachable
.count(&BB
)) {
114 DeadBlocks
.push_back(&BB
);
116 // Update dominator and loop info.
117 if (MLI
) MLI
->removeBlock(&BB
);
118 if (MDT
&& MDT
->getNode(&BB
)) MDT
->eraseNode(&BB
);
120 while (BB
.succ_begin() != BB
.succ_end()) {
121 MachineBasicBlock
* succ
= *BB
.succ_begin();
123 MachineBasicBlock::iterator start
= succ
->begin();
124 while (start
!= succ
->end() && start
->isPHI()) {
125 for (unsigned i
= start
->getNumOperands() - 1; i
>= 2; i
-=2)
126 if (start
->getOperand(i
).isMBB() &&
127 start
->getOperand(i
).getMBB() == &BB
) {
128 start
->removeOperand(i
);
129 start
->removeOperand(i
-1);
135 BB
.removeSuccessor(BB
.succ_begin());
140 // Actually remove the blocks now.
141 for (MachineBasicBlock
*BB
: DeadBlocks
) {
142 // Remove any call site information for calls in the block.
143 for (auto &I
: BB
->instrs())
144 if (I
.shouldUpdateCallSiteInfo())
145 BB
->getParent()->eraseCallSiteInfo(&I
);
147 BB
->eraseFromParent();
150 // Cleanup PHI nodes.
151 for (MachineBasicBlock
&BB
: F
) {
152 // Prune unneeded PHI entries.
153 SmallPtrSet
<MachineBasicBlock
*, 8> preds(BB
.pred_begin(),
155 MachineBasicBlock::iterator phi
= BB
.begin();
156 while (phi
!= BB
.end() && phi
->isPHI()) {
157 for (unsigned i
= phi
->getNumOperands() - 1; i
>= 2; i
-=2)
158 if (!preds
.count(phi
->getOperand(i
).getMBB())) {
159 phi
->removeOperand(i
);
160 phi
->removeOperand(i
-1);
164 if (phi
->getNumOperands() == 3) {
165 const MachineOperand
&Input
= phi
->getOperand(1);
166 const MachineOperand
&Output
= phi
->getOperand(0);
167 Register InputReg
= Input
.getReg();
168 Register OutputReg
= Output
.getReg();
169 assert(Output
.getSubReg() == 0 && "Cannot have output subregister");
172 if (InputReg
!= OutputReg
) {
173 MachineRegisterInfo
&MRI
= F
.getRegInfo();
174 unsigned InputSub
= Input
.getSubReg();
176 MRI
.constrainRegClass(InputReg
, MRI
.getRegClass(OutputReg
)) &&
178 MRI
.replaceRegWith(OutputReg
, InputReg
);
180 // The input register to the PHI has a subregister or it can't be
181 // constrained to the proper register class or it is undef:
182 // insert a COPY instead of simply replacing the output
184 const TargetInstrInfo
*TII
= F
.getSubtarget().getInstrInfo();
185 BuildMI(BB
, BB
.getFirstNonPHI(), phi
->getDebugLoc(),
186 TII
->get(TargetOpcode::COPY
), OutputReg
)
187 .addReg(InputReg
, getRegState(Input
), InputSub
);
189 phi
++->eraseFromParent();
200 return (!DeadBlocks
.empty() || ModifiedPHI
);