LowerSwitch.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
  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. // The LowerSwitch transformation rewrites switch instructions with a sequence
  11. // of branches, which allows targets to get away with not implementing the
  12. // switch instruction until it is convenient.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/Scalar.h"
  16. #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
  17. #include "llvm/Constants.h"
  18. #include "llvm/Function.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/LLVMContext.h"
  21. #include "llvm/Pass.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/Support/Compiler.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <algorithm>
  27. using namespace llvm;
  28. namespace {
  29. /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
  30. /// instructions.
  31. class LowerSwitch : public FunctionPass {
  32. public:
  33. static char ID; // Pass identification, replacement for typeid
  34. LowerSwitch() : FunctionPass(ID) {}
  35. virtual bool runOnFunction(Function &F);
  36. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  37. // This is a cluster of orthogonal Transforms
  38. AU.addPreserved<UnifyFunctionExitNodes>();
  39. AU.addPreserved("mem2reg");
  40. AU.addPreservedID(LowerInvokePassID);
  41. }
  42. struct CaseRange {
  43. Constant* Low;
  44. Constant* High;
  45. BasicBlock* BB;
  46. CaseRange(Constant *low = 0, Constant *high = 0, BasicBlock *bb = 0) :
  47. Low(low), High(high), BB(bb) { }
  48. };
  49. typedef std::vector<CaseRange> CaseVector;
  50. typedef std::vector<CaseRange>::iterator CaseItr;
  51. private:
  52. void processSwitchInst(SwitchInst *SI);
  53. BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
  54. BasicBlock* OrigBlock, BasicBlock* Default);
  55. BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
  56. BasicBlock* OrigBlock, BasicBlock* Default);
  57. unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
  58. };
  59. /// The comparison function for sorting the switch case values in the vector.
  60. /// WARNING: Case ranges should be disjoint!
  61. struct CaseCmp {
  62. bool operator () (const LowerSwitch::CaseRange& C1,
  63. const LowerSwitch::CaseRange& C2) {
  64. const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
  65. const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
  66. return CI1->getValue().slt(CI2->getValue());
  67. }
  68. };
  69. }
  70. char LowerSwitch::ID = 0;
  71. INITIALIZE_PASS(LowerSwitch, "lowerswitch",
  72. "Lower SwitchInst's to branches", false, false);
  73. // Publically exposed interface to pass...
  74. char &llvm::LowerSwitchID = LowerSwitch::ID;
  75. // createLowerSwitchPass - Interface to this file...
  76. FunctionPass *llvm::createLowerSwitchPass() {
  77. return new LowerSwitch();
  78. }
  79. bool LowerSwitch::runOnFunction(Function &F) {
  80. bool Changed = false;
  81. for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
  82. BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
  83. if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
  84. Changed = true;
  85. processSwitchInst(SI);
  86. }
  87. }
  88. return Changed;
  89. }
  90. // operator<< - Used for debugging purposes.
  91. //
  92. static raw_ostream& operator<<(raw_ostream &O,
  93. const LowerSwitch::CaseVector &C) ATTRIBUTE_USED;
  94. static raw_ostream& operator<<(raw_ostream &O,
  95. const LowerSwitch::CaseVector &C) {
  96. O << "[";
  97. for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
  98. E = C.end(); B != E; ) {
  99. O << *B->Low << " -" << *B->High;
  100. if (++B != E) O << ", ";
  101. }
  102. return O << "]";
  103. }
  104. // switchConvert - Convert the switch statement into a binary lookup of
  105. // the case values. The function recursively builds this tree.
  106. //
  107. BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
  108. Value* Val, BasicBlock* OrigBlock,
  109. BasicBlock* Default)
  110. {
  111. unsigned Size = End - Begin;
  112. if (Size == 1)
  113. return newLeafBlock(*Begin, Val, OrigBlock, Default);
  114. unsigned Mid = Size / 2;
  115. std::vector<CaseRange> LHS(Begin, Begin + Mid);
  116. DEBUG(dbgs() << "LHS: " << LHS << "\n");
  117. std::vector<CaseRange> RHS(Begin + Mid, End);
  118. DEBUG(dbgs() << "RHS: " << RHS << "\n");
  119. CaseRange& Pivot = *(Begin + Mid);
  120. DEBUG(dbgs() << "Pivot ==> "
  121. << cast<ConstantInt>(Pivot.Low)->getValue() << " -"
  122. << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
  123. BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
  124. OrigBlock, Default);
  125. BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
  126. OrigBlock, Default);
  127. // Create a new node that checks if the value is < pivot. Go to the
  128. // left branch if it is and right branch if not.
  129. Function* F = OrigBlock->getParent();
  130. BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
  131. Function::iterator FI = OrigBlock;
  132. F->getBasicBlockList().insert(++FI, NewNode);
  133. ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
  134. Val, Pivot.Low, "Pivot");
  135. NewNode->getInstList().push_back(Comp);
  136. BranchInst::Create(LBranch, RBranch, Comp, NewNode);
  137. return NewNode;
  138. }
  139. // newLeafBlock - Create a new leaf block for the binary lookup tree. It
  140. // checks if the switch's value == the case's value. If not, then it
  141. // jumps to the default branch. At this point in the tree, the value
  142. // can't be another valid case value, so the jump to the "default" branch
  143. // is warranted.
  144. //
  145. BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
  146. BasicBlock* OrigBlock,
  147. BasicBlock* Default)
  148. {
  149. Function* F = OrigBlock->getParent();
  150. BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
  151. Function::iterator FI = OrigBlock;
  152. F->getBasicBlockList().insert(++FI, NewLeaf);
  153. // Emit comparison
  154. ICmpInst* Comp = NULL;
  155. if (Leaf.Low == Leaf.High) {
  156. // Make the seteq instruction...
  157. Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
  158. Leaf.Low, "SwitchLeaf");
  159. } else {
  160. // Make range comparison
  161. if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
  162. // Val >= Min && Val <= Hi --> Val <= Hi
  163. Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
  164. "SwitchLeaf");
  165. } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
  166. // Val >= 0 && Val <= Hi --> Val <=u Hi
  167. Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
  168. "SwitchLeaf");
  169. } else {
  170. // Emit V-Lo <=u Hi-Lo
  171. Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
  172. Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
  173. Val->getName()+".off",
  174. NewLeaf);
  175. Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
  176. Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
  177. "SwitchLeaf");
  178. }
  179. }
  180. // Make the conditional branch...
  181. BasicBlock* Succ = Leaf.BB;
  182. BranchInst::Create(Succ, Default, Comp, NewLeaf);
  183. // If there were any PHI nodes in this successor, rewrite one entry
  184. // from OrigBlock to come from NewLeaf.
  185. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  186. PHINode* PN = cast<PHINode>(I);
  187. // Remove all but one incoming entries from the cluster
  188. uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
  189. cast<ConstantInt>(Leaf.Low)->getSExtValue();
  190. for (uint64_t j = 0; j < Range; ++j) {
  191. PN->removeIncomingValue(OrigBlock);
  192. }
  193. int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
  194. assert(BlockIdx != -1 && "Switch didn't go to this successor??");
  195. PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
  196. }
  197. return NewLeaf;
  198. }
  199. // Clusterify - Transform simple list of Cases into list of CaseRange's
  200. unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
  201. unsigned numCmps = 0;
  202. // Start with "simple" cases
  203. for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
  204. Cases.push_back(CaseRange(SI->getSuccessorValue(i),
  205. SI->getSuccessorValue(i),
  206. SI->getSuccessor(i)));
  207. std::sort(Cases.begin(), Cases.end(), CaseCmp());
  208. // Merge case into clusters
  209. if (Cases.size()>=2)
  210. for (CaseItr I=Cases.begin(), J=llvm::next(Cases.begin()); J!=Cases.end(); ) {
  211. int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
  212. int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
  213. BasicBlock* nextBB = J->BB;
  214. BasicBlock* currentBB = I->BB;
  215. // If the two neighboring cases go to the same destination, merge them
  216. // into a single case.
  217. if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
  218. I->High = J->High;
  219. J = Cases.erase(J);
  220. } else {
  221. I = J++;
  222. }
  223. }
  224. for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
  225. if (I->Low != I->High)
  226. // A range counts double, since it requires two compares.
  227. ++numCmps;
  228. }
  229. return numCmps;
  230. }
  231. // processSwitchInst - Replace the specified switch instruction with a sequence
  232. // of chained if-then insts in a balanced binary search.
  233. //
  234. void LowerSwitch::processSwitchInst(SwitchInst *SI) {
  235. BasicBlock *CurBlock = SI->getParent();
  236. BasicBlock *OrigBlock = CurBlock;
  237. Function *F = CurBlock->getParent();
  238. Value *Val = SI->getOperand(0); // The value we are switching on...
  239. BasicBlock* Default = SI->getDefaultDest();
  240. // If there is only the default destination, don't bother with the code below.
  241. if (SI->getNumOperands() == 2) {
  242. BranchInst::Create(SI->getDefaultDest(), CurBlock);
  243. CurBlock->getInstList().erase(SI);
  244. return;
  245. }
  246. // Create a new, empty default block so that the new hierarchy of
  247. // if-then statements go to this and the PHI nodes are happy.
  248. BasicBlock* NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
  249. F->getBasicBlockList().insert(Default, NewDefault);
  250. BranchInst::Create(Default, NewDefault);
  251. // If there is an entry in any PHI nodes for the default edge, make sure
  252. // to update them as well.
  253. for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
  254. PHINode *PN = cast<PHINode>(I);
  255. int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
  256. assert(BlockIdx != -1 && "Switch didn't go to this successor??");
  257. PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
  258. }
  259. // Prepare cases vector.
  260. CaseVector Cases;
  261. unsigned numCmps = Clusterify(Cases, SI);
  262. DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
  263. << ". Total compares: " << numCmps << "\n");
  264. DEBUG(dbgs() << "Cases: " << Cases << "\n");
  265. (void)numCmps;
  266. BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
  267. OrigBlock, NewDefault);
  268. // Branch to our shiny new if-then stuff...
  269. BranchInst::Create(SwitchBlock, OrigBlock);
  270. // We are now done with the switch instruction, delete it.
  271. CurBlock->getInstList().erase(SI);
  272. }