LowerSwitch.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
  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. // The LowerSwitch transformation rewrites switch instructions with a sequence
  10. // of branches, which allows targets to get away with not implementing the
  11. // switch instruction until it is convenient.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/LowerSwitch.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/Analysis/AssumptionCache.h"
  20. #include "llvm/Analysis/LazyValueInfo.h"
  21. #include "llvm/Analysis/ValueTracking.h"
  22. #include "llvm/IR/BasicBlock.h"
  23. #include "llvm/IR/CFG.h"
  24. #include "llvm/IR/ConstantRange.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/IR/InstrTypes.h"
  28. #include "llvm/IR/Instructions.h"
  29. #include "llvm/IR/PassManager.h"
  30. #include "llvm/IR/Value.h"
  31. #include "llvm/InitializePasses.h"
  32. #include "llvm/Pass.h"
  33. #include "llvm/Support/Casting.h"
  34. #include "llvm/Support/Compiler.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/KnownBits.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Transforms/Utils.h"
  39. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  40. #include <algorithm>
  41. #include <cassert>
  42. #include <cstdint>
  43. #include <iterator>
  44. #include <limits>
  45. #include <vector>
  46. using namespace llvm;
  47. #define DEBUG_TYPE "lower-switch"
  48. namespace {
  49. struct IntRange {
  50. int64_t Low, High;
  51. };
  52. } // end anonymous namespace
  53. namespace {
  54. // Return true iff R is covered by Ranges.
  55. bool IsInRanges(const IntRange &R, const std::vector<IntRange> &Ranges) {
  56. // Note: Ranges must be sorted, non-overlapping and non-adjacent.
  57. // Find the first range whose High field is >= R.High,
  58. // then check if the Low field is <= R.Low. If so, we
  59. // have a Range that covers R.
  60. auto I = llvm::lower_bound(
  61. Ranges, R, [](IntRange A, IntRange B) { return A.High < B.High; });
  62. return I != Ranges.end() && I->Low <= R.Low;
  63. }
  64. struct CaseRange {
  65. ConstantInt *Low;
  66. ConstantInt *High;
  67. BasicBlock *BB;
  68. CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
  69. : Low(low), High(high), BB(bb) {}
  70. };
  71. using CaseVector = std::vector<CaseRange>;
  72. using CaseItr = std::vector<CaseRange>::iterator;
  73. /// The comparison function for sorting the switch case values in the vector.
  74. /// WARNING: Case ranges should be disjoint!
  75. struct CaseCmp {
  76. bool operator()(const CaseRange &C1, const CaseRange &C2) {
  77. const ConstantInt *CI1 = cast<const ConstantInt>(C1.Low);
  78. const ConstantInt *CI2 = cast<const ConstantInt>(C2.High);
  79. return CI1->getValue().slt(CI2->getValue());
  80. }
  81. };
  82. /// Used for debugging purposes.
  83. LLVM_ATTRIBUTE_USED
  84. raw_ostream &operator<<(raw_ostream &O, const CaseVector &C) {
  85. O << "[";
  86. for (CaseVector::const_iterator B = C.begin(), E = C.end(); B != E;) {
  87. O << "[" << B->Low->getValue() << ", " << B->High->getValue() << "]";
  88. if (++B != E)
  89. O << ", ";
  90. }
  91. return O << "]";
  92. }
  93. /// Update the first occurrence of the "switch statement" BB in the PHI
  94. /// node with the "new" BB. The other occurrences will:
  95. ///
  96. /// 1) Be updated by subsequent calls to this function. Switch statements may
  97. /// have more than one outcoming edge into the same BB if they all have the same
  98. /// value. When the switch statement is converted these incoming edges are now
  99. /// coming from multiple BBs.
  100. /// 2) Removed if subsequent incoming values now share the same case, i.e.,
  101. /// multiple outcome edges are condensed into one. This is necessary to keep the
  102. /// number of phi values equal to the number of branches to SuccBB.
  103. void FixPhis(
  104. BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
  105. const unsigned NumMergedCases = std::numeric_limits<unsigned>::max()) {
  106. for (BasicBlock::iterator I = SuccBB->begin(),
  107. IE = SuccBB->getFirstNonPHI()->getIterator();
  108. I != IE; ++I) {
  109. PHINode *PN = cast<PHINode>(I);
  110. // Only update the first occurrence.
  111. unsigned Idx = 0, E = PN->getNumIncomingValues();
  112. unsigned LocalNumMergedCases = NumMergedCases;
  113. for (; Idx != E; ++Idx) {
  114. if (PN->getIncomingBlock(Idx) == OrigBB) {
  115. PN->setIncomingBlock(Idx, NewBB);
  116. break;
  117. }
  118. }
  119. // Remove additional occurrences coming from condensed cases and keep the
  120. // number of incoming values equal to the number of branches to SuccBB.
  121. SmallVector<unsigned, 8> Indices;
  122. for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
  123. if (PN->getIncomingBlock(Idx) == OrigBB) {
  124. Indices.push_back(Idx);
  125. LocalNumMergedCases--;
  126. }
  127. // Remove incoming values in the reverse order to prevent invalidating
  128. // *successive* index.
  129. for (unsigned III : llvm::reverse(Indices))
  130. PN->removeIncomingValue(III);
  131. }
  132. }
  133. /// Create a new leaf block for the binary lookup tree. It checks if the
  134. /// switch's value == the case's value. If not, then it jumps to the default
  135. /// branch. At this point in the tree, the value can't be another valid case
  136. /// value, so the jump to the "default" branch is warranted.
  137. BasicBlock *NewLeafBlock(CaseRange &Leaf, Value *Val, ConstantInt *LowerBound,
  138. ConstantInt *UpperBound, BasicBlock *OrigBlock,
  139. BasicBlock *Default) {
  140. Function *F = OrigBlock->getParent();
  141. BasicBlock *NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
  142. F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
  143. // Emit comparison
  144. ICmpInst *Comp = nullptr;
  145. if (Leaf.Low == Leaf.High) {
  146. // Make the seteq instruction...
  147. Comp =
  148. new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val, Leaf.Low, "SwitchLeaf");
  149. } else {
  150. // Make range comparison
  151. if (Leaf.Low == LowerBound) {
  152. // Val >= Min && Val <= Hi --> Val <= Hi
  153. Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
  154. "SwitchLeaf");
  155. } else if (Leaf.High == UpperBound) {
  156. // Val <= Max && Val >= Lo --> Val >= Lo
  157. Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SGE, Val, Leaf.Low,
  158. "SwitchLeaf");
  159. } else if (Leaf.Low->isZero()) {
  160. // Val >= 0 && Val <= Hi --> Val <=u Hi
  161. Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
  162. "SwitchLeaf");
  163. } else {
  164. // Emit V-Lo <=u Hi-Lo
  165. Constant *NegLo = ConstantExpr::getNeg(Leaf.Low);
  166. Instruction *Add = BinaryOperator::CreateAdd(
  167. Val, NegLo, Val->getName() + ".off", NewLeaf);
  168. Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
  169. Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
  170. "SwitchLeaf");
  171. }
  172. }
  173. // Make the conditional branch...
  174. BasicBlock *Succ = Leaf.BB;
  175. BranchInst::Create(Succ, Default, Comp, NewLeaf);
  176. // If there were any PHI nodes in this successor, rewrite one entry
  177. // from OrigBlock to come from NewLeaf.
  178. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  179. PHINode *PN = cast<PHINode>(I);
  180. // Remove all but one incoming entries from the cluster
  181. uint64_t Range = Leaf.High->getSExtValue() - Leaf.Low->getSExtValue();
  182. for (uint64_t j = 0; j < Range; ++j) {
  183. PN->removeIncomingValue(OrigBlock);
  184. }
  185. int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
  186. assert(BlockIdx != -1 && "Switch didn't go to this successor??");
  187. PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
  188. }
  189. return NewLeaf;
  190. }
  191. /// Convert the switch statement into a binary lookup of the case values.
  192. /// The function recursively builds this tree. LowerBound and UpperBound are
  193. /// used to keep track of the bounds for Val that have already been checked by
  194. /// a block emitted by one of the previous calls to switchConvert in the call
  195. /// stack.
  196. BasicBlock *SwitchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
  197. ConstantInt *UpperBound, Value *Val,
  198. BasicBlock *Predecessor, BasicBlock *OrigBlock,
  199. BasicBlock *Default,
  200. const std::vector<IntRange> &UnreachableRanges) {
  201. assert(LowerBound && UpperBound && "Bounds must be initialized");
  202. unsigned Size = End - Begin;
  203. if (Size == 1) {
  204. // Check if the Case Range is perfectly squeezed in between
  205. // already checked Upper and Lower bounds. If it is then we can avoid
  206. // emitting the code that checks if the value actually falls in the range
  207. // because the bounds already tell us so.
  208. if (Begin->Low == LowerBound && Begin->High == UpperBound) {
  209. unsigned NumMergedCases = 0;
  210. NumMergedCases = UpperBound->getSExtValue() - LowerBound->getSExtValue();
  211. FixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
  212. return Begin->BB;
  213. }
  214. return NewLeafBlock(*Begin, Val, LowerBound, UpperBound, OrigBlock,
  215. Default);
  216. }
  217. unsigned Mid = Size / 2;
  218. std::vector<CaseRange> LHS(Begin, Begin + Mid);
  219. LLVM_DEBUG(dbgs() << "LHS: " << LHS << "\n");
  220. std::vector<CaseRange> RHS(Begin + Mid, End);
  221. LLVM_DEBUG(dbgs() << "RHS: " << RHS << "\n");
  222. CaseRange &Pivot = *(Begin + Mid);
  223. LLVM_DEBUG(dbgs() << "Pivot ==> [" << Pivot.Low->getValue() << ", "
  224. << Pivot.High->getValue() << "]\n");
  225. // NewLowerBound here should never be the integer minimal value.
  226. // This is because it is computed from a case range that is never
  227. // the smallest, so there is always a case range that has at least
  228. // a smaller value.
  229. ConstantInt *NewLowerBound = Pivot.Low;
  230. // Because NewLowerBound is never the smallest representable integer
  231. // it is safe here to subtract one.
  232. ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
  233. NewLowerBound->getValue() - 1);
  234. if (!UnreachableRanges.empty()) {
  235. // Check if the gap between LHS's highest and NewLowerBound is unreachable.
  236. int64_t GapLow = LHS.back().High->getSExtValue() + 1;
  237. int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
  238. IntRange Gap = { GapLow, GapHigh };
  239. if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
  240. NewUpperBound = LHS.back().High;
  241. }
  242. LLVM_DEBUG(dbgs() << "LHS Bounds ==> [" << LowerBound->getSExtValue() << ", "
  243. << NewUpperBound->getSExtValue() << "]\n"
  244. << "RHS Bounds ==> [" << NewLowerBound->getSExtValue()
  245. << ", " << UpperBound->getSExtValue() << "]\n");
  246. // Create a new node that checks if the value is < pivot. Go to the
  247. // left branch if it is and right branch if not.
  248. Function* F = OrigBlock->getParent();
  249. BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
  250. ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
  251. Val, Pivot.Low, "Pivot");
  252. BasicBlock *LBranch =
  253. SwitchConvert(LHS.begin(), LHS.end(), LowerBound, NewUpperBound, Val,
  254. NewNode, OrigBlock, Default, UnreachableRanges);
  255. BasicBlock *RBranch =
  256. SwitchConvert(RHS.begin(), RHS.end(), NewLowerBound, UpperBound, Val,
  257. NewNode, OrigBlock, Default, UnreachableRanges);
  258. F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
  259. NewNode->getInstList().push_back(Comp);
  260. BranchInst::Create(LBranch, RBranch, Comp, NewNode);
  261. return NewNode;
  262. }
  263. /// Transform simple list of \p SI's cases into list of CaseRange's \p Cases.
  264. /// \post \p Cases wouldn't contain references to \p SI's default BB.
  265. /// \returns Number of \p SI's cases that do not reference \p SI's default BB.
  266. unsigned Clusterify(CaseVector &Cases, SwitchInst *SI) {
  267. unsigned NumSimpleCases = 0;
  268. // Start with "simple" cases
  269. for (auto Case : SI->cases()) {
  270. if (Case.getCaseSuccessor() == SI->getDefaultDest())
  271. continue;
  272. Cases.push_back(CaseRange(Case.getCaseValue(), Case.getCaseValue(),
  273. Case.getCaseSuccessor()));
  274. ++NumSimpleCases;
  275. }
  276. llvm::sort(Cases, CaseCmp());
  277. // Merge case into clusters
  278. if (Cases.size() >= 2) {
  279. CaseItr I = Cases.begin();
  280. for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
  281. int64_t nextValue = J->Low->getSExtValue();
  282. int64_t currentValue = I->High->getSExtValue();
  283. BasicBlock* nextBB = J->BB;
  284. BasicBlock* currentBB = I->BB;
  285. // If the two neighboring cases go to the same destination, merge them
  286. // into a single case.
  287. assert(nextValue > currentValue && "Cases should be strictly ascending");
  288. if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
  289. I->High = J->High;
  290. // FIXME: Combine branch weights.
  291. } else if (++I != J) {
  292. *I = *J;
  293. }
  294. }
  295. Cases.erase(std::next(I), Cases.end());
  296. }
  297. return NumSimpleCases;
  298. }
  299. /// Replace the specified switch instruction with a sequence of chained if-then
  300. /// insts in a balanced binary search.
  301. void ProcessSwitchInst(SwitchInst *SI,
  302. SmallPtrSetImpl<BasicBlock *> &DeleteList,
  303. AssumptionCache *AC, LazyValueInfo *LVI) {
  304. BasicBlock *OrigBlock = SI->getParent();
  305. Function *F = OrigBlock->getParent();
  306. Value *Val = SI->getCondition(); // The value we are switching on...
  307. BasicBlock* Default = SI->getDefaultDest();
  308. // Don't handle unreachable blocks. If there are successors with phis, this
  309. // would leave them behind with missing predecessors.
  310. if ((OrigBlock != &F->getEntryBlock() && pred_empty(OrigBlock)) ||
  311. OrigBlock->getSinglePredecessor() == OrigBlock) {
  312. DeleteList.insert(OrigBlock);
  313. return;
  314. }
  315. // Prepare cases vector.
  316. CaseVector Cases;
  317. const unsigned NumSimpleCases = Clusterify(Cases, SI);
  318. LLVM_DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
  319. << ". Total non-default cases: " << NumSimpleCases
  320. << "\nCase clusters: " << Cases << "\n");
  321. // If there is only the default destination, just branch.
  322. if (Cases.empty()) {
  323. BranchInst::Create(Default, OrigBlock);
  324. // Remove all the references from Default's PHIs to OrigBlock, but one.
  325. FixPhis(Default, OrigBlock, OrigBlock);
  326. SI->eraseFromParent();
  327. return;
  328. }
  329. ConstantInt *LowerBound = nullptr;
  330. ConstantInt *UpperBound = nullptr;
  331. bool DefaultIsUnreachableFromSwitch = false;
  332. if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
  333. // Make the bounds tightly fitted around the case value range, because we
  334. // know that the value passed to the switch must be exactly one of the case
  335. // values.
  336. LowerBound = Cases.front().Low;
  337. UpperBound = Cases.back().High;
  338. DefaultIsUnreachableFromSwitch = true;
  339. } else {
  340. // Constraining the range of the value being switched over helps eliminating
  341. // unreachable BBs and minimizing the number of `add` instructions
  342. // newLeafBlock ends up emitting. Running CorrelatedValuePropagation after
  343. // LowerSwitch isn't as good, and also much more expensive in terms of
  344. // compile time for the following reasons:
  345. // 1. it processes many kinds of instructions, not just switches;
  346. // 2. even if limited to icmp instructions only, it will have to process
  347. // roughly C icmp's per switch, where C is the number of cases in the
  348. // switch, while LowerSwitch only needs to call LVI once per switch.
  349. const DataLayout &DL = F->getParent()->getDataLayout();
  350. KnownBits Known = computeKnownBits(Val, DL, /*Depth=*/0, AC, SI);
  351. // TODO Shouldn't this create a signed range?
  352. ConstantRange KnownBitsRange =
  353. ConstantRange::fromKnownBits(Known, /*IsSigned=*/false);
  354. const ConstantRange LVIRange = LVI->getConstantRange(Val, SI);
  355. ConstantRange ValRange = KnownBitsRange.intersectWith(LVIRange);
  356. // We delegate removal of unreachable non-default cases to other passes. In
  357. // the unlikely event that some of them survived, we just conservatively
  358. // maintain the invariant that all the cases lie between the bounds. This
  359. // may, however, still render the default case effectively unreachable.
  360. APInt Low = Cases.front().Low->getValue();
  361. APInt High = Cases.back().High->getValue();
  362. APInt Min = APIntOps::smin(ValRange.getSignedMin(), Low);
  363. APInt Max = APIntOps::smax(ValRange.getSignedMax(), High);
  364. LowerBound = ConstantInt::get(SI->getContext(), Min);
  365. UpperBound = ConstantInt::get(SI->getContext(), Max);
  366. DefaultIsUnreachableFromSwitch = (Min + (NumSimpleCases - 1) == Max);
  367. }
  368. std::vector<IntRange> UnreachableRanges;
  369. if (DefaultIsUnreachableFromSwitch) {
  370. DenseMap<BasicBlock *, unsigned> Popularity;
  371. unsigned MaxPop = 0;
  372. BasicBlock *PopSucc = nullptr;
  373. IntRange R = {std::numeric_limits<int64_t>::min(),
  374. std::numeric_limits<int64_t>::max()};
  375. UnreachableRanges.push_back(R);
  376. for (const auto &I : Cases) {
  377. int64_t Low = I.Low->getSExtValue();
  378. int64_t High = I.High->getSExtValue();
  379. IntRange &LastRange = UnreachableRanges.back();
  380. if (LastRange.Low == Low) {
  381. // There is nothing left of the previous range.
  382. UnreachableRanges.pop_back();
  383. } else {
  384. // Terminate the previous range.
  385. assert(Low > LastRange.Low);
  386. LastRange.High = Low - 1;
  387. }
  388. if (High != std::numeric_limits<int64_t>::max()) {
  389. IntRange R = { High + 1, std::numeric_limits<int64_t>::max() };
  390. UnreachableRanges.push_back(R);
  391. }
  392. // Count popularity.
  393. int64_t N = High - Low + 1;
  394. unsigned &Pop = Popularity[I.BB];
  395. if ((Pop += N) > MaxPop) {
  396. MaxPop = Pop;
  397. PopSucc = I.BB;
  398. }
  399. }
  400. #ifndef NDEBUG
  401. /* UnreachableRanges should be sorted and the ranges non-adjacent. */
  402. for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
  403. I != E; ++I) {
  404. assert(I->Low <= I->High);
  405. auto Next = I + 1;
  406. if (Next != E) {
  407. assert(Next->Low > I->High);
  408. }
  409. }
  410. #endif
  411. // As the default block in the switch is unreachable, update the PHI nodes
  412. // (remove all of the references to the default block) to reflect this.
  413. const unsigned NumDefaultEdges = SI->getNumCases() + 1 - NumSimpleCases;
  414. for (unsigned I = 0; I < NumDefaultEdges; ++I)
  415. Default->removePredecessor(OrigBlock);
  416. // Use the most popular block as the new default, reducing the number of
  417. // cases.
  418. assert(MaxPop > 0 && PopSucc);
  419. Default = PopSucc;
  420. llvm::erase_if(Cases,
  421. [PopSucc](const CaseRange &R) { return R.BB == PopSucc; });
  422. // If there are no cases left, just branch.
  423. if (Cases.empty()) {
  424. BranchInst::Create(Default, OrigBlock);
  425. SI->eraseFromParent();
  426. // As all the cases have been replaced with a single branch, only keep
  427. // one entry in the PHI nodes.
  428. for (unsigned I = 0 ; I < (MaxPop - 1) ; ++I)
  429. PopSucc->removePredecessor(OrigBlock);
  430. return;
  431. }
  432. // If the condition was a PHI node with the switch block as a predecessor
  433. // removing predecessors may have caused the condition to be erased.
  434. // Getting the condition value again here protects against that.
  435. Val = SI->getCondition();
  436. }
  437. // Create a new, empty default block so that the new hierarchy of
  438. // if-then statements go to this and the PHI nodes are happy.
  439. BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
  440. F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
  441. BranchInst::Create(Default, NewDefault);
  442. BasicBlock *SwitchBlock =
  443. SwitchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
  444. OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
  445. // If there are entries in any PHI nodes for the default edge, make sure
  446. // to update them as well.
  447. FixPhis(Default, OrigBlock, NewDefault);
  448. // Branch to our shiny new if-then stuff...
  449. BranchInst::Create(SwitchBlock, OrigBlock);
  450. // We are now done with the switch instruction, delete it.
  451. BasicBlock *OldDefault = SI->getDefaultDest();
  452. OrigBlock->getInstList().erase(SI);
  453. // If the Default block has no more predecessors just add it to DeleteList.
  454. if (pred_empty(OldDefault))
  455. DeleteList.insert(OldDefault);
  456. }
  457. bool LowerSwitch(Function &F, LazyValueInfo *LVI, AssumptionCache *AC) {
  458. bool Changed = false;
  459. SmallPtrSet<BasicBlock *, 8> DeleteList;
  460. // We use make_early_inc_range here so that we don't traverse new blocks.
  461. for (BasicBlock &Cur : llvm::make_early_inc_range(F)) {
  462. // If the block is a dead Default block that will be deleted later, don't
  463. // waste time processing it.
  464. if (DeleteList.count(&Cur))
  465. continue;
  466. if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur.getTerminator())) {
  467. Changed = true;
  468. ProcessSwitchInst(SI, DeleteList, AC, LVI);
  469. }
  470. }
  471. for (BasicBlock *BB : DeleteList) {
  472. LVI->eraseBlock(BB);
  473. DeleteDeadBlock(BB);
  474. }
  475. return Changed;
  476. }
  477. /// Replace all SwitchInst instructions with chained branch instructions.
  478. class LowerSwitchLegacyPass : public FunctionPass {
  479. public:
  480. // Pass identification, replacement for typeid
  481. static char ID;
  482. LowerSwitchLegacyPass() : FunctionPass(ID) {
  483. initializeLowerSwitchLegacyPassPass(*PassRegistry::getPassRegistry());
  484. }
  485. bool runOnFunction(Function &F) override;
  486. void getAnalysisUsage(AnalysisUsage &AU) const override {
  487. AU.addRequired<LazyValueInfoWrapperPass>();
  488. }
  489. };
  490. } // end anonymous namespace
  491. char LowerSwitchLegacyPass::ID = 0;
  492. // Publicly exposed interface to pass...
  493. char &llvm::LowerSwitchID = LowerSwitchLegacyPass::ID;
  494. INITIALIZE_PASS_BEGIN(LowerSwitchLegacyPass, "lowerswitch",
  495. "Lower SwitchInst's to branches", false, false)
  496. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  497. INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
  498. INITIALIZE_PASS_END(LowerSwitchLegacyPass, "lowerswitch",
  499. "Lower SwitchInst's to branches", false, false)
  500. // createLowerSwitchPass - Interface to this file...
  501. FunctionPass *llvm::createLowerSwitchPass() {
  502. return new LowerSwitchLegacyPass();
  503. }
  504. bool LowerSwitchLegacyPass::runOnFunction(Function &F) {
  505. LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
  506. auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>();
  507. AssumptionCache *AC = ACT ? &ACT->getAssumptionCache(F) : nullptr;
  508. return LowerSwitch(F, LVI, AC);
  509. }
  510. PreservedAnalyses LowerSwitchPass::run(Function &F,
  511. FunctionAnalysisManager &AM) {
  512. LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F);
  513. AssumptionCache *AC = AM.getCachedResult<AssumptionAnalysis>(F);
  514. return LowerSwitch(F, LVI, AC) ? PreservedAnalyses::none()
  515. : PreservedAnalyses::all();
  516. }