SimplifyCFGPass.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. //===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===//
  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 file implements dead code elimination and basic block merging, along
  10. // with a collection of other peephole control flow optimizations. For example:
  11. //
  12. // * Removes basic blocks with no predecessors.
  13. // * Merges a basic block into its predecessor if there is only one and the
  14. // predecessor only has one successor.
  15. // * Eliminates PHI nodes for basic blocks with a single predecessor.
  16. // * Eliminates a basic block that only contains an unconditional branch.
  17. // * Changes invoke instructions to nounwind functions to be calls.
  18. // * Change things like "if (x) if (y)" into "if (x&y)".
  19. // * etc..
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "llvm/ADT/MapVector.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/Analysis/AssumptionCache.h"
  27. #include "llvm/Analysis/CFG.h"
  28. #include "llvm/Analysis/DomTreeUpdater.h"
  29. #include "llvm/Analysis/GlobalsModRef.h"
  30. #include "llvm/Analysis/TargetTransformInfo.h"
  31. #include "llvm/IR/Attributes.h"
  32. #include "llvm/IR/CFG.h"
  33. #include "llvm/IR/DebugInfoMetadata.h"
  34. #include "llvm/IR/Dominators.h"
  35. #include "llvm/IR/Instructions.h"
  36. #include "llvm/IR/IntrinsicInst.h"
  37. #include "llvm/IR/ValueHandle.h"
  38. #include "llvm/InitializePasses.h"
  39. #include "llvm/Pass.h"
  40. #include "llvm/Support/CommandLine.h"
  41. #include "llvm/Transforms/Scalar.h"
  42. #include "llvm/Transforms/Scalar/SimplifyCFG.h"
  43. #include "llvm/Transforms/Utils/Local.h"
  44. #include "llvm/Transforms/Utils/SimplifyCFGOptions.h"
  45. #include <utility>
  46. using namespace llvm;
  47. #define DEBUG_TYPE "simplifycfg"
  48. static cl::opt<unsigned> UserBonusInstThreshold(
  49. "bonus-inst-threshold", cl::Hidden, cl::init(1),
  50. cl::desc("Control the number of bonus instructions (default = 1)"));
  51. static cl::opt<bool> UserKeepLoops(
  52. "keep-loops", cl::Hidden, cl::init(true),
  53. cl::desc("Preserve canonical loop structure (default = true)"));
  54. static cl::opt<bool> UserSwitchRangeToICmp(
  55. "switch-range-to-icmp", cl::Hidden, cl::init(false),
  56. cl::desc(
  57. "Convert switches into an integer range comparison (default = false)"));
  58. static cl::opt<bool> UserSwitchToLookup(
  59. "switch-to-lookup", cl::Hidden, cl::init(false),
  60. cl::desc("Convert switches to lookup tables (default = false)"));
  61. static cl::opt<bool> UserForwardSwitchCond(
  62. "forward-switch-cond", cl::Hidden, cl::init(false),
  63. cl::desc("Forward switch condition to phi ops (default = false)"));
  64. static cl::opt<bool> UserHoistCommonInsts(
  65. "hoist-common-insts", cl::Hidden, cl::init(false),
  66. cl::desc("hoist common instructions (default = false)"));
  67. static cl::opt<bool> UserSinkCommonInsts(
  68. "sink-common-insts", cl::Hidden, cl::init(false),
  69. cl::desc("Sink common instructions (default = false)"));
  70. STATISTIC(NumSimpl, "Number of blocks simplified");
  71. static bool
  72. performBlockTailMerging(Function &F, ArrayRef<BasicBlock *> BBs,
  73. std::vector<DominatorTree::UpdateType> *Updates) {
  74. SmallVector<PHINode *, 1> NewOps;
  75. // We don't want to change IR just because we can.
  76. // Only do that if there are at least two blocks we'll tail-merge.
  77. if (BBs.size() < 2)
  78. return false;
  79. if (Updates)
  80. Updates->reserve(Updates->size() + BBs.size());
  81. BasicBlock *CanonicalBB;
  82. Instruction *CanonicalTerm;
  83. {
  84. auto *Term = BBs[0]->getTerminator();
  85. // Create a canonical block for this function terminator type now,
  86. // placing it *before* the first block that will branch to it.
  87. CanonicalBB = BasicBlock::Create(
  88. F.getContext(), Twine("common.") + Term->getOpcodeName(), &F, BBs[0]);
  89. // We'll also need a PHI node per each operand of the terminator.
  90. NewOps.resize(Term->getNumOperands());
  91. for (auto I : zip(Term->operands(), NewOps)) {
  92. std::get<1>(I) = PHINode::Create(std::get<0>(I)->getType(),
  93. /*NumReservedValues=*/BBs.size(),
  94. CanonicalBB->getName() + ".op");
  95. std::get<1>(I)->insertInto(CanonicalBB, CanonicalBB->end());
  96. }
  97. // Make it so that this canonical block actually has the right
  98. // terminator.
  99. CanonicalTerm = Term->clone();
  100. CanonicalTerm->insertInto(CanonicalBB, CanonicalBB->end());
  101. // If the canonical terminator has operands, rewrite it to take PHI's.
  102. for (auto I : zip(NewOps, CanonicalTerm->operands()))
  103. std::get<1>(I) = std::get<0>(I);
  104. }
  105. // Now, go through each block (with the current terminator type)
  106. // we've recorded, and rewrite it to branch to the new common block.
  107. const DILocation *CommonDebugLoc = nullptr;
  108. for (BasicBlock *BB : BBs) {
  109. auto *Term = BB->getTerminator();
  110. assert(Term->getOpcode() == CanonicalTerm->getOpcode() &&
  111. "All blocks to be tail-merged must be the same "
  112. "(function-terminating) terminator type.");
  113. // Aha, found a new non-canonical function terminator. If it has operands,
  114. // forward them to the PHI nodes in the canonical block.
  115. for (auto I : zip(Term->operands(), NewOps))
  116. std::get<1>(I)->addIncoming(std::get<0>(I), BB);
  117. // Compute the debug location common to all the original terminators.
  118. if (!CommonDebugLoc)
  119. CommonDebugLoc = Term->getDebugLoc();
  120. else
  121. CommonDebugLoc =
  122. DILocation::getMergedLocation(CommonDebugLoc, Term->getDebugLoc());
  123. // And turn BB into a block that just unconditionally branches
  124. // to the canonical block.
  125. Term->eraseFromParent();
  126. BranchInst::Create(CanonicalBB, BB);
  127. if (Updates)
  128. Updates->push_back({DominatorTree::Insert, BB, CanonicalBB});
  129. }
  130. CanonicalTerm->setDebugLoc(CommonDebugLoc);
  131. return true;
  132. }
  133. static bool tailMergeBlocksWithSimilarFunctionTerminators(Function &F,
  134. DomTreeUpdater *DTU) {
  135. SmallMapVector<unsigned /*TerminatorOpcode*/, SmallVector<BasicBlock *, 2>, 4>
  136. Structure;
  137. // Scan all the blocks in the function, record the interesting-ones.
  138. for (BasicBlock &BB : F) {
  139. if (DTU && DTU->isBBPendingDeletion(&BB))
  140. continue;
  141. // We are only interested in function-terminating blocks.
  142. if (!succ_empty(&BB))
  143. continue;
  144. auto *Term = BB.getTerminator();
  145. // Fow now only support `ret`/`resume` function terminators.
  146. // FIXME: lift this restriction.
  147. switch (Term->getOpcode()) {
  148. case Instruction::Ret:
  149. case Instruction::Resume:
  150. break;
  151. default:
  152. continue;
  153. }
  154. // We can't tail-merge block that contains a musttail call.
  155. if (BB.getTerminatingMustTailCall())
  156. continue;
  157. // Calls to experimental_deoptimize must be followed by a return
  158. // of the value computed by experimental_deoptimize.
  159. // I.e., we can not change `ret` to `br` for this block.
  160. if (auto *CI =
  161. dyn_cast_or_null<CallInst>(Term->getPrevNonDebugInstruction())) {
  162. if (Function *F = CI->getCalledFunction())
  163. if (Intrinsic::ID ID = F->getIntrinsicID())
  164. if (ID == Intrinsic::experimental_deoptimize)
  165. continue;
  166. }
  167. // PHI nodes cannot have token type, so if the terminator has an operand
  168. // with token type, we can not tail-merge this kind of function terminators.
  169. if (any_of(Term->operands(),
  170. [](Value *Op) { return Op->getType()->isTokenTy(); }))
  171. continue;
  172. // Canonical blocks are uniqued based on the terminator type (opcode).
  173. Structure[Term->getOpcode()].emplace_back(&BB);
  174. }
  175. bool Changed = false;
  176. std::vector<DominatorTree::UpdateType> Updates;
  177. for (ArrayRef<BasicBlock *> BBs : make_second_range(Structure))
  178. Changed |= performBlockTailMerging(F, BBs, DTU ? &Updates : nullptr);
  179. if (DTU)
  180. DTU->applyUpdates(Updates);
  181. return Changed;
  182. }
  183. /// Call SimplifyCFG on all the blocks in the function,
  184. /// iterating until no more changes are made.
  185. static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI,
  186. DomTreeUpdater *DTU,
  187. const SimplifyCFGOptions &Options) {
  188. bool Changed = false;
  189. bool LocalChange = true;
  190. SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 32> Edges;
  191. FindFunctionBackedges(F, Edges);
  192. SmallPtrSet<BasicBlock *, 16> UniqueLoopHeaders;
  193. for (unsigned i = 0, e = Edges.size(); i != e; ++i)
  194. UniqueLoopHeaders.insert(const_cast<BasicBlock *>(Edges[i].second));
  195. SmallVector<WeakVH, 16> LoopHeaders(UniqueLoopHeaders.begin(),
  196. UniqueLoopHeaders.end());
  197. unsigned IterCnt = 0;
  198. (void)IterCnt;
  199. while (LocalChange) {
  200. assert(IterCnt++ < 1000 && "Iterative simplification didn't converge!");
  201. LocalChange = false;
  202. // Loop over all of the basic blocks and remove them if they are unneeded.
  203. for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
  204. BasicBlock &BB = *BBIt++;
  205. if (DTU) {
  206. assert(
  207. !DTU->isBBPendingDeletion(&BB) &&
  208. "Should not end up trying to simplify blocks marked for removal.");
  209. // Make sure that the advanced iterator does not point at the blocks
  210. // that are marked for removal, skip over all such blocks.
  211. while (BBIt != F.end() && DTU->isBBPendingDeletion(&*BBIt))
  212. ++BBIt;
  213. }
  214. if (simplifyCFG(&BB, TTI, DTU, Options, LoopHeaders)) {
  215. LocalChange = true;
  216. ++NumSimpl;
  217. }
  218. }
  219. Changed |= LocalChange;
  220. }
  221. return Changed;
  222. }
  223. static bool simplifyFunctionCFGImpl(Function &F, const TargetTransformInfo &TTI,
  224. DominatorTree *DT,
  225. const SimplifyCFGOptions &Options) {
  226. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  227. bool EverChanged = removeUnreachableBlocks(F, DT ? &DTU : nullptr);
  228. EverChanged |=
  229. tailMergeBlocksWithSimilarFunctionTerminators(F, DT ? &DTU : nullptr);
  230. EverChanged |= iterativelySimplifyCFG(F, TTI, DT ? &DTU : nullptr, Options);
  231. // If neither pass changed anything, we're done.
  232. if (!EverChanged) return false;
  233. // iterativelySimplifyCFG can (rarely) make some loops dead. If this happens,
  234. // removeUnreachableBlocks is needed to nuke them, which means we should
  235. // iterate between the two optimizations. We structure the code like this to
  236. // avoid rerunning iterativelySimplifyCFG if the second pass of
  237. // removeUnreachableBlocks doesn't do anything.
  238. if (!removeUnreachableBlocks(F, DT ? &DTU : nullptr))
  239. return true;
  240. do {
  241. EverChanged = iterativelySimplifyCFG(F, TTI, DT ? &DTU : nullptr, Options);
  242. EverChanged |= removeUnreachableBlocks(F, DT ? &DTU : nullptr);
  243. } while (EverChanged);
  244. return true;
  245. }
  246. static bool simplifyFunctionCFG(Function &F, const TargetTransformInfo &TTI,
  247. DominatorTree *DT,
  248. const SimplifyCFGOptions &Options) {
  249. assert((!RequireAndPreserveDomTree ||
  250. (DT && DT->verify(DominatorTree::VerificationLevel::Full))) &&
  251. "Original domtree is invalid?");
  252. bool Changed = simplifyFunctionCFGImpl(F, TTI, DT, Options);
  253. assert((!RequireAndPreserveDomTree ||
  254. (DT && DT->verify(DominatorTree::VerificationLevel::Full))) &&
  255. "Failed to maintain validity of domtree!");
  256. return Changed;
  257. }
  258. // Command-line settings override compile-time settings.
  259. static void applyCommandLineOverridesToOptions(SimplifyCFGOptions &Options) {
  260. if (UserBonusInstThreshold.getNumOccurrences())
  261. Options.BonusInstThreshold = UserBonusInstThreshold;
  262. if (UserForwardSwitchCond.getNumOccurrences())
  263. Options.ForwardSwitchCondToPhi = UserForwardSwitchCond;
  264. if (UserSwitchRangeToICmp.getNumOccurrences())
  265. Options.ConvertSwitchRangeToICmp = UserSwitchRangeToICmp;
  266. if (UserSwitchToLookup.getNumOccurrences())
  267. Options.ConvertSwitchToLookupTable = UserSwitchToLookup;
  268. if (UserKeepLoops.getNumOccurrences())
  269. Options.NeedCanonicalLoop = UserKeepLoops;
  270. if (UserHoistCommonInsts.getNumOccurrences())
  271. Options.HoistCommonInsts = UserHoistCommonInsts;
  272. if (UserSinkCommonInsts.getNumOccurrences())
  273. Options.SinkCommonInsts = UserSinkCommonInsts;
  274. }
  275. SimplifyCFGPass::SimplifyCFGPass() {
  276. applyCommandLineOverridesToOptions(Options);
  277. }
  278. SimplifyCFGPass::SimplifyCFGPass(const SimplifyCFGOptions &Opts)
  279. : Options(Opts) {
  280. applyCommandLineOverridesToOptions(Options);
  281. }
  282. void SimplifyCFGPass::printPipeline(
  283. raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
  284. static_cast<PassInfoMixin<SimplifyCFGPass> *>(this)->printPipeline(
  285. OS, MapClassName2PassName);
  286. OS << "<";
  287. OS << "bonus-inst-threshold=" << Options.BonusInstThreshold << ";";
  288. OS << (Options.ForwardSwitchCondToPhi ? "" : "no-") << "forward-switch-cond;";
  289. OS << (Options.ConvertSwitchRangeToICmp ? "" : "no-")
  290. << "switch-range-to-icmp;";
  291. OS << (Options.ConvertSwitchToLookupTable ? "" : "no-")
  292. << "switch-to-lookup;";
  293. OS << (Options.NeedCanonicalLoop ? "" : "no-") << "keep-loops;";
  294. OS << (Options.HoistCommonInsts ? "" : "no-") << "hoist-common-insts;";
  295. OS << (Options.SinkCommonInsts ? "" : "no-") << "sink-common-insts";
  296. OS << ">";
  297. }
  298. PreservedAnalyses SimplifyCFGPass::run(Function &F,
  299. FunctionAnalysisManager &AM) {
  300. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  301. Options.AC = &AM.getResult<AssumptionAnalysis>(F);
  302. DominatorTree *DT = nullptr;
  303. if (RequireAndPreserveDomTree)
  304. DT = &AM.getResult<DominatorTreeAnalysis>(F);
  305. if (F.hasFnAttribute(Attribute::OptForFuzzing)) {
  306. Options.setSimplifyCondBranch(false).setFoldTwoEntryPHINode(false);
  307. } else {
  308. Options.setSimplifyCondBranch(true).setFoldTwoEntryPHINode(true);
  309. }
  310. if (!simplifyFunctionCFG(F, TTI, DT, Options))
  311. return PreservedAnalyses::all();
  312. PreservedAnalyses PA;
  313. if (RequireAndPreserveDomTree)
  314. PA.preserve<DominatorTreeAnalysis>();
  315. return PA;
  316. }
  317. namespace {
  318. struct CFGSimplifyPass : public FunctionPass {
  319. static char ID;
  320. SimplifyCFGOptions Options;
  321. std::function<bool(const Function &)> PredicateFtor;
  322. CFGSimplifyPass(SimplifyCFGOptions Options_ = SimplifyCFGOptions(),
  323. std::function<bool(const Function &)> Ftor = nullptr)
  324. : FunctionPass(ID), Options(Options_), PredicateFtor(std::move(Ftor)) {
  325. initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry());
  326. // Check for command-line overrides of options for debug/customization.
  327. applyCommandLineOverridesToOptions(Options);
  328. }
  329. bool runOnFunction(Function &F) override {
  330. if (skipFunction(F) || (PredicateFtor && !PredicateFtor(F)))
  331. return false;
  332. Options.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  333. DominatorTree *DT = nullptr;
  334. if (RequireAndPreserveDomTree)
  335. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  336. if (F.hasFnAttribute(Attribute::OptForFuzzing)) {
  337. Options.setSimplifyCondBranch(false)
  338. .setFoldTwoEntryPHINode(false);
  339. } else {
  340. Options.setSimplifyCondBranch(true)
  341. .setFoldTwoEntryPHINode(true);
  342. }
  343. auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  344. return simplifyFunctionCFG(F, TTI, DT, Options);
  345. }
  346. void getAnalysisUsage(AnalysisUsage &AU) const override {
  347. AU.addRequired<AssumptionCacheTracker>();
  348. if (RequireAndPreserveDomTree)
  349. AU.addRequired<DominatorTreeWrapperPass>();
  350. AU.addRequired<TargetTransformInfoWrapperPass>();
  351. if (RequireAndPreserveDomTree)
  352. AU.addPreserved<DominatorTreeWrapperPass>();
  353. AU.addPreserved<GlobalsAAWrapperPass>();
  354. }
  355. };
  356. }
  357. char CFGSimplifyPass::ID = 0;
  358. INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
  359. false)
  360. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  361. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  362. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  363. INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
  364. false)
  365. // Public interface to the CFGSimplification pass
  366. FunctionPass *
  367. llvm::createCFGSimplificationPass(SimplifyCFGOptions Options,
  368. std::function<bool(const Function &)> Ftor) {
  369. return new CFGSimplifyPass(Options, std::move(Ftor));
  370. }