UnreachableBlockElim.cpp 7.5 KB

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