SimplifyCFGPass.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. //===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements dead code elimination and basic block merging, along
  11. // with a collection of other peephole control flow optimizations. For example:
  12. //
  13. // * Removes basic blocks with no predecessors.
  14. // * Merges a basic block into its predecessor if there is only one and the
  15. // predecessor only has one successor.
  16. // * Eliminates PHI nodes for basic blocks with a single predecessor.
  17. // * Eliminates a basic block that only contains an unconditional branch.
  18. // * Changes invoke instructions to nounwind functions to be calls.
  19. // * Change things like "if (x) if (y)" into "if (x&y)".
  20. // * etc..
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "llvm/Transforms/Scalar/SimplifyCFG.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/Analysis/AssumptionCache.h"
  28. #include "llvm/Analysis/TargetTransformInfo.h"
  29. #include "llvm/IR/Attributes.h"
  30. #include "llvm/IR/CFG.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/IR/IntrinsicInst.h"
  35. #include "llvm/IR/Module.h"
  36. #include "llvm/Pass.h"
  37. #include "llvm/Support/CommandLine.h"
  38. #include "llvm/Transforms/Utils/Local.h"
  39. #include "llvm/Transforms/Scalar.h"
  40. using namespace llvm;
  41. #define DEBUG_TYPE "simplifycfg"
  42. #if 0 // HLSL Change Starts
  43. static cl::opt<unsigned>
  44. UserBonusInstThreshold("bonus-inst-threshold", cl::Hidden, cl::init(1),
  45. cl::desc("Control the number of bonus instructions (default = 1)"));
  46. #else
  47. unsigned UserBonusInstThreshold = 1;
  48. #endif
  49. STATISTIC(NumSimpl, "Number of blocks simplified");
  50. /// If we have more than one empty (other than phi node) return blocks,
  51. /// merge them together to promote recursive block merging.
  52. static bool mergeEmptyReturnBlocks(Function &F) {
  53. bool Changed = false;
  54. BasicBlock *RetBlock = nullptr;
  55. // Scan all the blocks in the function, looking for empty return blocks.
  56. for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) {
  57. BasicBlock &BB = *BBI++;
  58. // Only look at return blocks.
  59. ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
  60. if (!Ret) continue;
  61. // Only look at the block if it is empty or the only other thing in it is a
  62. // single PHI node that is the operand to the return.
  63. if (Ret != &BB.front()) {
  64. // Check for something else in the block.
  65. BasicBlock::iterator I = Ret;
  66. --I;
  67. // Skip over debug info.
  68. while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
  69. --I;
  70. if (!isa<DbgInfoIntrinsic>(I) &&
  71. (!isa<PHINode>(I) || I != BB.begin() ||
  72. Ret->getNumOperands() == 0 ||
  73. Ret->getOperand(0) != I))
  74. continue;
  75. }
  76. // If this is the first returning block, remember it and keep going.
  77. if (!RetBlock) {
  78. RetBlock = &BB;
  79. continue;
  80. }
  81. // Otherwise, we found a duplicate return block. Merge the two.
  82. Changed = true;
  83. // Case when there is no input to the return or when the returned values
  84. // agree is trivial. Note that they can't agree if there are phis in the
  85. // blocks.
  86. if (Ret->getNumOperands() == 0 ||
  87. Ret->getOperand(0) ==
  88. cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) {
  89. BB.replaceAllUsesWith(RetBlock);
  90. BB.eraseFromParent();
  91. continue;
  92. }
  93. // If the canonical return block has no PHI node, create one now.
  94. PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin());
  95. if (!RetBlockPHI) {
  96. Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0);
  97. pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock);
  98. RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(),
  99. std::distance(PB, PE), "merge",
  100. &RetBlock->front());
  101. for (pred_iterator PI = PB; PI != PE; ++PI)
  102. RetBlockPHI->addIncoming(InVal, *PI);
  103. RetBlock->getTerminator()->setOperand(0, RetBlockPHI);
  104. }
  105. // Turn BB into a block that just unconditionally branches to the return
  106. // block. This handles the case when the two return blocks have a common
  107. // predecessor but that return different things.
  108. RetBlockPHI->addIncoming(Ret->getOperand(0), &BB);
  109. BB.getTerminator()->eraseFromParent();
  110. BranchInst::Create(RetBlock, &BB);
  111. }
  112. return Changed;
  113. }
  114. /// Call SimplifyCFG on all the blocks in the function,
  115. /// iterating until no more changes are made.
  116. static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI,
  117. AssumptionCache *AC,
  118. unsigned BonusInstThreshold) {
  119. bool Changed = false;
  120. bool LocalChange = true;
  121. while (LocalChange) {
  122. LocalChange = false;
  123. // Loop over all of the basic blocks and remove them if they are unneeded.
  124. for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
  125. if (SimplifyCFG(BBIt++, TTI, BonusInstThreshold, AC)) {
  126. LocalChange = true;
  127. ++NumSimpl;
  128. }
  129. }
  130. Changed |= LocalChange;
  131. }
  132. return Changed;
  133. }
  134. static bool simplifyFunctionCFG(Function &F, const TargetTransformInfo &TTI,
  135. AssumptionCache *AC, int BonusInstThreshold) {
  136. bool EverChanged = removeUnreachableBlocks(F);
  137. EverChanged |= mergeEmptyReturnBlocks(F);
  138. EverChanged |= iterativelySimplifyCFG(F, TTI, AC, BonusInstThreshold);
  139. // If neither pass changed anything, we're done.
  140. if (!EverChanged) return false;
  141. // iterativelySimplifyCFG can (rarely) make some loops dead. If this happens,
  142. // removeUnreachableBlocks is needed to nuke them, which means we should
  143. // iterate between the two optimizations. We structure the code like this to
  144. // avoid rerunning iterativelySimplifyCFG if the second pass of
  145. // removeUnreachableBlocks doesn't do anything.
  146. if (!removeUnreachableBlocks(F))
  147. return true;
  148. do {
  149. EverChanged = iterativelySimplifyCFG(F, TTI, AC, BonusInstThreshold);
  150. EverChanged |= removeUnreachableBlocks(F);
  151. } while (EverChanged);
  152. return true;
  153. }
  154. SimplifyCFGPass::SimplifyCFGPass()
  155. : BonusInstThreshold(UserBonusInstThreshold) {}
  156. SimplifyCFGPass::SimplifyCFGPass(int BonusInstThreshold)
  157. : BonusInstThreshold(BonusInstThreshold) {}
  158. PreservedAnalyses SimplifyCFGPass::run(Function &F,
  159. AnalysisManager<Function> *AM) {
  160. auto &TTI = AM->getResult<TargetIRAnalysis>(F);
  161. auto &AC = AM->getResult<AssumptionAnalysis>(F);
  162. if (!simplifyFunctionCFG(F, TTI, &AC, BonusInstThreshold))
  163. return PreservedAnalyses::none();
  164. return PreservedAnalyses::all();
  165. }
  166. namespace {
  167. struct CFGSimplifyPass : public FunctionPass {
  168. static char ID; // Pass identification, replacement for typeid
  169. unsigned BonusInstThreshold;
  170. std::function<bool(const Function &)> PredicateFtor;
  171. CFGSimplifyPass(int T = -1,
  172. std::function<bool(const Function &)> Ftor = nullptr)
  173. : FunctionPass(ID), PredicateFtor(Ftor) {
  174. BonusInstThreshold = (T == -1) ? UserBonusInstThreshold : unsigned(T);
  175. initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry());
  176. }
  177. bool runOnFunction(Function &F) override {
  178. if (PredicateFtor && !PredicateFtor(F))
  179. return false;
  180. if (skipOptnoneFunction(F))
  181. return false;
  182. AssumptionCache *AC =
  183. &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  184. const TargetTransformInfo &TTI =
  185. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  186. return simplifyFunctionCFG(F, TTI, AC, BonusInstThreshold);
  187. }
  188. void getAnalysisUsage(AnalysisUsage &AU) const override {
  189. AU.addRequired<AssumptionCacheTracker>();
  190. AU.addRequired<TargetTransformInfoWrapperPass>();
  191. }
  192. };
  193. }
  194. char CFGSimplifyPass::ID = 0;
  195. INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
  196. false)
  197. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  198. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  199. INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
  200. false)
  201. // Public interface to the CFGSimplification pass
  202. FunctionPass *
  203. llvm::createCFGSimplificationPass(int Threshold,
  204. std::function<bool(const Function &)> Ftor) {
  205. return new CFGSimplifyPass(Threshold, Ftor);
  206. }