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