1 //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Pass.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
31 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
32 /// instructions. Note that this cannot be a BasicBlock pass because it
34 class LowerSwitch : public FunctionPass {
36 static char ID; // Pass identification, replacement for typeid
37 LowerSwitch() : FunctionPass(ID) {}
39 virtual bool runOnFunction(Function &F);
41 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42 // This is a cluster of orthogonal Transforms
43 AU.addPreserved<UnifyFunctionExitNodes>();
44 AU.addPreserved("mem2reg");
45 AU.addPreservedID(LowerInvokePassID);
53 CaseRange() : Low(0), High(0), BB(0) { }
54 CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
55 Low(low), High(high), BB(bb) { }
58 typedef std::vector<CaseRange> CaseVector;
59 typedef std::vector<CaseRange>::iterator CaseItr;
61 void processSwitchInst(SwitchInst *SI);
63 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
64 BasicBlock* OrigBlock, BasicBlock* Default);
65 BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
66 BasicBlock* OrigBlock, BasicBlock* Default);
67 unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
70 /// The comparison function for sorting the switch case values in the vector.
71 /// WARNING: Case ranges should be disjoint!
73 bool operator () (const LowerSwitch::CaseRange& C1,
74 const LowerSwitch::CaseRange& C2) {
76 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
77 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
78 return CI1->getValue().slt(CI2->getValue());
83 char LowerSwitch::ID = 0;
84 static RegisterPass<LowerSwitch>
85 X("lowerswitch", "Lower SwitchInst's to branches");
87 // Publically exposed interface to pass...
88 char &llvm::LowerSwitchID = LowerSwitch::ID;
89 // createLowerSwitchPass - Interface to this file...
90 FunctionPass *llvm::createLowerSwitchPass() {
91 return new LowerSwitch();
94 bool LowerSwitch::runOnFunction(Function &F) {
97 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
98 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
100 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
102 processSwitchInst(SI);
109 // operator<< - Used for debugging purposes.
111 static raw_ostream& operator<<(raw_ostream &O,
112 const LowerSwitch::CaseVector &C) ATTRIBUTE_USED;
113 static raw_ostream& operator<<(raw_ostream &O,
114 const LowerSwitch::CaseVector &C) {
117 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
118 E = C.end(); B != E; ) {
119 O << *B->Low << " -" << *B->High;
120 if (++B != E) O << ", ";
126 // switchConvert - Convert the switch statement into a binary lookup of
127 // the case values. The function recursively builds this tree.
129 BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
130 Value* Val, BasicBlock* OrigBlock,
133 unsigned Size = End - Begin;
136 return newLeafBlock(*Begin, Val, OrigBlock, Default);
138 unsigned Mid = Size / 2;
139 std::vector<CaseRange> LHS(Begin, Begin + Mid);
140 DEBUG(dbgs() << "LHS: " << LHS << "\n");
141 std::vector<CaseRange> RHS(Begin + Mid, End);
142 DEBUG(dbgs() << "RHS: " << RHS << "\n");
144 CaseRange& Pivot = *(Begin + Mid);
145 DEBUG(dbgs() << "Pivot ==> "
146 << cast<ConstantInt>(Pivot.Low)->getValue() << " -"
147 << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
149 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
151 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
154 // Create a new node that checks if the value is < pivot. Go to the
155 // left branch if it is and right branch if not.
156 Function* F = OrigBlock->getParent();
157 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
158 Function::iterator FI = OrigBlock;
159 F->getBasicBlockList().insert(++FI, NewNode);
161 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
162 Val, Pivot.Low, "Pivot");
163 NewNode->getInstList().push_back(Comp);
164 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
168 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
169 // checks if the switch's value == the case's value. If not, then it
170 // jumps to the default branch. At this point in the tree, the value
171 // can't be another valid case value, so the jump to the "default" branch
174 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
175 BasicBlock* OrigBlock,
178 Function* F = OrigBlock->getParent();
179 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
180 Function::iterator FI = OrigBlock;
181 F->getBasicBlockList().insert(++FI, NewLeaf);
184 ICmpInst* Comp = NULL;
185 if (Leaf.Low == Leaf.High) {
186 // Make the seteq instruction...
187 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
188 Leaf.Low, "SwitchLeaf");
190 // Make range comparison
191 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
192 // Val >= Min && Val <= Hi --> Val <= Hi
193 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
195 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
196 // Val >= 0 && Val <= Hi --> Val <=u Hi
197 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
200 // Emit V-Lo <=u Hi-Lo
201 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
202 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
203 Val->getName()+".off",
205 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
206 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
211 // Make the conditional branch...
212 BasicBlock* Succ = Leaf.BB;
213 BranchInst::Create(Succ, Default, Comp, NewLeaf);
215 // If there were any PHI nodes in this successor, rewrite one entry
216 // from OrigBlock to come from NewLeaf.
217 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
218 PHINode* PN = cast<PHINode>(I);
219 // Remove all but one incoming entries from the cluster
220 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
221 cast<ConstantInt>(Leaf.Low)->getSExtValue();
222 for (uint64_t j = 0; j < Range; ++j) {
223 PN->removeIncomingValue(OrigBlock);
226 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
227 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
228 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
234 // Clusterify - Transform simple list of Cases into list of CaseRange's
235 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
236 unsigned numCmps = 0;
238 // Start with "simple" cases
239 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
240 Cases.push_back(CaseRange(SI->getSuccessorValue(i),
241 SI->getSuccessorValue(i),
242 SI->getSuccessor(i)));
243 std::sort(Cases.begin(), Cases.end(), CaseCmp());
245 // Merge case into clusters
247 for (CaseItr I=Cases.begin(), J=llvm::next(Cases.begin()); J!=Cases.end(); ) {
248 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
249 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
250 BasicBlock* nextBB = J->BB;
251 BasicBlock* currentBB = I->BB;
253 // If the two neighboring cases go to the same destination, merge them
254 // into a single case.
255 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
263 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
264 if (I->Low != I->High)
265 // A range counts double, since it requires two compares.
272 // processSwitchInst - Replace the specified switch instruction with a sequence
273 // of chained if-then insts in a balanced binary search.
275 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
276 BasicBlock *CurBlock = SI->getParent();
277 BasicBlock *OrigBlock = CurBlock;
278 Function *F = CurBlock->getParent();
279 Value *Val = SI->getOperand(0); // The value we are switching on...
280 BasicBlock* Default = SI->getDefaultDest();
282 // If there is only the default destination, don't bother with the code below.
283 if (SI->getNumOperands() == 2) {
284 BranchInst::Create(SI->getDefaultDest(), CurBlock);
285 CurBlock->getInstList().erase(SI);
289 // Create a new, empty default block so that the new hierarchy of
290 // if-then statements go to this and the PHI nodes are happy.
291 BasicBlock* NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
292 F->getBasicBlockList().insert(Default, NewDefault);
294 BranchInst::Create(Default, NewDefault);
296 // If there is an entry in any PHI nodes for the default edge, make sure
297 // to update them as well.
298 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
299 PHINode *PN = cast<PHINode>(I);
300 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
301 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
302 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
305 // Prepare cases vector.
307 unsigned numCmps = Clusterify(Cases, SI);
309 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
310 << ". Total compares: " << numCmps << "\n");
311 DEBUG(dbgs() << "Cases: " << Cases << "\n");
314 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
315 OrigBlock, NewDefault);
317 // Branch to our shiny new if-then stuff...
318 BranchInst::Create(SwitchBlock, OrigBlock);
320 // We are now done with the switch instruction, delete it.
321 CurBlock->getInstList().erase(SI);