1 //===- DFAJumpThreading.cpp - Threads a switch statement inside a loop ----===// 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 // Transform each threading path to effectively jump thread the DFA. For 10 // example, the CFG below could be transformed as follows, where the cloned 11 // blocks unconditionally branch to the next correct case based on what is 12 // identified in the analysis. 13 // 14 // sw.bb sw.bb 15 // / | \ / | \ 16 // case1 case2 case3 case1 case2 case3 17 // \ | / | | | 18 // determinator det.2 det.3 det.1 19 // br sw.bb / | \ 20 // sw.bb.2 sw.bb.3 sw.bb.1 21 // br case2 br case3 br case1§ 22 // 23 // Definitions and Terminology: 24 // 25 // * Threading path: 26 // a list of basic blocks, the exit state, and the block that determines 27 // the next state, for which the following notation will be used: 28 // < path of BBs that form a cycle > [ state, determinator ] 29 // 30 // * Predictable switch: 31 // The switch variable is always a known constant so that all conditional 32 // jumps based on switch variable can be converted to unconditional jump. 33 // 34 // * Determinator: 35 // The basic block that determines the next state of the DFA. 36 // 37 // Representing the optimization in C-like pseudocode: the code pattern on the 38 // left could functionally be transformed to the right pattern if the switch 39 // condition is predictable. 40 // 41 // X = A goto A 42 // for (...) A: 43 // switch (X) ... 44 // case A goto B 45 // X = B B: 46 // case B ... 47 // X = C goto C 48 // 49 // The pass first checks that switch variable X is decided by the control flow 50 // path taken in the loop; for example, in case B, the next value of X is 51 // decided to be C. It then enumerates through all paths in the loop and labels 52 // the basic blocks where the next state is decided. 53 // 54 // Using this information it creates new paths that unconditionally branch to 55 // the next case. This involves cloning code, so it only gets triggered if the 56 // amount of code duplicated is below a threshold. 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Transforms/Scalar/DFAJumpThreading.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/DenseMap.h" 63 #include "llvm/ADT/DepthFirstIterator.h" 64 #include "llvm/ADT/SmallSet.h" 65 #include "llvm/ADT/Statistic.h" 66 #include "llvm/Analysis/AssumptionCache.h" 67 #include "llvm/Analysis/CodeMetrics.h" 68 #include "llvm/Analysis/LoopIterator.h" 69 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 70 #include "llvm/Analysis/TargetTransformInfo.h" 71 #include "llvm/IR/CFG.h" 72 #include "llvm/IR/Constants.h" 73 #include "llvm/IR/IntrinsicInst.h" 74 #include "llvm/IR/Verifier.h" 75 #include "llvm/InitializePasses.h" 76 #include "llvm/Pass.h" 77 #include "llvm/Support/CommandLine.h" 78 #include "llvm/Support/Debug.h" 79 #include "llvm/Transforms/Scalar.h" 80 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 81 #include "llvm/Transforms/Utils/Cloning.h" 82 #include "llvm/Transforms/Utils/SSAUpdaterBulk.h" 83 #include "llvm/Transforms/Utils/ValueMapper.h" 84 #include <algorithm> 85 #include <deque> 86 87 using namespace llvm; 88 89 #define DEBUG_TYPE "dfa-jump-threading" 90 91 STATISTIC(NumTransforms, "Number of transformations done"); 92 STATISTIC(NumCloned, "Number of blocks cloned"); 93 STATISTIC(NumPaths, "Number of individual paths threaded"); 94 95 static cl::opt<bool> 96 ClViewCfgBefore("dfa-jump-view-cfg-before", 97 cl::desc("View the CFG before DFA Jump Threading"), 98 cl::Hidden, cl::init(false)); 99 100 static cl::opt<unsigned> MaxPathLength( 101 "dfa-max-path-length", 102 cl::desc("Max number of blocks searched to find a threading path"), 103 cl::Hidden, cl::init(20)); 104 105 static cl::opt<unsigned> 106 CostThreshold("dfa-cost-threshold", 107 cl::desc("Maximum cost accepted for the transformation"), 108 cl::Hidden, cl::init(50)); 109 110 namespace { 111 112 class SelectInstToUnfold { 113 SelectInst *SI; 114 PHINode *SIUse; 115 116 public: 117 SelectInstToUnfold(SelectInst *SI, PHINode *SIUse) : SI(SI), SIUse(SIUse) {} 118 119 SelectInst *getInst() { return SI; } 120 PHINode *getUse() { return SIUse; } 121 122 explicit operator bool() const { return SI && SIUse; } 123 }; 124 125 void unfold(DomTreeUpdater *DTU, SelectInstToUnfold SIToUnfold, 126 std::vector<SelectInstToUnfold> *NewSIsToUnfold, 127 std::vector<BasicBlock *> *NewBBs); 128 129 class DFAJumpThreading { 130 public: 131 DFAJumpThreading(AssumptionCache *AC, DominatorTree *DT, 132 TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE) 133 : AC(AC), DT(DT), TTI(TTI), ORE(ORE) {} 134 135 bool run(Function &F); 136 137 private: 138 void 139 unfoldSelectInstrs(DominatorTree *DT, 140 const SmallVector<SelectInstToUnfold, 4> &SelectInsts) { 141 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 142 SmallVector<SelectInstToUnfold, 4> Stack; 143 for (SelectInstToUnfold SIToUnfold : SelectInsts) 144 Stack.push_back(SIToUnfold); 145 146 while (!Stack.empty()) { 147 SelectInstToUnfold SIToUnfold = Stack.pop_back_val(); 148 149 std::vector<SelectInstToUnfold> NewSIsToUnfold; 150 std::vector<BasicBlock *> NewBBs; 151 unfold(&DTU, SIToUnfold, &NewSIsToUnfold, &NewBBs); 152 153 // Put newly discovered select instructions into the work list. 154 for (const SelectInstToUnfold &NewSIToUnfold : NewSIsToUnfold) 155 Stack.push_back(NewSIToUnfold); 156 } 157 } 158 159 AssumptionCache *AC; 160 DominatorTree *DT; 161 TargetTransformInfo *TTI; 162 OptimizationRemarkEmitter *ORE; 163 }; 164 165 class DFAJumpThreadingLegacyPass : public FunctionPass { 166 public: 167 static char ID; // Pass identification 168 DFAJumpThreadingLegacyPass() : FunctionPass(ID) {} 169 170 void getAnalysisUsage(AnalysisUsage &AU) const override { 171 AU.addRequired<AssumptionCacheTracker>(); 172 AU.addRequired<DominatorTreeWrapperPass>(); 173 AU.addPreserved<DominatorTreeWrapperPass>(); 174 AU.addRequired<TargetTransformInfoWrapperPass>(); 175 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 176 } 177 178 bool runOnFunction(Function &F) override { 179 if (skipFunction(F)) 180 return false; 181 182 AssumptionCache *AC = 183 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 184 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 185 TargetTransformInfo *TTI = 186 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 187 OptimizationRemarkEmitter *ORE = 188 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 189 190 return DFAJumpThreading(AC, DT, TTI, ORE).run(F); 191 } 192 }; 193 } // end anonymous namespace 194 195 char DFAJumpThreadingLegacyPass::ID = 0; 196 INITIALIZE_PASS_BEGIN(DFAJumpThreadingLegacyPass, "dfa-jump-threading", 197 "DFA Jump Threading", false, false) 198 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 199 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 200 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 201 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 202 INITIALIZE_PASS_END(DFAJumpThreadingLegacyPass, "dfa-jump-threading", 203 "DFA Jump Threading", false, false) 204 205 // Public interface to the DFA Jump Threading pass 206 FunctionPass *llvm::createDFAJumpThreadingPass() { 207 return new DFAJumpThreadingLegacyPass(); 208 } 209 210 namespace { 211 212 /// Create a new basic block and sink \p SIToSink into it. 213 void createBasicBlockAndSinkSelectInst( 214 DomTreeUpdater *DTU, SelectInst *SI, PHINode *SIUse, SelectInst *SIToSink, 215 BasicBlock *EndBlock, StringRef NewBBName, BasicBlock **NewBlock, 216 BranchInst **NewBranch, std::vector<SelectInstToUnfold> *NewSIsToUnfold, 217 std::vector<BasicBlock *> *NewBBs) { 218 assert(SIToSink->hasOneUse()); 219 assert(NewBlock); 220 assert(NewBranch); 221 *NewBlock = BasicBlock::Create(SI->getContext(), NewBBName, 222 EndBlock->getParent(), EndBlock); 223 NewBBs->push_back(*NewBlock); 224 *NewBranch = BranchInst::Create(EndBlock, *NewBlock); 225 SIToSink->moveBefore(*NewBranch); 226 NewSIsToUnfold->push_back(SelectInstToUnfold(SIToSink, SIUse)); 227 DTU->applyUpdates({{DominatorTree::Insert, *NewBlock, EndBlock}}); 228 } 229 230 /// Unfold the select instruction held in \p SIToUnfold by replacing it with 231 /// control flow. 232 /// 233 /// Put newly discovered select instructions into \p NewSIsToUnfold. Put newly 234 /// created basic blocks into \p NewBBs. 235 /// 236 /// TODO: merge it with CodeGenPrepare::optimizeSelectInst() if possible. 237 void unfold(DomTreeUpdater *DTU, SelectInstToUnfold SIToUnfold, 238 std::vector<SelectInstToUnfold> *NewSIsToUnfold, 239 std::vector<BasicBlock *> *NewBBs) { 240 SelectInst *SI = SIToUnfold.getInst(); 241 PHINode *SIUse = SIToUnfold.getUse(); 242 BasicBlock *StartBlock = SI->getParent(); 243 BasicBlock *EndBlock = SIUse->getParent(); 244 BranchInst *StartBlockTerm = 245 dyn_cast<BranchInst>(StartBlock->getTerminator()); 246 247 assert(StartBlockTerm && StartBlockTerm->isUnconditional()); 248 assert(SI->hasOneUse()); 249 250 // These are the new basic blocks for the conditional branch. 251 // At least one will become an actual new basic block. 252 BasicBlock *TrueBlock = nullptr; 253 BasicBlock *FalseBlock = nullptr; 254 BranchInst *TrueBranch = nullptr; 255 BranchInst *FalseBranch = nullptr; 256 257 // Sink select instructions to be able to unfold them later. 258 if (SelectInst *SIOp = dyn_cast<SelectInst>(SI->getTrueValue())) { 259 createBasicBlockAndSinkSelectInst(DTU, SI, SIUse, SIOp, EndBlock, 260 "si.unfold.true", &TrueBlock, &TrueBranch, 261 NewSIsToUnfold, NewBBs); 262 } 263 if (SelectInst *SIOp = dyn_cast<SelectInst>(SI->getFalseValue())) { 264 createBasicBlockAndSinkSelectInst(DTU, SI, SIUse, SIOp, EndBlock, 265 "si.unfold.false", &FalseBlock, 266 &FalseBranch, NewSIsToUnfold, NewBBs); 267 } 268 269 // If there was nothing to sink, then arbitrarily choose the 'false' side 270 // for a new input value to the PHI. 271 if (!TrueBlock && !FalseBlock) { 272 FalseBlock = BasicBlock::Create(SI->getContext(), "si.unfold.false", 273 EndBlock->getParent(), EndBlock); 274 NewBBs->push_back(FalseBlock); 275 BranchInst::Create(EndBlock, FalseBlock); 276 DTU->applyUpdates({{DominatorTree::Insert, FalseBlock, EndBlock}}); 277 } 278 279 // Insert the real conditional branch based on the original condition. 280 // If we did not create a new block for one of the 'true' or 'false' paths 281 // of the condition, it means that side of the branch goes to the end block 282 // directly and the path originates from the start block from the point of 283 // view of the new PHI. 284 BasicBlock *TT = EndBlock; 285 BasicBlock *FT = EndBlock; 286 if (TrueBlock && FalseBlock) { 287 // A diamond. 288 TT = TrueBlock; 289 FT = FalseBlock; 290 291 // Update the phi node of SI. 292 SIUse->removeIncomingValue(StartBlock, /* DeletePHIIfEmpty = */ false); 293 SIUse->addIncoming(SI->getTrueValue(), TrueBlock); 294 SIUse->addIncoming(SI->getFalseValue(), FalseBlock); 295 296 // Update any other PHI nodes in EndBlock. 297 for (PHINode &Phi : EndBlock->phis()) { 298 if (&Phi != SIUse) { 299 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), TrueBlock); 300 Phi.addIncoming(Phi.getIncomingValueForBlock(StartBlock), FalseBlock); 301 } 302 } 303 } else { 304 BasicBlock *NewBlock = nullptr; 305 Value *SIOp1 = SI->getTrueValue(); 306 Value *SIOp2 = SI->getFalseValue(); 307 308 // A triangle pointing right. 309 if (!TrueBlock) { 310 NewBlock = FalseBlock; 311 FT = FalseBlock; 312 } 313 // A triangle pointing left. 314 else { 315 NewBlock = TrueBlock; 316 TT = TrueBlock; 317 std::swap(SIOp1, SIOp2); 318 } 319 320 // Update the phi node of SI. 321 for (unsigned Idx = 0; Idx < SIUse->getNumIncomingValues(); ++Idx) { 322 if (SIUse->getIncomingBlock(Idx) == StartBlock) 323 SIUse->setIncomingValue(Idx, SIOp1); 324 } 325 SIUse->addIncoming(SIOp2, NewBlock); 326 327 // Update any other PHI nodes in EndBlock. 328 for (auto II = EndBlock->begin(); PHINode *Phi = dyn_cast<PHINode>(II); 329 ++II) { 330 if (Phi != SIUse) 331 Phi->addIncoming(Phi->getIncomingValueForBlock(StartBlock), NewBlock); 332 } 333 } 334 StartBlockTerm->eraseFromParent(); 335 BranchInst::Create(TT, FT, SI->getCondition(), StartBlock); 336 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, TT}, 337 {DominatorTree::Insert, StartBlock, FT}}); 338 339 // The select is now dead. 340 SI->eraseFromParent(); 341 } 342 343 struct ClonedBlock { 344 BasicBlock *BB; 345 uint64_t State; ///< \p State corresponds to the next value of a switch stmnt. 346 }; 347 348 typedef std::deque<BasicBlock *> PathType; 349 typedef std::vector<PathType> PathsType; 350 typedef SmallPtrSet<const BasicBlock *, 8> VisitedBlocks; 351 typedef std::vector<ClonedBlock> CloneList; 352 353 // This data structure keeps track of all blocks that have been cloned. If two 354 // different ThreadingPaths clone the same block for a certain state it should 355 // be reused, and it can be looked up in this map. 356 typedef DenseMap<BasicBlock *, CloneList> DuplicateBlockMap; 357 358 // This map keeps track of all the new definitions for an instruction. This 359 // information is needed when restoring SSA form after cloning blocks. 360 typedef MapVector<Instruction *, std::vector<Instruction *>> DefMap; 361 362 inline raw_ostream &operator<<(raw_ostream &OS, const PathType &Path) { 363 OS << "< "; 364 for (const BasicBlock *BB : Path) { 365 std::string BBName; 366 if (BB->hasName()) 367 raw_string_ostream(BBName) << BB->getName(); 368 else 369 raw_string_ostream(BBName) << BB; 370 OS << BBName << " "; 371 } 372 OS << ">"; 373 return OS; 374 } 375 376 /// ThreadingPath is a path in the control flow of a loop that can be threaded 377 /// by cloning necessary basic blocks and replacing conditional branches with 378 /// unconditional ones. A threading path includes a list of basic blocks, the 379 /// exit state, and the block that determines the next state. 380 struct ThreadingPath { 381 /// Exit value is DFA's exit state for the given path. 382 uint64_t getExitValue() const { return ExitVal; } 383 void setExitValue(const ConstantInt *V) { 384 ExitVal = V->getZExtValue(); 385 IsExitValSet = true; 386 } 387 bool isExitValueSet() const { return IsExitValSet; } 388 389 /// Determinator is the basic block that determines the next state of the DFA. 390 const BasicBlock *getDeterminatorBB() const { return DBB; } 391 void setDeterminator(const BasicBlock *BB) { DBB = BB; } 392 393 /// Path is a list of basic blocks. 394 const PathType &getPath() const { return Path; } 395 void setPath(const PathType &NewPath) { Path = NewPath; } 396 397 void print(raw_ostream &OS) const { 398 OS << Path << " [ " << ExitVal << ", " << DBB->getName() << " ]"; 399 } 400 401 private: 402 PathType Path; 403 uint64_t ExitVal; 404 const BasicBlock *DBB = nullptr; 405 bool IsExitValSet = false; 406 }; 407 408 #ifndef NDEBUG 409 inline raw_ostream &operator<<(raw_ostream &OS, const ThreadingPath &TPath) { 410 TPath.print(OS); 411 return OS; 412 } 413 #endif 414 415 struct MainSwitch { 416 MainSwitch(SwitchInst *SI, OptimizationRemarkEmitter *ORE) { 417 if (isPredictable(SI)) { 418 Instr = SI; 419 } else { 420 ORE->emit([&]() { 421 return OptimizationRemarkMissed(DEBUG_TYPE, "SwitchNotPredictable", SI) 422 << "Switch instruction is not predictable."; 423 }); 424 } 425 } 426 427 virtual ~MainSwitch() = default; 428 429 SwitchInst *getInstr() const { return Instr; } 430 const SmallVector<SelectInstToUnfold, 4> getSelectInsts() { 431 return SelectInsts; 432 } 433 434 private: 435 /// Do a use-def chain traversal. Make sure the value of the switch variable 436 /// is always a known constant. This means that all conditional jumps based on 437 /// switch variable can be converted to unconditional jumps. 438 bool isPredictable(const SwitchInst *SI) { 439 std::deque<Instruction *> Q; 440 SmallSet<Value *, 16> SeenValues; 441 SelectInsts.clear(); 442 443 Value *FirstDef = SI->getOperand(0); 444 auto *Inst = dyn_cast<Instruction>(FirstDef); 445 446 // If this is a function argument or another non-instruction, then give up. 447 // We are interested in loop local variables. 448 if (!Inst) 449 return false; 450 451 // Require the first definition to be a PHINode 452 if (!isa<PHINode>(Inst)) 453 return false; 454 455 LLVM_DEBUG(dbgs() << "\tisPredictable() FirstDef: " << *Inst << "\n"); 456 457 Q.push_back(Inst); 458 SeenValues.insert(FirstDef); 459 460 while (!Q.empty()) { 461 Instruction *Current = Q.front(); 462 Q.pop_front(); 463 464 if (auto *Phi = dyn_cast<PHINode>(Current)) { 465 for (Value *Incoming : Phi->incoming_values()) { 466 if (!isPredictableValue(Incoming, SeenValues)) 467 return false; 468 addInstToQueue(Incoming, Q, SeenValues); 469 } 470 LLVM_DEBUG(dbgs() << "\tisPredictable() phi: " << *Phi << "\n"); 471 } else if (SelectInst *SelI = dyn_cast<SelectInst>(Current)) { 472 if (!isValidSelectInst(SelI)) 473 return false; 474 if (!isPredictableValue(SelI->getTrueValue(), SeenValues) || 475 !isPredictableValue(SelI->getFalseValue(), SeenValues)) { 476 return false; 477 } 478 addInstToQueue(SelI->getTrueValue(), Q, SeenValues); 479 addInstToQueue(SelI->getFalseValue(), Q, SeenValues); 480 LLVM_DEBUG(dbgs() << "\tisPredictable() select: " << *SelI << "\n"); 481 if (auto *SelIUse = dyn_cast<PHINode>(SelI->user_back())) 482 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse)); 483 } else { 484 // If it is neither a phi nor a select, then we give up. 485 return false; 486 } 487 } 488 489 return true; 490 } 491 492 bool isPredictableValue(Value *InpVal, SmallSet<Value *, 16> &SeenValues) { 493 if (SeenValues.contains(InpVal)) 494 return true; 495 496 if (isa<ConstantInt>(InpVal)) 497 return true; 498 499 // If this is a function argument or another non-instruction, then give up. 500 if (!isa<Instruction>(InpVal)) 501 return false; 502 503 return true; 504 } 505 506 void addInstToQueue(Value *Val, std::deque<Instruction *> &Q, 507 SmallSet<Value *, 16> &SeenValues) { 508 if (SeenValues.contains(Val)) 509 return; 510 if (Instruction *I = dyn_cast<Instruction>(Val)) 511 Q.push_back(I); 512 SeenValues.insert(Val); 513 } 514 515 bool isValidSelectInst(SelectInst *SI) { 516 if (!SI->hasOneUse()) 517 return false; 518 519 Instruction *SIUse = dyn_cast<Instruction>(SI->user_back()); 520 // The use of the select inst should be either a phi or another select. 521 if (!SIUse && !(isa<PHINode>(SIUse) || isa<SelectInst>(SIUse))) 522 return false; 523 524 BasicBlock *SIBB = SI->getParent(); 525 526 // Currently, we can only expand select instructions in basic blocks with 527 // one successor. 528 BranchInst *SITerm = dyn_cast<BranchInst>(SIBB->getTerminator()); 529 if (!SITerm || !SITerm->isUnconditional()) 530 return false; 531 532 if (isa<PHINode>(SIUse) && 533 SIBB->getSingleSuccessor() != cast<Instruction>(SIUse)->getParent()) 534 return false; 535 536 // If select will not be sunk during unfolding, and it is in the same basic 537 // block as another state defining select, then cannot unfold both. 538 for (SelectInstToUnfold SIToUnfold : SelectInsts) { 539 SelectInst *PrevSI = SIToUnfold.getInst(); 540 if (PrevSI->getTrueValue() != SI && PrevSI->getFalseValue() != SI && 541 PrevSI->getParent() == SI->getParent()) 542 return false; 543 } 544 545 return true; 546 } 547 548 SwitchInst *Instr = nullptr; 549 SmallVector<SelectInstToUnfold, 4> SelectInsts; 550 }; 551 552 struct AllSwitchPaths { 553 AllSwitchPaths(const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE) 554 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->getParent()), 555 ORE(ORE) {} 556 557 std::vector<ThreadingPath> &getThreadingPaths() { return TPaths; } 558 unsigned getNumThreadingPaths() { return TPaths.size(); } 559 SwitchInst *getSwitchInst() { return Switch; } 560 BasicBlock *getSwitchBlock() { return SwitchBlock; } 561 562 void run() { 563 VisitedBlocks Visited; 564 PathsType LoopPaths = paths(SwitchBlock, Visited, /* PathDepth = */ 1); 565 StateDefMap StateDef = getStateDefMap(); 566 567 for (PathType Path : LoopPaths) { 568 ThreadingPath TPath; 569 570 const BasicBlock *PrevBB = Path.back(); 571 for (const BasicBlock *BB : Path) { 572 if (StateDef.count(BB) != 0) { 573 const PHINode *Phi = dyn_cast<PHINode>(StateDef[BB]); 574 assert(Phi && "Expected a state-defining instr to be a phi node."); 575 576 const Value *V = Phi->getIncomingValueForBlock(PrevBB); 577 if (const ConstantInt *C = dyn_cast<const ConstantInt>(V)) { 578 TPath.setExitValue(C); 579 TPath.setDeterminator(BB); 580 TPath.setPath(Path); 581 } 582 } 583 584 // Switch block is the determinator, this is the final exit value. 585 if (TPath.isExitValueSet() && BB == Path.front()) 586 break; 587 588 PrevBB = BB; 589 } 590 591 if (TPath.isExitValueSet() && isSupported(TPath)) 592 TPaths.push_back(TPath); 593 } 594 } 595 596 private: 597 // Value: an instruction that defines a switch state; 598 // Key: the parent basic block of that instruction. 599 typedef DenseMap<const BasicBlock *, const PHINode *> StateDefMap; 600 601 PathsType paths(BasicBlock *BB, VisitedBlocks &Visited, 602 unsigned PathDepth) const { 603 PathsType Res; 604 605 // Stop exploring paths after visiting MaxPathLength blocks 606 if (PathDepth > MaxPathLength) { 607 ORE->emit([&]() { 608 return OptimizationRemarkAnalysis(DEBUG_TYPE, "MaxPathLengthReached", 609 Switch) 610 << "Exploration stopped after visiting MaxPathLength=" 611 << ore::NV("MaxPathLength", MaxPathLength) << " blocks."; 612 }); 613 return Res; 614 } 615 616 Visited.insert(BB); 617 618 // Some blocks have multiple edges to the same successor, and this set 619 // is used to prevent a duplicate path from being generated 620 SmallSet<BasicBlock *, 4> Successors; 621 for (BasicBlock *Succ : successors(BB)) { 622 if (!Successors.insert(Succ).second) 623 continue; 624 625 // Found a cycle through the SwitchBlock 626 if (Succ == SwitchBlock) { 627 Res.push_back({BB}); 628 continue; 629 } 630 631 // We have encountered a cycle, do not get caught in it 632 if (Visited.contains(Succ)) 633 continue; 634 635 PathsType SuccPaths = paths(Succ, Visited, PathDepth + 1); 636 for (PathType Path : SuccPaths) { 637 PathType NewPath(Path); 638 NewPath.push_front(BB); 639 Res.push_back(NewPath); 640 } 641 } 642 // This block could now be visited again from a different predecessor. Note 643 // that this will result in exponential runtime. Subpaths could possibly be 644 // cached but it takes a lot of memory to store them. 645 Visited.erase(BB); 646 return Res; 647 } 648 649 /// Walk the use-def chain and collect all the state-defining instructions. 650 StateDefMap getStateDefMap() const { 651 StateDefMap Res; 652 653 Value *FirstDef = Switch->getOperand(0); 654 655 assert(isa<PHINode>(FirstDef) && "After select unfolding, all state " 656 "definitions are expected to be phi " 657 "nodes."); 658 659 SmallVector<PHINode *, 8> Stack; 660 Stack.push_back(dyn_cast<PHINode>(FirstDef)); 661 SmallSet<Value *, 16> SeenValues; 662 663 while (!Stack.empty()) { 664 PHINode *CurPhi = Stack.pop_back_val(); 665 666 Res[CurPhi->getParent()] = CurPhi; 667 SeenValues.insert(CurPhi); 668 669 for (Value *Incoming : CurPhi->incoming_values()) { 670 if (Incoming == FirstDef || isa<ConstantInt>(Incoming) || 671 SeenValues.contains(Incoming)) { 672 continue; 673 } 674 675 assert(isa<PHINode>(Incoming) && "After select unfolding, all state " 676 "definitions are expected to be phi " 677 "nodes."); 678 679 Stack.push_back(cast<PHINode>(Incoming)); 680 } 681 } 682 683 return Res; 684 } 685 686 /// The determinator BB should precede the switch-defining BB. 687 /// 688 /// Otherwise, it is possible that the state defined in the determinator block 689 /// defines the state for the next iteration of the loop, rather than for the 690 /// current one. 691 /// 692 /// Currently supported paths: 693 /// \code 694 /// < switch bb1 determ def > [ 42, determ ] 695 /// < switch_and_def bb1 determ > [ 42, determ ] 696 /// < switch_and_def_and_determ bb1 > [ 42, switch_and_def_and_determ ] 697 /// \endcode 698 /// 699 /// Unsupported paths: 700 /// \code 701 /// < switch bb1 def determ > [ 43, determ ] 702 /// < switch_and_determ bb1 def > [ 43, switch_and_determ ] 703 /// \endcode 704 bool isSupported(const ThreadingPath &TPath) { 705 Instruction *SwitchCondI = dyn_cast<Instruction>(Switch->getCondition()); 706 assert(SwitchCondI); 707 if (!SwitchCondI) 708 return false; 709 710 const BasicBlock *SwitchCondDefBB = SwitchCondI->getParent(); 711 const BasicBlock *SwitchCondUseBB = Switch->getParent(); 712 const BasicBlock *DeterminatorBB = TPath.getDeterminatorBB(); 713 714 assert( 715 SwitchCondUseBB == TPath.getPath().front() && 716 "The first BB in a threading path should have the switch instruction"); 717 if (SwitchCondUseBB != TPath.getPath().front()) 718 return false; 719 720 // Make DeterminatorBB the first element in Path. 721 PathType Path = TPath.getPath(); 722 auto ItDet = std::find(Path.begin(), Path.end(), DeterminatorBB); 723 std::rotate(Path.begin(), ItDet, Path.end()); 724 725 bool IsDetBBSeen = false; 726 bool IsDefBBSeen = false; 727 bool IsUseBBSeen = false; 728 for (BasicBlock *BB : Path) { 729 if (BB == DeterminatorBB) 730 IsDetBBSeen = true; 731 if (BB == SwitchCondDefBB) 732 IsDefBBSeen = true; 733 if (BB == SwitchCondUseBB) 734 IsUseBBSeen = true; 735 if (IsDetBBSeen && IsUseBBSeen && !IsDefBBSeen) 736 return false; 737 } 738 739 return true; 740 } 741 742 SwitchInst *Switch; 743 BasicBlock *SwitchBlock; 744 OptimizationRemarkEmitter *ORE; 745 std::vector<ThreadingPath> TPaths; 746 }; 747 748 struct TransformDFA { 749 TransformDFA(AllSwitchPaths *SwitchPaths, DominatorTree *DT, 750 AssumptionCache *AC, TargetTransformInfo *TTI, 751 OptimizationRemarkEmitter *ORE, 752 SmallPtrSet<const Value *, 32> EphValues) 753 : SwitchPaths(SwitchPaths), DT(DT), AC(AC), TTI(TTI), ORE(ORE), 754 EphValues(EphValues) {} 755 756 void run() { 757 if (isLegalAndProfitableToTransform()) { 758 createAllExitPaths(); 759 NumTransforms++; 760 } 761 } 762 763 private: 764 /// This function performs both a legality check and profitability check at 765 /// the same time since it is convenient to do so. It iterates through all 766 /// blocks that will be cloned, and keeps track of the duplication cost. It 767 /// also returns false if it is illegal to clone some required block. 768 bool isLegalAndProfitableToTransform() { 769 CodeMetrics Metrics; 770 SwitchInst *Switch = SwitchPaths->getSwitchInst(); 771 772 // Note that DuplicateBlockMap is not being used as intended here. It is 773 // just being used to ensure (BB, State) pairs are only counted once. 774 DuplicateBlockMap DuplicateMap; 775 776 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) { 777 PathType PathBBs = TPath.getPath(); 778 uint64_t NextState = TPath.getExitValue(); 779 const BasicBlock *Determinator = TPath.getDeterminatorBB(); 780 781 // Update Metrics for the Switch block, this is always cloned 782 BasicBlock *BB = SwitchPaths->getSwitchBlock(); 783 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap); 784 if (!VisitedBB) { 785 Metrics.analyzeBasicBlock(BB, *TTI, EphValues); 786 DuplicateMap[BB].push_back({BB, NextState}); 787 } 788 789 // If the Switch block is the Determinator, then we can continue since 790 // this is the only block that is cloned and we already counted for it. 791 if (PathBBs.front() == Determinator) 792 continue; 793 794 // Otherwise update Metrics for all blocks that will be cloned. If any 795 // block is already cloned and would be reused, don't double count it. 796 auto DetIt = std::find(PathBBs.begin(), PathBBs.end(), Determinator); 797 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) { 798 BB = *BBIt; 799 VisitedBB = getClonedBB(BB, NextState, DuplicateMap); 800 if (VisitedBB) 801 continue; 802 Metrics.analyzeBasicBlock(BB, *TTI, EphValues); 803 DuplicateMap[BB].push_back({BB, NextState}); 804 } 805 806 if (Metrics.notDuplicatable) { 807 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains " 808 << "non-duplicatable instructions.\n"); 809 ORE->emit([&]() { 810 return OptimizationRemarkMissed(DEBUG_TYPE, "NonDuplicatableInst", 811 Switch) 812 << "Contains non-duplicatable instructions."; 813 }); 814 return false; 815 } 816 817 if (Metrics.convergent) { 818 LLVM_DEBUG(dbgs() << "DFA Jump Threading: Not jump threading, contains " 819 << "convergent instructions.\n"); 820 ORE->emit([&]() { 821 return OptimizationRemarkMissed(DEBUG_TYPE, "ConvergentInst", Switch) 822 << "Contains convergent instructions."; 823 }); 824 return false; 825 } 826 } 827 828 unsigned DuplicationCost = 0; 829 830 unsigned JumpTableSize = 0; 831 TTI->getEstimatedNumberOfCaseClusters(*Switch, JumpTableSize, nullptr, 832 nullptr); 833 if (JumpTableSize == 0) { 834 // Factor in the number of conditional branches reduced from jump 835 // threading. Assume that lowering the switch block is implemented by 836 // using binary search, hence the LogBase2(). 837 unsigned CondBranches = 838 APInt(32, Switch->getNumSuccessors()).ceilLogBase2(); 839 DuplicationCost = Metrics.NumInsts / CondBranches; 840 } else { 841 // Compared with jump tables, the DFA optimizer removes an indirect branch 842 // on each loop iteration, thus making branch prediction more precise. The 843 // more branch targets there are, the more likely it is for the branch 844 // predictor to make a mistake, and the more benefit there is in the DFA 845 // optimizer. Thus, the more branch targets there are, the lower is the 846 // cost of the DFA opt. 847 DuplicationCost = Metrics.NumInsts / JumpTableSize; 848 } 849 850 LLVM_DEBUG(dbgs() << "\nDFA Jump Threading: Cost to jump thread block " 851 << SwitchPaths->getSwitchBlock()->getName() 852 << " is: " << DuplicationCost << "\n\n"); 853 854 if (DuplicationCost > CostThreshold) { 855 LLVM_DEBUG(dbgs() << "Not jump threading, duplication cost exceeds the " 856 << "cost threshold.\n"); 857 ORE->emit([&]() { 858 return OptimizationRemarkMissed(DEBUG_TYPE, "NotProfitable", Switch) 859 << "Duplication cost exceeds the cost threshold (cost=" 860 << ore::NV("Cost", DuplicationCost) 861 << ", threshold=" << ore::NV("Threshold", CostThreshold) << ")."; 862 }); 863 return false; 864 } 865 866 ORE->emit([&]() { 867 return OptimizationRemark(DEBUG_TYPE, "JumpThreaded", Switch) 868 << "Switch statement jump-threaded."; 869 }); 870 871 return true; 872 } 873 874 /// Transform each threading path to effectively jump thread the DFA. 875 void createAllExitPaths() { 876 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager); 877 878 // Move the switch block to the end of the path, since it will be duplicated 879 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock(); 880 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) { 881 LLVM_DEBUG(dbgs() << TPath << "\n"); 882 PathType NewPath(TPath.getPath()); 883 NewPath.push_back(SwitchBlock); 884 TPath.setPath(NewPath); 885 } 886 887 // Transform the ThreadingPaths and keep track of the cloned values 888 DuplicateBlockMap DuplicateMap; 889 DefMap NewDefs; 890 891 SmallSet<BasicBlock *, 16> BlocksToClean; 892 for (BasicBlock *BB : successors(SwitchBlock)) 893 BlocksToClean.insert(BB); 894 895 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) { 896 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, &DTU); 897 NumPaths++; 898 } 899 900 // After all paths are cloned, now update the last successor of the cloned 901 // path so it skips over the switch statement 902 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) 903 updateLastSuccessor(TPath, DuplicateMap, &DTU); 904 905 // For each instruction that was cloned and used outside, update its uses 906 updateSSA(NewDefs); 907 908 // Clean PHI Nodes for the newly created blocks 909 for (BasicBlock *BB : BlocksToClean) 910 cleanPhiNodes(BB); 911 } 912 913 /// For a specific ThreadingPath \p Path, create an exit path starting from 914 /// the determinator block. 915 /// 916 /// To remember the correct destination, we have to duplicate blocks 917 /// corresponding to each state. Also update the terminating instruction of 918 /// the predecessors, and phis in the successor blocks. 919 void createExitPath(DefMap &NewDefs, ThreadingPath &Path, 920 DuplicateBlockMap &DuplicateMap, 921 SmallSet<BasicBlock *, 16> &BlocksToClean, 922 DomTreeUpdater *DTU) { 923 uint64_t NextState = Path.getExitValue(); 924 const BasicBlock *Determinator = Path.getDeterminatorBB(); 925 PathType PathBBs = Path.getPath(); 926 927 // Don't select the placeholder block in front 928 if (PathBBs.front() == Determinator) 929 PathBBs.pop_front(); 930 931 auto DetIt = std::find(PathBBs.begin(), PathBBs.end(), Determinator); 932 auto Prev = std::prev(DetIt); 933 BasicBlock *PrevBB = *Prev; 934 for (auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) { 935 BasicBlock *BB = *BBIt; 936 BlocksToClean.insert(BB); 937 938 // We already cloned BB for this NextState, now just update the branch 939 // and continue. 940 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap); 941 if (NextBB) { 942 updatePredecessor(PrevBB, BB, NextBB, DTU); 943 PrevBB = NextBB; 944 continue; 945 } 946 947 // Clone the BB and update the successor of Prev to jump to the new block 948 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor( 949 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU); 950 DuplicateMap[BB].push_back({NewBB, NextState}); 951 BlocksToClean.insert(NewBB); 952 PrevBB = NewBB; 953 } 954 } 955 956 /// Restore SSA form after cloning blocks. 957 /// 958 /// Each cloned block creates new defs for a variable, and the uses need to be 959 /// updated to reflect this. The uses may be replaced with a cloned value, or 960 /// some derived phi instruction. Note that all uses of a value defined in the 961 /// same block were already remapped when cloning the block. 962 void updateSSA(DefMap &NewDefs) { 963 SSAUpdaterBulk SSAUpdate; 964 SmallVector<Use *, 16> UsesToRename; 965 966 for (auto KV : NewDefs) { 967 Instruction *I = KV.first; 968 BasicBlock *BB = I->getParent(); 969 std::vector<Instruction *> Cloned = KV.second; 970 971 // Scan all uses of this instruction to see if it is used outside of its 972 // block, and if so, record them in UsesToRename. 973 for (Use &U : I->uses()) { 974 Instruction *User = cast<Instruction>(U.getUser()); 975 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 976 if (UserPN->getIncomingBlock(U) == BB) 977 continue; 978 } else if (User->getParent() == BB) { 979 continue; 980 } 981 982 UsesToRename.push_back(&U); 983 } 984 985 // If there are no uses outside the block, we're done with this 986 // instruction. 987 if (UsesToRename.empty()) 988 continue; 989 LLVM_DEBUG(dbgs() << "DFA-JT: Renaming non-local uses of: " << *I 990 << "\n"); 991 992 // We found a use of I outside of BB. Rename all uses of I that are 993 // outside its block to be uses of the appropriate PHI node etc. See 994 // ValuesInBlocks with the values we know. 995 unsigned VarNum = SSAUpdate.AddVariable(I->getName(), I->getType()); 996 SSAUpdate.AddAvailableValue(VarNum, BB, I); 997 for (Instruction *New : Cloned) 998 SSAUpdate.AddAvailableValue(VarNum, New->getParent(), New); 999 1000 while (!UsesToRename.empty()) 1001 SSAUpdate.AddUse(VarNum, UsesToRename.pop_back_val()); 1002 1003 LLVM_DEBUG(dbgs() << "\n"); 1004 } 1005 // SSAUpdater handles phi placement and renaming uses with the appropriate 1006 // value. 1007 SSAUpdate.RewriteAllUses(DT); 1008 } 1009 1010 /// Clones a basic block, and adds it to the CFG. 1011 /// 1012 /// This function also includes updating phi nodes in the successors of the 1013 /// BB, and remapping uses that were defined locally in the cloned BB. 1014 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB, 1015 uint64_t NextState, 1016 DuplicateBlockMap &DuplicateMap, 1017 DefMap &NewDefs, 1018 DomTreeUpdater *DTU) { 1019 ValueToValueMapTy VMap; 1020 BasicBlock *NewBB = CloneBasicBlock( 1021 BB, VMap, ".jt" + std::to_string(NextState), BB->getParent()); 1022 NewBB->moveAfter(BB); 1023 NumCloned++; 1024 1025 for (Instruction &I : *NewBB) { 1026 // Do not remap operands of PHINode in case a definition in BB is an 1027 // incoming value to a phi in the same block. This incoming value will 1028 // be renamed later while restoring SSA. 1029 if (isa<PHINode>(&I)) 1030 continue; 1031 RemapInstruction(&I, VMap, 1032 RF_IgnoreMissingLocals | RF_NoModuleLevelChanges); 1033 if (AssumeInst *II = dyn_cast<AssumeInst>(&I)) 1034 AC->registerAssumption(II); 1035 } 1036 1037 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap); 1038 updatePredecessor(PrevBB, BB, NewBB, DTU); 1039 updateDefMap(NewDefs, VMap); 1040 1041 // Add all successors to the DominatorTree 1042 SmallPtrSet<BasicBlock *, 4> SuccSet; 1043 for (auto *SuccBB : successors(NewBB)) { 1044 if (SuccSet.insert(SuccBB).second) 1045 DTU->applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}}); 1046 } 1047 SuccSet.clear(); 1048 return NewBB; 1049 } 1050 1051 /// Update the phi nodes in BB's successors. 1052 /// 1053 /// This means creating a new incoming value from NewBB with the new 1054 /// instruction wherever there is an incoming value from BB. 1055 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB, 1056 uint64_t NextState, ValueToValueMapTy &VMap, 1057 DuplicateBlockMap &DuplicateMap) { 1058 std::vector<BasicBlock *> BlocksToUpdate; 1059 1060 // If BB is the last block in the path, we can simply update the one case 1061 // successor that will be reached. 1062 if (BB == SwitchPaths->getSwitchBlock()) { 1063 SwitchInst *Switch = SwitchPaths->getSwitchInst(); 1064 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState); 1065 BlocksToUpdate.push_back(NextCase); 1066 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap); 1067 if (ClonedSucc) 1068 BlocksToUpdate.push_back(ClonedSucc); 1069 } 1070 // Otherwise update phis in all successors. 1071 else { 1072 for (BasicBlock *Succ : successors(BB)) { 1073 BlocksToUpdate.push_back(Succ); 1074 1075 // Check if a successor has already been cloned for the particular exit 1076 // value. In this case if a successor was already cloned, the phi nodes 1077 // in the cloned block should be updated directly. 1078 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap); 1079 if (ClonedSucc) 1080 BlocksToUpdate.push_back(ClonedSucc); 1081 } 1082 } 1083 1084 // If there is a phi with an incoming value from BB, create a new incoming 1085 // value for the new predecessor ClonedBB. The value will either be the same 1086 // value from BB or a cloned value. 1087 for (BasicBlock *Succ : BlocksToUpdate) { 1088 for (auto II = Succ->begin(); PHINode *Phi = dyn_cast<PHINode>(II); 1089 ++II) { 1090 Value *Incoming = Phi->getIncomingValueForBlock(BB); 1091 if (Incoming) { 1092 if (isa<Constant>(Incoming)) { 1093 Phi->addIncoming(Incoming, ClonedBB); 1094 continue; 1095 } 1096 Value *ClonedVal = VMap[Incoming]; 1097 if (ClonedVal) 1098 Phi->addIncoming(ClonedVal, ClonedBB); 1099 else 1100 Phi->addIncoming(Incoming, ClonedBB); 1101 } 1102 } 1103 } 1104 } 1105 1106 /// Sets the successor of PrevBB to be NewBB instead of OldBB. Note that all 1107 /// other successors are kept as well. 1108 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB, 1109 BasicBlock *NewBB, DomTreeUpdater *DTU) { 1110 // When a path is reused, there is a chance that predecessors were already 1111 // updated before. Check if the predecessor needs to be updated first. 1112 if (!isPredecessor(OldBB, PrevBB)) 1113 return; 1114 1115 Instruction *PrevTerm = PrevBB->getTerminator(); 1116 for (unsigned Idx = 0; Idx < PrevTerm->getNumSuccessors(); Idx++) { 1117 if (PrevTerm->getSuccessor(Idx) == OldBB) { 1118 OldBB->removePredecessor(PrevBB, /* KeepOneInputPHIs = */ true); 1119 PrevTerm->setSuccessor(Idx, NewBB); 1120 } 1121 } 1122 DTU->applyUpdates({{DominatorTree::Delete, PrevBB, OldBB}, 1123 {DominatorTree::Insert, PrevBB, NewBB}}); 1124 } 1125 1126 /// Add new value mappings to the DefMap to keep track of all new definitions 1127 /// for a particular instruction. These will be used while updating SSA form. 1128 void updateDefMap(DefMap &NewDefs, ValueToValueMapTy &VMap) { 1129 SmallVector<std::pair<Instruction *, Instruction *>> NewDefsVector; 1130 NewDefsVector.reserve(VMap.size()); 1131 1132 for (auto Entry : VMap) { 1133 Instruction *Inst = 1134 dyn_cast<Instruction>(const_cast<Value *>(Entry.first)); 1135 if (!Inst || !Entry.second || isa<BranchInst>(Inst) || 1136 isa<SwitchInst>(Inst)) { 1137 continue; 1138 } 1139 1140 Instruction *Cloned = dyn_cast<Instruction>(Entry.second); 1141 if (!Cloned) 1142 continue; 1143 1144 NewDefsVector.push_back({Inst, Cloned}); 1145 } 1146 1147 // Sort the defs to get deterministic insertion order into NewDefs. 1148 sort(NewDefsVector, [](const auto &LHS, const auto &RHS) { 1149 if (LHS.first == RHS.first) 1150 return LHS.second->comesBefore(RHS.second); 1151 return LHS.first->comesBefore(RHS.first); 1152 }); 1153 1154 for (const auto &KV : NewDefsVector) 1155 NewDefs[KV.first].push_back(KV.second); 1156 } 1157 1158 /// Update the last branch of a particular cloned path to point to the correct 1159 /// case successor. 1160 /// 1161 /// Note that this is an optional step and would have been done in later 1162 /// optimizations, but it makes the CFG significantly easier to work with. 1163 void updateLastSuccessor(ThreadingPath &TPath, 1164 DuplicateBlockMap &DuplicateMap, 1165 DomTreeUpdater *DTU) { 1166 uint64_t NextState = TPath.getExitValue(); 1167 BasicBlock *BB = TPath.getPath().back(); 1168 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap); 1169 1170 // Note multiple paths can end at the same block so check that it is not 1171 // updated yet 1172 if (!isa<SwitchInst>(LastBlock->getTerminator())) 1173 return; 1174 SwitchInst *Switch = cast<SwitchInst>(LastBlock->getTerminator()); 1175 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState); 1176 1177 std::vector<DominatorTree::UpdateType> DTUpdates; 1178 SmallPtrSet<BasicBlock *, 4> SuccSet; 1179 for (BasicBlock *Succ : successors(LastBlock)) { 1180 if (Succ != NextCase && SuccSet.insert(Succ).second) 1181 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ}); 1182 } 1183 1184 Switch->eraseFromParent(); 1185 BranchInst::Create(NextCase, LastBlock); 1186 1187 DTU->applyUpdates(DTUpdates); 1188 } 1189 1190 /// After cloning blocks, some of the phi nodes have extra incoming values 1191 /// that are no longer used. This function removes them. 1192 void cleanPhiNodes(BasicBlock *BB) { 1193 // If BB is no longer reachable, remove any remaining phi nodes 1194 if (pred_empty(BB)) { 1195 std::vector<PHINode *> PhiToRemove; 1196 for (auto II = BB->begin(); PHINode *Phi = dyn_cast<PHINode>(II); ++II) { 1197 PhiToRemove.push_back(Phi); 1198 } 1199 for (PHINode *PN : PhiToRemove) { 1200 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 1201 PN->eraseFromParent(); 1202 } 1203 return; 1204 } 1205 1206 // Remove any incoming values that come from an invalid predecessor 1207 for (auto II = BB->begin(); PHINode *Phi = dyn_cast<PHINode>(II); ++II) { 1208 std::vector<BasicBlock *> BlocksToRemove; 1209 for (BasicBlock *IncomingBB : Phi->blocks()) { 1210 if (!isPredecessor(BB, IncomingBB)) 1211 BlocksToRemove.push_back(IncomingBB); 1212 } 1213 for (BasicBlock *BB : BlocksToRemove) 1214 Phi->removeIncomingValue(BB); 1215 } 1216 } 1217 1218 /// Checks if BB was already cloned for a particular next state value. If it 1219 /// was then it returns this cloned block, and otherwise null. 1220 BasicBlock *getClonedBB(BasicBlock *BB, uint64_t NextState, 1221 DuplicateBlockMap &DuplicateMap) { 1222 CloneList ClonedBBs = DuplicateMap[BB]; 1223 1224 // Find an entry in the CloneList with this NextState. If it exists then 1225 // return the corresponding BB 1226 auto It = llvm::find_if(ClonedBBs, [NextState](const ClonedBlock &C) { 1227 return C.State == NextState; 1228 }); 1229 return It != ClonedBBs.end() ? (*It).BB : nullptr; 1230 } 1231 1232 /// Helper to get the successor corresponding to a particular case value for 1233 /// a switch statement. 1234 BasicBlock *getNextCaseSuccessor(SwitchInst *Switch, uint64_t NextState) { 1235 BasicBlock *NextCase = nullptr; 1236 for (auto Case : Switch->cases()) { 1237 if (Case.getCaseValue()->getZExtValue() == NextState) { 1238 NextCase = Case.getCaseSuccessor(); 1239 break; 1240 } 1241 } 1242 if (!NextCase) 1243 NextCase = Switch->getDefaultDest(); 1244 return NextCase; 1245 } 1246 1247 /// Returns true if IncomingBB is a predecessor of BB. 1248 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) { 1249 return llvm::find(predecessors(BB), IncomingBB) != pred_end(BB); 1250 } 1251 1252 AllSwitchPaths *SwitchPaths; 1253 DominatorTree *DT; 1254 AssumptionCache *AC; 1255 TargetTransformInfo *TTI; 1256 OptimizationRemarkEmitter *ORE; 1257 SmallPtrSet<const Value *, 32> EphValues; 1258 std::vector<ThreadingPath> TPaths; 1259 }; 1260 1261 bool DFAJumpThreading::run(Function &F) { 1262 LLVM_DEBUG(dbgs() << "\nDFA Jump threading: " << F.getName() << "\n"); 1263 1264 if (F.hasOptSize()) { 1265 LLVM_DEBUG(dbgs() << "Skipping due to the 'minsize' attribute\n"); 1266 return false; 1267 } 1268 1269 if (ClViewCfgBefore) 1270 F.viewCFG(); 1271 1272 SmallVector<AllSwitchPaths, 2> ThreadableLoops; 1273 bool MadeChanges = false; 1274 1275 for (BasicBlock &BB : F) { 1276 auto *SI = dyn_cast<SwitchInst>(BB.getTerminator()); 1277 if (!SI) 1278 continue; 1279 1280 LLVM_DEBUG(dbgs() << "\nCheck if SwitchInst in BB " << BB.getName() 1281 << " is predictable\n"); 1282 MainSwitch Switch(SI, ORE); 1283 1284 if (!Switch.getInstr()) 1285 continue; 1286 1287 LLVM_DEBUG(dbgs() << "\nSwitchInst in BB " << BB.getName() << " is a " 1288 << "candidate for jump threading\n"); 1289 LLVM_DEBUG(SI->dump()); 1290 1291 unfoldSelectInstrs(DT, Switch.getSelectInsts()); 1292 if (!Switch.getSelectInsts().empty()) 1293 MadeChanges = true; 1294 1295 AllSwitchPaths SwitchPaths(&Switch, ORE); 1296 SwitchPaths.run(); 1297 1298 if (SwitchPaths.getNumThreadingPaths() > 0) { 1299 ThreadableLoops.push_back(SwitchPaths); 1300 1301 // For the time being limit this optimization to occurring once in a 1302 // function since it can change the CFG significantly. This is not a 1303 // strict requirement but it can cause buggy behavior if there is an 1304 // overlap of blocks in different opportunities. There is a lot of room to 1305 // experiment with catching more opportunities here. 1306 break; 1307 } 1308 } 1309 1310 SmallPtrSet<const Value *, 32> EphValues; 1311 if (ThreadableLoops.size() > 0) 1312 CodeMetrics::collectEphemeralValues(&F, AC, EphValues); 1313 1314 for (AllSwitchPaths SwitchPaths : ThreadableLoops) { 1315 TransformDFA Transform(&SwitchPaths, DT, AC, TTI, ORE, EphValues); 1316 Transform.run(); 1317 MadeChanges = true; 1318 } 1319 1320 #ifdef EXPENSIVE_CHECKS 1321 assert(DT->verify(DominatorTree::VerificationLevel::Full)); 1322 verifyFunction(F, &dbgs()); 1323 #endif 1324 1325 return MadeChanges; 1326 } 1327 1328 } // end anonymous namespace 1329 1330 /// Integrate with the new Pass Manager 1331 PreservedAnalyses DFAJumpThreadingPass::run(Function &F, 1332 FunctionAnalysisManager &AM) { 1333 AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F); 1334 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 1335 TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F); 1336 OptimizationRemarkEmitter ORE(&F); 1337 1338 if (!DFAJumpThreading(&AC, &DT, &TTI, &ORE).run(F)) 1339 return PreservedAnalyses::all(); 1340 1341 PreservedAnalyses PA; 1342 PA.preserve<DominatorTreeAnalysis>(); 1343 return PA; 1344 } 1345