LowerSwitch.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. APInt 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.slt(B.High); });
  62. return I != Ranges.end() && I->Low.sle(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(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
  104. const APInt &NumMergedCases) {
  105. for (auto &I : SuccBB->phis()) {
  106. PHINode *PN = cast<PHINode>(&I);
  107. // Only update the first occurrence if NewBB exists.
  108. unsigned Idx = 0, E = PN->getNumIncomingValues();
  109. APInt LocalNumMergedCases = NumMergedCases;
  110. for (; Idx != E && NewBB; ++Idx) {
  111. if (PN->getIncomingBlock(Idx) == OrigBB) {
  112. PN->setIncomingBlock(Idx, NewBB);
  113. break;
  114. }
  115. }
  116. // Skip the updated incoming block so that it will not be removed.
  117. if (NewBB)
  118. ++Idx;
  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 (; LocalNumMergedCases.ugt(0) && Idx < E; ++Idx)
  123. if (PN->getIncomingBlock(Idx) == OrigBB) {
  124. Indices.push_back(Idx);
  125. LocalNumMergedCases -= 1;
  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->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. // Update the PHI incoming value/block for the default.
  177. for (auto &I : Default->phis()) {
  178. PHINode *PN = cast<PHINode>(&I);
  179. auto *V = PN->getIncomingValueForBlock(OrigBlock);
  180. PN->addIncoming(V, NewLeaf);
  181. }
  182. // If there were any PHI nodes in this successor, rewrite one entry
  183. // from OrigBlock to come from NewLeaf.
  184. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  185. PHINode *PN = cast<PHINode>(I);
  186. // Remove all but one incoming entries from the cluster
  187. APInt Range = Leaf.High->getValue() - Leaf.Low->getValue();
  188. for (APInt j(Range.getBitWidth(), 0, true); j.slt(Range); ++j) {
  189. PN->removeIncomingValue(OrigBlock);
  190. }
  191. int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
  192. assert(BlockIdx != -1 && "Switch didn't go to this successor??");
  193. PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
  194. }
  195. return NewLeaf;
  196. }
  197. /// Convert the switch statement into a binary lookup of the case values.
  198. /// The function recursively builds this tree. LowerBound and UpperBound are
  199. /// used to keep track of the bounds for Val that have already been checked by
  200. /// a block emitted by one of the previous calls to switchConvert in the call
  201. /// stack.
  202. BasicBlock *SwitchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
  203. ConstantInt *UpperBound, Value *Val,
  204. BasicBlock *Predecessor, BasicBlock *OrigBlock,
  205. BasicBlock *Default,
  206. const std::vector<IntRange> &UnreachableRanges) {
  207. assert(LowerBound && UpperBound && "Bounds must be initialized");
  208. unsigned Size = End - Begin;
  209. if (Size == 1) {
  210. // Check if the Case Range is perfectly squeezed in between
  211. // already checked Upper and Lower bounds. If it is then we can avoid
  212. // emitting the code that checks if the value actually falls in the range
  213. // because the bounds already tell us so.
  214. if (Begin->Low == LowerBound && Begin->High == UpperBound) {
  215. APInt NumMergedCases = UpperBound->getValue() - LowerBound->getValue();
  216. FixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
  217. return Begin->BB;
  218. }
  219. return NewLeafBlock(*Begin, Val, LowerBound, UpperBound, OrigBlock,
  220. Default);
  221. }
  222. unsigned Mid = Size / 2;
  223. std::vector<CaseRange> LHS(Begin, Begin + Mid);
  224. LLVM_DEBUG(dbgs() << "LHS: " << LHS << "\n");
  225. std::vector<CaseRange> RHS(Begin + Mid, End);
  226. LLVM_DEBUG(dbgs() << "RHS: " << RHS << "\n");
  227. CaseRange &Pivot = *(Begin + Mid);
  228. LLVM_DEBUG(dbgs() << "Pivot ==> [" << Pivot.Low->getValue() << ", "
  229. << Pivot.High->getValue() << "]\n");
  230. // NewLowerBound here should never be the integer minimal value.
  231. // This is because it is computed from a case range that is never
  232. // the smallest, so there is always a case range that has at least
  233. // a smaller value.
  234. ConstantInt *NewLowerBound = Pivot.Low;
  235. // Because NewLowerBound is never the smallest representable integer
  236. // it is safe here to subtract one.
  237. ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
  238. NewLowerBound->getValue() - 1);
  239. if (!UnreachableRanges.empty()) {
  240. // Check if the gap between LHS's highest and NewLowerBound is unreachable.
  241. APInt GapLow = LHS.back().High->getValue() + 1;
  242. APInt GapHigh = NewLowerBound->getValue() - 1;
  243. IntRange Gap = {GapLow, GapHigh};
  244. if (GapHigh.sge(GapLow) && IsInRanges(Gap, UnreachableRanges))
  245. NewUpperBound = LHS.back().High;
  246. }
  247. LLVM_DEBUG(dbgs() << "LHS Bounds ==> [" << LowerBound->getValue() << ", "
  248. << NewUpperBound->getValue() << "]\n"
  249. << "RHS Bounds ==> [" << NewLowerBound->getValue() << ", "
  250. << UpperBound->getValue() << "]\n");
  251. // Create a new node that checks if the value is < pivot. Go to the
  252. // left branch if it is and right branch if not.
  253. Function *F = OrigBlock->getParent();
  254. BasicBlock *NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
  255. ICmpInst *Comp = new ICmpInst(ICmpInst::ICMP_SLT, Val, Pivot.Low, "Pivot");
  256. BasicBlock *LBranch =
  257. SwitchConvert(LHS.begin(), LHS.end(), LowerBound, NewUpperBound, Val,
  258. NewNode, OrigBlock, Default, UnreachableRanges);
  259. BasicBlock *RBranch =
  260. SwitchConvert(RHS.begin(), RHS.end(), NewLowerBound, UpperBound, Val,
  261. NewNode, OrigBlock, Default, UnreachableRanges);
  262. F->insert(++OrigBlock->getIterator(), NewNode);
  263. Comp->insertInto(NewNode, NewNode->end());
  264. BranchInst::Create(LBranch, RBranch, Comp, NewNode);
  265. return NewNode;
  266. }
  267. /// Transform simple list of \p SI's cases into list of CaseRange's \p Cases.
  268. /// \post \p Cases wouldn't contain references to \p SI's default BB.
  269. /// \returns Number of \p SI's cases that do not reference \p SI's default BB.
  270. unsigned Clusterify(CaseVector &Cases, SwitchInst *SI) {
  271. unsigned NumSimpleCases = 0;
  272. // Start with "simple" cases
  273. for (auto Case : SI->cases()) {
  274. if (Case.getCaseSuccessor() == SI->getDefaultDest())
  275. continue;
  276. Cases.push_back(CaseRange(Case.getCaseValue(), Case.getCaseValue(),
  277. Case.getCaseSuccessor()));
  278. ++NumSimpleCases;
  279. }
  280. llvm::sort(Cases, CaseCmp());
  281. // Merge case into clusters
  282. if (Cases.size() >= 2) {
  283. CaseItr I = Cases.begin();
  284. for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
  285. const APInt &nextValue = J->Low->getValue();
  286. const APInt &currentValue = I->High->getValue();
  287. BasicBlock *nextBB = J->BB;
  288. BasicBlock *currentBB = I->BB;
  289. // If the two neighboring cases go to the same destination, merge them
  290. // into a single case.
  291. assert(nextValue.sgt(currentValue) &&
  292. "Cases should be strictly ascending");
  293. if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
  294. I->High = J->High;
  295. // FIXME: Combine branch weights.
  296. } else if (++I != J) {
  297. *I = *J;
  298. }
  299. }
  300. Cases.erase(std::next(I), Cases.end());
  301. }
  302. return NumSimpleCases;
  303. }
  304. /// Replace the specified switch instruction with a sequence of chained if-then
  305. /// insts in a balanced binary search.
  306. void ProcessSwitchInst(SwitchInst *SI,
  307. SmallPtrSetImpl<BasicBlock *> &DeleteList,
  308. AssumptionCache *AC, LazyValueInfo *LVI) {
  309. BasicBlock *OrigBlock = SI->getParent();
  310. Function *F = OrigBlock->getParent();
  311. Value *Val = SI->getCondition(); // The value we are switching on...
  312. BasicBlock *Default = SI->getDefaultDest();
  313. // Don't handle unreachable blocks. If there are successors with phis, this
  314. // would leave them behind with missing predecessors.
  315. if ((OrigBlock != &F->getEntryBlock() && pred_empty(OrigBlock)) ||
  316. OrigBlock->getSinglePredecessor() == OrigBlock) {
  317. DeleteList.insert(OrigBlock);
  318. return;
  319. }
  320. // Prepare cases vector.
  321. CaseVector Cases;
  322. const unsigned NumSimpleCases = Clusterify(Cases, SI);
  323. IntegerType *IT = cast<IntegerType>(SI->getCondition()->getType());
  324. const unsigned BitWidth = IT->getBitWidth();
  325. // Explictly use higher precision to prevent unsigned overflow where
  326. // `UnsignedMax - 0 + 1 == 0`
  327. APInt UnsignedZero(BitWidth + 1, 0);
  328. APInt UnsignedMax = APInt::getMaxValue(BitWidth);
  329. LLVM_DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
  330. << ". Total non-default cases: " << NumSimpleCases
  331. << "\nCase clusters: " << Cases << "\n");
  332. // If there is only the default destination, just branch.
  333. if (Cases.empty()) {
  334. BranchInst::Create(Default, OrigBlock);
  335. // Remove all the references from Default's PHIs to OrigBlock, but one.
  336. FixPhis(Default, OrigBlock, OrigBlock, UnsignedMax);
  337. SI->eraseFromParent();
  338. return;
  339. }
  340. ConstantInt *LowerBound = nullptr;
  341. ConstantInt *UpperBound = nullptr;
  342. bool DefaultIsUnreachableFromSwitch = false;
  343. if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
  344. // Make the bounds tightly fitted around the case value range, because we
  345. // know that the value passed to the switch must be exactly one of the case
  346. // values.
  347. LowerBound = Cases.front().Low;
  348. UpperBound = Cases.back().High;
  349. DefaultIsUnreachableFromSwitch = true;
  350. } else {
  351. // Constraining the range of the value being switched over helps eliminating
  352. // unreachable BBs and minimizing the number of `add` instructions
  353. // newLeafBlock ends up emitting. Running CorrelatedValuePropagation after
  354. // LowerSwitch isn't as good, and also much more expensive in terms of
  355. // compile time for the following reasons:
  356. // 1. it processes many kinds of instructions, not just switches;
  357. // 2. even if limited to icmp instructions only, it will have to process
  358. // roughly C icmp's per switch, where C is the number of cases in the
  359. // switch, while LowerSwitch only needs to call LVI once per switch.
  360. const DataLayout &DL = F->getParent()->getDataLayout();
  361. KnownBits Known = computeKnownBits(Val, DL, /*Depth=*/0, AC, SI);
  362. // TODO Shouldn't this create a signed range?
  363. ConstantRange KnownBitsRange =
  364. ConstantRange::fromKnownBits(Known, /*IsSigned=*/false);
  365. const ConstantRange LVIRange = LVI->getConstantRange(Val, SI);
  366. ConstantRange ValRange = KnownBitsRange.intersectWith(LVIRange);
  367. // We delegate removal of unreachable non-default cases to other passes. In
  368. // the unlikely event that some of them survived, we just conservatively
  369. // maintain the invariant that all the cases lie between the bounds. This
  370. // may, however, still render the default case effectively unreachable.
  371. const APInt &Low = Cases.front().Low->getValue();
  372. const APInt &High = Cases.back().High->getValue();
  373. APInt Min = APIntOps::smin(ValRange.getSignedMin(), Low);
  374. APInt Max = APIntOps::smax(ValRange.getSignedMax(), High);
  375. LowerBound = ConstantInt::get(SI->getContext(), Min);
  376. UpperBound = ConstantInt::get(SI->getContext(), Max);
  377. DefaultIsUnreachableFromSwitch = (Min + (NumSimpleCases - 1) == Max);
  378. }
  379. std::vector<IntRange> UnreachableRanges;
  380. if (DefaultIsUnreachableFromSwitch) {
  381. DenseMap<BasicBlock *, APInt> Popularity;
  382. APInt MaxPop(UnsignedZero);
  383. BasicBlock *PopSucc = nullptr;
  384. APInt SignedMax = APInt::getSignedMaxValue(BitWidth);
  385. APInt SignedMin = APInt::getSignedMinValue(BitWidth);
  386. IntRange R = {SignedMin, SignedMax};
  387. UnreachableRanges.push_back(R);
  388. for (const auto &I : Cases) {
  389. const APInt &Low = I.Low->getValue();
  390. const APInt &High = I.High->getValue();
  391. IntRange &LastRange = UnreachableRanges.back();
  392. if (LastRange.Low.eq(Low)) {
  393. // There is nothing left of the previous range.
  394. UnreachableRanges.pop_back();
  395. } else {
  396. // Terminate the previous range.
  397. assert(Low.sgt(LastRange.Low));
  398. LastRange.High = Low - 1;
  399. }
  400. if (High.ne(SignedMax)) {
  401. IntRange R = {High + 1, SignedMax};
  402. UnreachableRanges.push_back(R);
  403. }
  404. // Count popularity.
  405. assert(High.sge(Low) && "Popularity shouldn't be negative.");
  406. APInt N = High.sext(BitWidth + 1) - Low.sext(BitWidth + 1) + 1;
  407. // Explict insert to make sure the bitwidth of APInts match
  408. APInt &Pop = Popularity.insert({I.BB, APInt(UnsignedZero)}).first->second;
  409. if ((Pop += N).ugt(MaxPop)) {
  410. MaxPop = Pop;
  411. PopSucc = I.BB;
  412. }
  413. }
  414. #ifndef NDEBUG
  415. /* UnreachableRanges should be sorted and the ranges non-adjacent. */
  416. for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
  417. I != E; ++I) {
  418. assert(I->Low.sle(I->High));
  419. auto Next = I + 1;
  420. if (Next != E) {
  421. assert(Next->Low.sgt(I->High));
  422. }
  423. }
  424. #endif
  425. // As the default block in the switch is unreachable, update the PHI nodes
  426. // (remove all of the references to the default block) to reflect this.
  427. const unsigned NumDefaultEdges = SI->getNumCases() + 1 - NumSimpleCases;
  428. for (unsigned I = 0; I < NumDefaultEdges; ++I)
  429. Default->removePredecessor(OrigBlock);
  430. // Use the most popular block as the new default, reducing the number of
  431. // cases.
  432. Default = PopSucc;
  433. llvm::erase_if(Cases,
  434. [PopSucc](const CaseRange &R) { return R.BB == PopSucc; });
  435. // If there are no cases left, just branch.
  436. if (Cases.empty()) {
  437. BranchInst::Create(Default, OrigBlock);
  438. SI->eraseFromParent();
  439. // As all the cases have been replaced with a single branch, only keep
  440. // one entry in the PHI nodes.
  441. if (!MaxPop.isZero())
  442. for (APInt I(UnsignedZero); I.ult(MaxPop - 1); ++I)
  443. PopSucc->removePredecessor(OrigBlock);
  444. return;
  445. }
  446. // If the condition was a PHI node with the switch block as a predecessor
  447. // removing predecessors may have caused the condition to be erased.
  448. // Getting the condition value again here protects against that.
  449. Val = SI->getCondition();
  450. }
  451. BasicBlock *SwitchBlock =
  452. SwitchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
  453. OrigBlock, OrigBlock, Default, UnreachableRanges);
  454. // We have added incoming values for newly-created predecessors in
  455. // NewLeafBlock(). The only meaningful work we offload to FixPhis() is to
  456. // remove the incoming values from OrigBlock. There might be a special case
  457. // that SwitchBlock is the same as Default, under which the PHIs in Default
  458. // are fixed inside SwitchConvert().
  459. if (SwitchBlock != Default)
  460. FixPhis(Default, OrigBlock, nullptr, UnsignedMax);
  461. // Branch to our shiny new if-then stuff...
  462. BranchInst::Create(SwitchBlock, OrigBlock);
  463. // We are now done with the switch instruction, delete it.
  464. BasicBlock *OldDefault = SI->getDefaultDest();
  465. SI->eraseFromParent();
  466. // If the Default block has no more predecessors just add it to DeleteList.
  467. if (pred_empty(OldDefault))
  468. DeleteList.insert(OldDefault);
  469. }
  470. bool LowerSwitch(Function &F, LazyValueInfo *LVI, AssumptionCache *AC) {
  471. bool Changed = false;
  472. SmallPtrSet<BasicBlock *, 8> DeleteList;
  473. // We use make_early_inc_range here so that we don't traverse new blocks.
  474. for (BasicBlock &Cur : llvm::make_early_inc_range(F)) {
  475. // If the block is a dead Default block that will be deleted later, don't
  476. // waste time processing it.
  477. if (DeleteList.count(&Cur))
  478. continue;
  479. if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur.getTerminator())) {
  480. Changed = true;
  481. ProcessSwitchInst(SI, DeleteList, AC, LVI);
  482. }
  483. }
  484. for (BasicBlock *BB : DeleteList) {
  485. LVI->eraseBlock(BB);
  486. DeleteDeadBlock(BB);
  487. }
  488. return Changed;
  489. }
  490. /// Replace all SwitchInst instructions with chained branch instructions.
  491. class LowerSwitchLegacyPass : public FunctionPass {
  492. public:
  493. // Pass identification, replacement for typeid
  494. static char ID;
  495. LowerSwitchLegacyPass() : FunctionPass(ID) {
  496. initializeLowerSwitchLegacyPassPass(*PassRegistry::getPassRegistry());
  497. }
  498. bool runOnFunction(Function &F) override;
  499. void getAnalysisUsage(AnalysisUsage &AU) const override {
  500. AU.addRequired<LazyValueInfoWrapperPass>();
  501. }
  502. };
  503. } // end anonymous namespace
  504. char LowerSwitchLegacyPass::ID = 0;
  505. // Publicly exposed interface to pass...
  506. char &llvm::LowerSwitchID = LowerSwitchLegacyPass::ID;
  507. INITIALIZE_PASS_BEGIN(LowerSwitchLegacyPass, "lowerswitch",
  508. "Lower SwitchInst's to branches", false, false)
  509. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  510. INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
  511. INITIALIZE_PASS_END(LowerSwitchLegacyPass, "lowerswitch",
  512. "Lower SwitchInst's to branches", false, false)
  513. // createLowerSwitchPass - Interface to this file...
  514. FunctionPass *llvm::createLowerSwitchPass() {
  515. return new LowerSwitchLegacyPass();
  516. }
  517. bool LowerSwitchLegacyPass::runOnFunction(Function &F) {
  518. LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
  519. auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>();
  520. AssumptionCache *AC = ACT ? &ACT->getAssumptionCache(F) : nullptr;
  521. return LowerSwitch(F, LVI, AC);
  522. }
  523. PreservedAnalyses LowerSwitchPass::run(Function &F,
  524. FunctionAnalysisManager &AM) {
  525. LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F);
  526. AssumptionCache *AC = AM.getCachedResult<AssumptionAnalysis>(F);
  527. return LowerSwitch(F, LVI, AC) ? PreservedAnalyses::none()
  528. : PreservedAnalyses::all();
  529. }