1 //===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 // 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. 13 // 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 18 // complexity. 19 // 20 //===----------------------------------------------------------------------===// 21 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/MachineModuleInfo.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/CodeGen/Passes.h" 32 #include "llvm/CodeGen/TargetInstrInfo.h" 33 #include "llvm/IR/CFG.h" 34 #include "llvm/IR/Constant.h" 35 #include "llvm/IR/Dominators.h" 36 #include "llvm/IR/Function.h" 37 #include "llvm/IR/Instructions.h" 38 #include "llvm/IR/Type.h" 39 #include "llvm/Pass.h" 40 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 41 using namespace llvm; 42 43 static bool eliminateUnreachableBlock(Function &F) { 44 df_iterator_default_set<BasicBlock*> Reachable; 45 46 // Mark all reachable blocks. 47 for (BasicBlock *BB : depth_first_ext(&F, Reachable)) 48 (void)BB/* Mark all reachable blocks */; 49 50 // Collect all dead blocks. 51 std::vector<BasicBlock*> DeadBlocks; 52 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) 53 if (!Reachable.count(&*I)) { 54 BasicBlock *BB = &*I; 55 DeadBlocks.push_back(BB); 56 } 57 58 // Delete the dead blocks. 59 DeleteDeadBlocks(DeadBlocks); 60 61 return !DeadBlocks.empty(); 62 } 63 64 namespace { 65 class UnreachableBlockElimLegacyPass : public FunctionPass { 66 bool runOnFunction(Function &F) override { 67 return eliminateUnreachableBlock(F); 68 } 69 70 public: 71 static char ID; // Pass identification, replacement for typeid 72 UnreachableBlockElimLegacyPass() : FunctionPass(ID) { 73 initializeUnreachableBlockElimLegacyPassPass( 74 *PassRegistry::getPassRegistry()); 75 } 76 77 void getAnalysisUsage(AnalysisUsage &AU) const override { 78 AU.addPreserved<DominatorTreeWrapperPass>(); 79 } 80 }; 81 } 82 char UnreachableBlockElimLegacyPass::ID = 0; 83 INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim", 84 "Remove unreachable blocks from the CFG", false, false) 85 86 FunctionPass *llvm::createUnreachableBlockEliminationPass() { 87 return new UnreachableBlockElimLegacyPass(); 88 } 89 90 PreservedAnalyses UnreachableBlockElimPass::run(Function &F, 91 FunctionAnalysisManager &AM) { 92 bool Changed = eliminateUnreachableBlock(F); 93 if (!Changed) 94 return PreservedAnalyses::all(); 95 PreservedAnalyses PA; 96 PA.preserve<DominatorTreeAnalysis>(); 97 return PA; 98 } 99 100 namespace { 101 class UnreachableMachineBlockElim : public MachineFunctionPass { 102 bool runOnMachineFunction(MachineFunction &F) override; 103 void getAnalysisUsage(AnalysisUsage &AU) const override; 104 MachineModuleInfo *MMI; 105 public: 106 static char ID; // Pass identification, replacement for typeid 107 UnreachableMachineBlockElim() : MachineFunctionPass(ID) {} 108 }; 109 } 110 char UnreachableMachineBlockElim::ID = 0; 111 112 INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination", 113 "Remove unreachable machine basic blocks", false, false) 114 115 char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID; 116 117 void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const { 118 AU.addPreserved<MachineLoopInfo>(); 119 AU.addPreserved<MachineDominatorTree>(); 120 MachineFunctionPass::getAnalysisUsage(AU); 121 } 122 123 bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) { 124 df_iterator_default_set<MachineBasicBlock*> Reachable; 125 bool ModifiedPHI = false; 126 127 MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 128 MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>(); 129 MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>(); 130 131 // Mark all reachable blocks. 132 for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable)) 133 (void)BB/* Mark all reachable blocks */; 134 135 // Loop over all dead blocks, remembering them and deleting all instructions 136 // in them. 137 std::vector<MachineBasicBlock*> DeadBlocks; 138 for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) { 139 MachineBasicBlock *BB = &*I; 140 141 // Test for deadness. 142 if (!Reachable.count(BB)) { 143 DeadBlocks.push_back(BB); 144 145 // Update dominator and loop info. 146 if (MLI) MLI->removeBlock(BB); 147 if (MDT && MDT->getNode(BB)) MDT->eraseNode(BB); 148 149 while (BB->succ_begin() != BB->succ_end()) { 150 MachineBasicBlock* succ = *BB->succ_begin(); 151 152 MachineBasicBlock::iterator start = succ->begin(); 153 while (start != succ->end() && start->isPHI()) { 154 for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2) 155 if (start->getOperand(i).isMBB() && 156 start->getOperand(i).getMBB() == BB) { 157 start->RemoveOperand(i); 158 start->RemoveOperand(i-1); 159 } 160 161 start++; 162 } 163 164 BB->removeSuccessor(BB->succ_begin()); 165 } 166 } 167 } 168 169 // Actually remove the blocks now. 170 for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) 171 DeadBlocks[i]->eraseFromParent(); 172 173 // Cleanup PHI nodes. 174 for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) { 175 MachineBasicBlock *BB = &*I; 176 // Prune unneeded PHI entries. 177 SmallPtrSet<MachineBasicBlock*, 8> preds(BB->pred_begin(), 178 BB->pred_end()); 179 MachineBasicBlock::iterator phi = BB->begin(); 180 while (phi != BB->end() && phi->isPHI()) { 181 for (unsigned i = phi->getNumOperands() - 1; i >= 2; i-=2) 182 if (!preds.count(phi->getOperand(i).getMBB())) { 183 phi->RemoveOperand(i); 184 phi->RemoveOperand(i-1); 185 ModifiedPHI = true; 186 } 187 188 if (phi->getNumOperands() == 3) { 189 const MachineOperand &Input = phi->getOperand(1); 190 const MachineOperand &Output = phi->getOperand(0); 191 unsigned InputReg = Input.getReg(); 192 unsigned OutputReg = Output.getReg(); 193 assert(Output.getSubReg() == 0 && "Cannot have output subregister"); 194 ModifiedPHI = true; 195 196 if (InputReg != OutputReg) { 197 MachineRegisterInfo &MRI = F.getRegInfo(); 198 unsigned InputSub = Input.getSubReg(); 199 if (InputSub == 0 && 200 MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) && 201 !Input.isUndef()) { 202 MRI.replaceRegWith(OutputReg, InputReg); 203 } else { 204 // The input register to the PHI has a subregister or it can't be 205 // constrained to the proper register class or it is undef: 206 // insert a COPY instead of simply replacing the output 207 // with the input. 208 const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo(); 209 BuildMI(*BB, BB->getFirstNonPHI(), phi->getDebugLoc(), 210 TII->get(TargetOpcode::COPY), OutputReg) 211 .addReg(InputReg, getRegState(Input), InputSub); 212 } 213 phi++->eraseFromParent(); 214 } 215 continue; 216 } 217 218 ++phi; 219 } 220 } 221 222 F.RenumberBlocks(); 223 224 return (!DeadBlocks.empty() || ModifiedPHI); 225 } 226