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