1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===// 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 // This file implements the Jump Threading pass. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Transforms/Scalar/JumpThreading.h" 14 #include "llvm/ADT/DenseMap.h" 15 #include "llvm/ADT/DenseSet.h" 16 #include "llvm/ADT/MapVector.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AliasAnalysis.h" 23 #include "llvm/Analysis/BlockFrequencyInfo.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/CFG.h" 26 #include "llvm/Analysis/ConstantFolding.h" 27 #include "llvm/Analysis/DomTreeUpdater.h" 28 #include "llvm/Analysis/GlobalsModRef.h" 29 #include "llvm/Analysis/GuardUtils.h" 30 #include "llvm/Analysis/InstructionSimplify.h" 31 #include "llvm/Analysis/LazyValueInfo.h" 32 #include "llvm/Analysis/Loads.h" 33 #include "llvm/Analysis/LoopInfo.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/IR/BasicBlock.h" 37 #include "llvm/IR/CFG.h" 38 #include "llvm/IR/Constant.h" 39 #include "llvm/IR/ConstantRange.h" 40 #include "llvm/IR/Constants.h" 41 #include "llvm/IR/DataLayout.h" 42 #include "llvm/IR/Dominators.h" 43 #include "llvm/IR/Function.h" 44 #include "llvm/IR/InstrTypes.h" 45 #include "llvm/IR/Instruction.h" 46 #include "llvm/IR/Instructions.h" 47 #include "llvm/IR/IntrinsicInst.h" 48 #include "llvm/IR/Intrinsics.h" 49 #include "llvm/IR/LLVMContext.h" 50 #include "llvm/IR/MDBuilder.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/IR/PassManager.h" 54 #include "llvm/IR/PatternMatch.h" 55 #include "llvm/IR/Type.h" 56 #include "llvm/IR/Use.h" 57 #include "llvm/IR/User.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/InitializePasses.h" 60 #include "llvm/Pass.h" 61 #include "llvm/Support/BlockFrequency.h" 62 #include "llvm/Support/BranchProbability.h" 63 #include "llvm/Support/Casting.h" 64 #include "llvm/Support/CommandLine.h" 65 #include "llvm/Support/Debug.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Transforms/Scalar.h" 68 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 69 #include "llvm/Transforms/Utils/Cloning.h" 70 #include "llvm/Transforms/Utils/Local.h" 71 #include "llvm/Transforms/Utils/SSAUpdater.h" 72 #include "llvm/Transforms/Utils/ValueMapper.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstddef> 76 #include <cstdint> 77 #include <iterator> 78 #include <memory> 79 #include <utility> 80 81 using namespace llvm; 82 using namespace jumpthreading; 83 84 #define DEBUG_TYPE "jump-threading" 85 86 STATISTIC(NumThreads, "Number of jumps threaded"); 87 STATISTIC(NumFolds, "Number of terminators folded"); 88 STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi"); 89 90 static cl::opt<unsigned> 91 BBDuplicateThreshold("jump-threading-threshold", 92 cl::desc("Max block size to duplicate for jump threading"), 93 cl::init(6), cl::Hidden); 94 95 static cl::opt<unsigned> 96 ImplicationSearchThreshold( 97 "jump-threading-implication-search-threshold", 98 cl::desc("The number of predecessors to search for a stronger " 99 "condition to use to thread over a weaker condition"), 100 cl::init(3), cl::Hidden); 101 102 static cl::opt<bool> PrintLVIAfterJumpThreading( 103 "print-lvi-after-jump-threading", 104 cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false), 105 cl::Hidden); 106 107 static cl::opt<bool> JumpThreadingFreezeSelectCond( 108 "jump-threading-freeze-select-cond", 109 cl::desc("Freeze the condition when unfolding select"), cl::init(false), 110 cl::Hidden); 111 112 static cl::opt<bool> ThreadAcrossLoopHeaders( 113 "jump-threading-across-loop-headers", 114 cl::desc("Allow JumpThreading to thread across loop headers, for testing"), 115 cl::init(false), cl::Hidden); 116 117 118 namespace { 119 120 /// This pass performs 'jump threading', which looks at blocks that have 121 /// multiple predecessors and multiple successors. If one or more of the 122 /// predecessors of the block can be proven to always jump to one of the 123 /// successors, we forward the edge from the predecessor to the successor by 124 /// duplicating the contents of this block. 125 /// 126 /// An example of when this can occur is code like this: 127 /// 128 /// if () { ... 129 /// X = 4; 130 /// } 131 /// if (X < 3) { 132 /// 133 /// In this case, the unconditional branch at the end of the first if can be 134 /// revectored to the false side of the second if. 135 class JumpThreading : public FunctionPass { 136 JumpThreadingPass Impl; 137 138 public: 139 static char ID; // Pass identification 140 141 JumpThreading(bool InsertFreezeWhenUnfoldingSelect = false, int T = -1) 142 : FunctionPass(ID), Impl(InsertFreezeWhenUnfoldingSelect, T) { 143 initializeJumpThreadingPass(*PassRegistry::getPassRegistry()); 144 } 145 146 bool runOnFunction(Function &F) override; 147 148 void getAnalysisUsage(AnalysisUsage &AU) const override { 149 AU.addRequired<DominatorTreeWrapperPass>(); 150 AU.addPreserved<DominatorTreeWrapperPass>(); 151 AU.addRequired<AAResultsWrapperPass>(); 152 AU.addRequired<LazyValueInfoWrapperPass>(); 153 AU.addPreserved<LazyValueInfoWrapperPass>(); 154 AU.addPreserved<GlobalsAAWrapperPass>(); 155 AU.addRequired<TargetLibraryInfoWrapperPass>(); 156 } 157 158 void releaseMemory() override { Impl.releaseMemory(); } 159 }; 160 161 } // end anonymous namespace 162 163 char JumpThreading::ID = 0; 164 165 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading", 166 "Jump Threading", false, false) 167 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 168 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 169 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 170 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 171 INITIALIZE_PASS_END(JumpThreading, "jump-threading", 172 "Jump Threading", false, false) 173 174 // Public interface to the Jump Threading pass 175 FunctionPass *llvm::createJumpThreadingPass(bool InsertFr, int Threshold) { 176 return new JumpThreading(InsertFr, Threshold); 177 } 178 179 JumpThreadingPass::JumpThreadingPass(bool InsertFr, int T) { 180 InsertFreezeWhenUnfoldingSelect = JumpThreadingFreezeSelectCond | InsertFr; 181 DefaultBBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T); 182 } 183 184 // Update branch probability information according to conditional 185 // branch probability. This is usually made possible for cloned branches 186 // in inline instances by the context specific profile in the caller. 187 // For instance, 188 // 189 // [Block PredBB] 190 // [Branch PredBr] 191 // if (t) { 192 // Block A; 193 // } else { 194 // Block B; 195 // } 196 // 197 // [Block BB] 198 // cond = PN([true, %A], [..., %B]); // PHI node 199 // [Branch CondBr] 200 // if (cond) { 201 // ... // P(cond == true) = 1% 202 // } 203 // 204 // Here we know that when block A is taken, cond must be true, which means 205 // P(cond == true | A) = 1 206 // 207 // Given that P(cond == true) = P(cond == true | A) * P(A) + 208 // P(cond == true | B) * P(B) 209 // we get: 210 // P(cond == true ) = P(A) + P(cond == true | B) * P(B) 211 // 212 // which gives us: 213 // P(A) is less than P(cond == true), i.e. 214 // P(t == true) <= P(cond == true) 215 // 216 // In other words, if we know P(cond == true) is unlikely, we know 217 // that P(t == true) is also unlikely. 218 // 219 static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) { 220 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 221 if (!CondBr) 222 return; 223 224 uint64_t TrueWeight, FalseWeight; 225 if (!CondBr->extractProfMetadata(TrueWeight, FalseWeight)) 226 return; 227 228 if (TrueWeight + FalseWeight == 0) 229 // Zero branch_weights do not give a hint for getting branch probabilities. 230 // Technically it would result in division by zero denominator, which is 231 // TrueWeight + FalseWeight. 232 return; 233 234 // Returns the outgoing edge of the dominating predecessor block 235 // that leads to the PhiNode's incoming block: 236 auto GetPredOutEdge = 237 [](BasicBlock *IncomingBB, 238 BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> { 239 auto *PredBB = IncomingBB; 240 auto *SuccBB = PhiBB; 241 SmallPtrSet<BasicBlock *, 16> Visited; 242 while (true) { 243 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()); 244 if (PredBr && PredBr->isConditional()) 245 return {PredBB, SuccBB}; 246 Visited.insert(PredBB); 247 auto *SinglePredBB = PredBB->getSinglePredecessor(); 248 if (!SinglePredBB) 249 return {nullptr, nullptr}; 250 251 // Stop searching when SinglePredBB has been visited. It means we see 252 // an unreachable loop. 253 if (Visited.count(SinglePredBB)) 254 return {nullptr, nullptr}; 255 256 SuccBB = PredBB; 257 PredBB = SinglePredBB; 258 } 259 }; 260 261 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 262 Value *PhiOpnd = PN->getIncomingValue(i); 263 ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd); 264 265 if (!CI || !CI->getType()->isIntegerTy(1)) 266 continue; 267 268 BranchProbability BP = 269 (CI->isOne() ? BranchProbability::getBranchProbability( 270 TrueWeight, TrueWeight + FalseWeight) 271 : BranchProbability::getBranchProbability( 272 FalseWeight, TrueWeight + FalseWeight)); 273 274 auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB); 275 if (!PredOutEdge.first) 276 return; 277 278 BasicBlock *PredBB = PredOutEdge.first; 279 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()); 280 if (!PredBr) 281 return; 282 283 uint64_t PredTrueWeight, PredFalseWeight; 284 // FIXME: We currently only set the profile data when it is missing. 285 // With PGO, this can be used to refine even existing profile data with 286 // context information. This needs to be done after more performance 287 // testing. 288 if (PredBr->extractProfMetadata(PredTrueWeight, PredFalseWeight)) 289 continue; 290 291 // We can not infer anything useful when BP >= 50%, because BP is the 292 // upper bound probability value. 293 if (BP >= BranchProbability(50, 100)) 294 continue; 295 296 SmallVector<uint32_t, 2> Weights; 297 if (PredBr->getSuccessor(0) == PredOutEdge.second) { 298 Weights.push_back(BP.getNumerator()); 299 Weights.push_back(BP.getCompl().getNumerator()); 300 } else { 301 Weights.push_back(BP.getCompl().getNumerator()); 302 Weights.push_back(BP.getNumerator()); 303 } 304 PredBr->setMetadata(LLVMContext::MD_prof, 305 MDBuilder(PredBr->getParent()->getContext()) 306 .createBranchWeights(Weights)); 307 } 308 } 309 310 /// runOnFunction - Toplevel algorithm. 311 bool JumpThreading::runOnFunction(Function &F) { 312 if (skipFunction(F)) 313 return false; 314 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 315 auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 316 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI(); 317 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 318 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy); 319 std::unique_ptr<BlockFrequencyInfo> BFI; 320 std::unique_ptr<BranchProbabilityInfo> BPI; 321 if (F.hasProfileData()) { 322 LoopInfo LI{DominatorTree(F)}; 323 BPI.reset(new BranchProbabilityInfo(F, LI, TLI)); 324 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); 325 } 326 327 bool Changed = Impl.runImpl(F, TLI, LVI, AA, &DTU, F.hasProfileData(), 328 std::move(BFI), std::move(BPI)); 329 if (PrintLVIAfterJumpThreading) { 330 dbgs() << "LVI for function '" << F.getName() << "':\n"; 331 LVI->printLVI(F, DTU.getDomTree(), dbgs()); 332 } 333 return Changed; 334 } 335 336 PreservedAnalyses JumpThreadingPass::run(Function &F, 337 FunctionAnalysisManager &AM) { 338 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 339 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 340 auto &LVI = AM.getResult<LazyValueAnalysis>(F); 341 auto &AA = AM.getResult<AAManager>(F); 342 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 343 344 std::unique_ptr<BlockFrequencyInfo> BFI; 345 std::unique_ptr<BranchProbabilityInfo> BPI; 346 if (F.hasProfileData()) { 347 LoopInfo LI{DominatorTree(F)}; 348 BPI.reset(new BranchProbabilityInfo(F, LI, &TLI)); 349 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); 350 } 351 352 bool Changed = runImpl(F, &TLI, &LVI, &AA, &DTU, F.hasProfileData(), 353 std::move(BFI), std::move(BPI)); 354 355 if (!Changed) 356 return PreservedAnalyses::all(); 357 PreservedAnalyses PA; 358 PA.preserve<GlobalsAA>(); 359 PA.preserve<DominatorTreeAnalysis>(); 360 PA.preserve<LazyValueAnalysis>(); 361 return PA; 362 } 363 364 bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_, 365 LazyValueInfo *LVI_, AliasAnalysis *AA_, 366 DomTreeUpdater *DTU_, bool HasProfileData_, 367 std::unique_ptr<BlockFrequencyInfo> BFI_, 368 std::unique_ptr<BranchProbabilityInfo> BPI_) { 369 LLVM_DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n"); 370 TLI = TLI_; 371 LVI = LVI_; 372 AA = AA_; 373 DTU = DTU_; 374 BFI.reset(); 375 BPI.reset(); 376 // When profile data is available, we need to update edge weights after 377 // successful jump threading, which requires both BPI and BFI being available. 378 HasProfileData = HasProfileData_; 379 auto *GuardDecl = F.getParent()->getFunction( 380 Intrinsic::getName(Intrinsic::experimental_guard)); 381 HasGuards = GuardDecl && !GuardDecl->use_empty(); 382 if (HasProfileData) { 383 BPI = std::move(BPI_); 384 BFI = std::move(BFI_); 385 } 386 387 // Reduce the number of instructions duplicated when optimizing strictly for 388 // size. 389 if (BBDuplicateThreshold.getNumOccurrences()) 390 BBDupThreshold = BBDuplicateThreshold; 391 else if (F.hasFnAttribute(Attribute::MinSize)) 392 BBDupThreshold = 3; 393 else 394 BBDupThreshold = DefaultBBDupThreshold; 395 396 // JumpThreading must not processes blocks unreachable from entry. It's a 397 // waste of compute time and can potentially lead to hangs. 398 SmallPtrSet<BasicBlock *, 16> Unreachable; 399 assert(DTU && "DTU isn't passed into JumpThreading before using it."); 400 assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed."); 401 DominatorTree &DT = DTU->getDomTree(); 402 for (auto &BB : F) 403 if (!DT.isReachableFromEntry(&BB)) 404 Unreachable.insert(&BB); 405 406 if (!ThreadAcrossLoopHeaders) 407 findLoopHeaders(F); 408 409 bool EverChanged = false; 410 bool Changed; 411 do { 412 Changed = false; 413 for (auto &BB : F) { 414 if (Unreachable.count(&BB)) 415 continue; 416 while (processBlock(&BB)) // Thread all of the branches we can over BB. 417 Changed = true; 418 419 // Jump threading may have introduced redundant debug values into BB 420 // which should be removed. 421 if (Changed) 422 RemoveRedundantDbgInstrs(&BB); 423 424 // Stop processing BB if it's the entry or is now deleted. The following 425 // routines attempt to eliminate BB and locating a suitable replacement 426 // for the entry is non-trivial. 427 if (&BB == &F.getEntryBlock() || DTU->isBBPendingDeletion(&BB)) 428 continue; 429 430 if (pred_empty(&BB)) { 431 // When processBlock makes BB unreachable it doesn't bother to fix up 432 // the instructions in it. We must remove BB to prevent invalid IR. 433 LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName() 434 << "' with terminator: " << *BB.getTerminator() 435 << '\n'); 436 LoopHeaders.erase(&BB); 437 LVI->eraseBlock(&BB); 438 DeleteDeadBlock(&BB, DTU); 439 Changed = true; 440 continue; 441 } 442 443 // processBlock doesn't thread BBs with unconditional TIs. However, if BB 444 // is "almost empty", we attempt to merge BB with its sole successor. 445 auto *BI = dyn_cast<BranchInst>(BB.getTerminator()); 446 if (BI && BI->isUnconditional()) { 447 BasicBlock *Succ = BI->getSuccessor(0); 448 if ( 449 // The terminator must be the only non-phi instruction in BB. 450 BB.getFirstNonPHIOrDbg()->isTerminator() && 451 // Don't alter Loop headers and latches to ensure another pass can 452 // detect and transform nested loops later. 453 !LoopHeaders.count(&BB) && !LoopHeaders.count(Succ) && 454 TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU)) { 455 RemoveRedundantDbgInstrs(Succ); 456 // BB is valid for cleanup here because we passed in DTU. F remains 457 // BB's parent until a DTU->getDomTree() event. 458 LVI->eraseBlock(&BB); 459 Changed = true; 460 } 461 } 462 } 463 EverChanged |= Changed; 464 } while (Changed); 465 466 LoopHeaders.clear(); 467 return EverChanged; 468 } 469 470 // Replace uses of Cond with ToVal when safe to do so. If all uses are 471 // replaced, we can remove Cond. We cannot blindly replace all uses of Cond 472 // because we may incorrectly replace uses when guards/assumes are uses of 473 // of `Cond` and we used the guards/assume to reason about the `Cond` value 474 // at the end of block. RAUW unconditionally replaces all uses 475 // including the guards/assumes themselves and the uses before the 476 // guard/assume. 477 static void replaceFoldableUses(Instruction *Cond, Value *ToVal) { 478 assert(Cond->getType() == ToVal->getType()); 479 auto *BB = Cond->getParent(); 480 // We can unconditionally replace all uses in non-local blocks (i.e. uses 481 // strictly dominated by BB), since LVI information is true from the 482 // terminator of BB. 483 replaceNonLocalUsesWith(Cond, ToVal); 484 for (Instruction &I : reverse(*BB)) { 485 // Reached the Cond whose uses we are trying to replace, so there are no 486 // more uses. 487 if (&I == Cond) 488 break; 489 // We only replace uses in instructions that are guaranteed to reach the end 490 // of BB, where we know Cond is ToVal. 491 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 492 break; 493 I.replaceUsesOfWith(Cond, ToVal); 494 } 495 if (Cond->use_empty() && !Cond->mayHaveSideEffects()) 496 Cond->eraseFromParent(); 497 } 498 499 /// Return the cost of duplicating a piece of this block from first non-phi 500 /// and before StopAt instruction to thread across it. Stop scanning the block 501 /// when exceeding the threshold. If duplication is impossible, returns ~0U. 502 static unsigned getJumpThreadDuplicationCost(BasicBlock *BB, 503 Instruction *StopAt, 504 unsigned Threshold) { 505 assert(StopAt->getParent() == BB && "Not an instruction from proper BB?"); 506 /// Ignore PHI nodes, these will be flattened when duplication happens. 507 BasicBlock::const_iterator I(BB->getFirstNonPHI()); 508 509 // FIXME: THREADING will delete values that are just used to compute the 510 // branch, so they shouldn't count against the duplication cost. 511 512 unsigned Bonus = 0; 513 if (BB->getTerminator() == StopAt) { 514 // Threading through a switch statement is particularly profitable. If this 515 // block ends in a switch, decrease its cost to make it more likely to 516 // happen. 517 if (isa<SwitchInst>(StopAt)) 518 Bonus = 6; 519 520 // The same holds for indirect branches, but slightly more so. 521 if (isa<IndirectBrInst>(StopAt)) 522 Bonus = 8; 523 } 524 525 // Bump the threshold up so the early exit from the loop doesn't skip the 526 // terminator-based Size adjustment at the end. 527 Threshold += Bonus; 528 529 // Sum up the cost of each instruction until we get to the terminator. Don't 530 // include the terminator because the copy won't include it. 531 unsigned Size = 0; 532 for (; &*I != StopAt; ++I) { 533 534 // Stop scanning the block if we've reached the threshold. 535 if (Size > Threshold) 536 return Size; 537 538 // Debugger intrinsics don't incur code size. 539 if (isa<DbgInfoIntrinsic>(I)) continue; 540 541 // If this is a pointer->pointer bitcast, it is free. 542 if (isa<BitCastInst>(I) && I->getType()->isPointerTy()) 543 continue; 544 545 // Freeze instruction is free, too. 546 if (isa<FreezeInst>(I)) 547 continue; 548 549 // Bail out if this instruction gives back a token type, it is not possible 550 // to duplicate it if it is used outside this BB. 551 if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB)) 552 return ~0U; 553 554 // All other instructions count for at least one unit. 555 ++Size; 556 557 // Calls are more expensive. If they are non-intrinsic calls, we model them 558 // as having cost of 4. If they are a non-vector intrinsic, we model them 559 // as having cost of 2 total, and if they are a vector intrinsic, we model 560 // them as having cost 1. 561 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 562 if (CI->cannotDuplicate() || CI->isConvergent()) 563 // Blocks with NoDuplicate are modelled as having infinite cost, so they 564 // are never duplicated. 565 return ~0U; 566 else if (!isa<IntrinsicInst>(CI)) 567 Size += 3; 568 else if (!CI->getType()->isVectorTy()) 569 Size += 1; 570 } 571 } 572 573 return Size > Bonus ? Size - Bonus : 0; 574 } 575 576 /// findLoopHeaders - We do not want jump threading to turn proper loop 577 /// structures into irreducible loops. Doing this breaks up the loop nesting 578 /// hierarchy and pessimizes later transformations. To prevent this from 579 /// happening, we first have to find the loop headers. Here we approximate this 580 /// by finding targets of backedges in the CFG. 581 /// 582 /// Note that there definitely are cases when we want to allow threading of 583 /// edges across a loop header. For example, threading a jump from outside the 584 /// loop (the preheader) to an exit block of the loop is definitely profitable. 585 /// It is also almost always profitable to thread backedges from within the loop 586 /// to exit blocks, and is often profitable to thread backedges to other blocks 587 /// within the loop (forming a nested loop). This simple analysis is not rich 588 /// enough to track all of these properties and keep it up-to-date as the CFG 589 /// mutates, so we don't allow any of these transformations. 590 void JumpThreadingPass::findLoopHeaders(Function &F) { 591 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges; 592 FindFunctionBackedges(F, Edges); 593 594 for (const auto &Edge : Edges) 595 LoopHeaders.insert(Edge.second); 596 } 597 598 /// getKnownConstant - Helper method to determine if we can thread over a 599 /// terminator with the given value as its condition, and if so what value to 600 /// use for that. What kind of value this is depends on whether we want an 601 /// integer or a block address, but an undef is always accepted. 602 /// Returns null if Val is null or not an appropriate constant. 603 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) { 604 if (!Val) 605 return nullptr; 606 607 // Undef is "known" enough. 608 if (UndefValue *U = dyn_cast<UndefValue>(Val)) 609 return U; 610 611 if (Preference == WantBlockAddress) 612 return dyn_cast<BlockAddress>(Val->stripPointerCasts()); 613 614 return dyn_cast<ConstantInt>(Val); 615 } 616 617 /// computeValueKnownInPredecessors - Given a basic block BB and a value V, see 618 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef 619 /// in any of our predecessors. If so, return the known list of value and pred 620 /// BB in the result vector. 621 /// 622 /// This returns true if there were any known values. 623 bool JumpThreadingPass::computeValueKnownInPredecessorsImpl( 624 Value *V, BasicBlock *BB, PredValueInfo &Result, 625 ConstantPreference Preference, DenseSet<Value *> &RecursionSet, 626 Instruction *CxtI) { 627 // This method walks up use-def chains recursively. Because of this, we could 628 // get into an infinite loop going around loops in the use-def chain. To 629 // prevent this, keep track of what (value, block) pairs we've already visited 630 // and terminate the search if we loop back to them 631 if (!RecursionSet.insert(V).second) 632 return false; 633 634 // If V is a constant, then it is known in all predecessors. 635 if (Constant *KC = getKnownConstant(V, Preference)) { 636 for (BasicBlock *Pred : predecessors(BB)) 637 Result.emplace_back(KC, Pred); 638 639 return !Result.empty(); 640 } 641 642 // If V is a non-instruction value, or an instruction in a different block, 643 // then it can't be derived from a PHI. 644 Instruction *I = dyn_cast<Instruction>(V); 645 if (!I || I->getParent() != BB) { 646 647 // Okay, if this is a live-in value, see if it has a known value at the end 648 // of any of our predecessors. 649 // 650 // FIXME: This should be an edge property, not a block end property. 651 /// TODO: Per PR2563, we could infer value range information about a 652 /// predecessor based on its terminator. 653 // 654 // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if 655 // "I" is a non-local compare-with-a-constant instruction. This would be 656 // able to handle value inequalities better, for example if the compare is 657 // "X < 4" and "X < 3" is known true but "X < 4" itself is not available. 658 // Perhaps getConstantOnEdge should be smart enough to do this? 659 for (BasicBlock *P : predecessors(BB)) { 660 // If the value is known by LazyValueInfo to be a constant in a 661 // predecessor, use that information to try to thread this block. 662 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI); 663 if (Constant *KC = getKnownConstant(PredCst, Preference)) 664 Result.emplace_back(KC, P); 665 } 666 667 return !Result.empty(); 668 } 669 670 /// If I is a PHI node, then we know the incoming values for any constants. 671 if (PHINode *PN = dyn_cast<PHINode>(I)) { 672 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 673 Value *InVal = PN->getIncomingValue(i); 674 if (Constant *KC = getKnownConstant(InVal, Preference)) { 675 Result.emplace_back(KC, PN->getIncomingBlock(i)); 676 } else { 677 Constant *CI = LVI->getConstantOnEdge(InVal, 678 PN->getIncomingBlock(i), 679 BB, CxtI); 680 if (Constant *KC = getKnownConstant(CI, Preference)) 681 Result.emplace_back(KC, PN->getIncomingBlock(i)); 682 } 683 } 684 685 return !Result.empty(); 686 } 687 688 // Handle Cast instructions. 689 if (CastInst *CI = dyn_cast<CastInst>(I)) { 690 Value *Source = CI->getOperand(0); 691 computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference, 692 RecursionSet, CxtI); 693 if (Result.empty()) 694 return false; 695 696 // Convert the known values. 697 for (auto &R : Result) 698 R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType()); 699 700 return true; 701 } 702 703 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) { 704 Value *Source = FI->getOperand(0); 705 computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference, 706 RecursionSet, CxtI); 707 708 erase_if(Result, [](auto &Pair) { 709 return !isGuaranteedNotToBeUndefOrPoison(Pair.first); 710 }); 711 712 return !Result.empty(); 713 } 714 715 // Handle some boolean conditions. 716 if (I->getType()->getPrimitiveSizeInBits() == 1) { 717 assert(Preference == WantInteger && "One-bit non-integer type?"); 718 // X | true -> true 719 // X & false -> false 720 if (I->getOpcode() == Instruction::Or || 721 I->getOpcode() == Instruction::And) { 722 PredValueInfoTy LHSVals, RHSVals; 723 724 computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals, 725 WantInteger, RecursionSet, CxtI); 726 computeValueKnownInPredecessorsImpl(I->getOperand(1), BB, RHSVals, 727 WantInteger, RecursionSet, CxtI); 728 729 if (LHSVals.empty() && RHSVals.empty()) 730 return false; 731 732 ConstantInt *InterestingVal; 733 if (I->getOpcode() == Instruction::Or) 734 InterestingVal = ConstantInt::getTrue(I->getContext()); 735 else 736 InterestingVal = ConstantInt::getFalse(I->getContext()); 737 738 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs; 739 740 // Scan for the sentinel. If we find an undef, force it to the 741 // interesting value: x|undef -> true and x&undef -> false. 742 for (const auto &LHSVal : LHSVals) 743 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) { 744 Result.emplace_back(InterestingVal, LHSVal.second); 745 LHSKnownBBs.insert(LHSVal.second); 746 } 747 for (const auto &RHSVal : RHSVals) 748 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) { 749 // If we already inferred a value for this block on the LHS, don't 750 // re-add it. 751 if (!LHSKnownBBs.count(RHSVal.second)) 752 Result.emplace_back(InterestingVal, RHSVal.second); 753 } 754 755 return !Result.empty(); 756 } 757 758 // Handle the NOT form of XOR. 759 if (I->getOpcode() == Instruction::Xor && 760 isa<ConstantInt>(I->getOperand(1)) && 761 cast<ConstantInt>(I->getOperand(1))->isOne()) { 762 computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result, 763 WantInteger, RecursionSet, CxtI); 764 if (Result.empty()) 765 return false; 766 767 // Invert the known values. 768 for (auto &R : Result) 769 R.first = ConstantExpr::getNot(R.first); 770 771 return true; 772 } 773 774 // Try to simplify some other binary operator values. 775 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 776 assert(Preference != WantBlockAddress 777 && "A binary operator creating a block address?"); 778 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) { 779 PredValueInfoTy LHSVals; 780 computeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals, 781 WantInteger, RecursionSet, CxtI); 782 783 // Try to use constant folding to simplify the binary operator. 784 for (const auto &LHSVal : LHSVals) { 785 Constant *V = LHSVal.first; 786 Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI); 787 788 if (Constant *KC = getKnownConstant(Folded, WantInteger)) 789 Result.emplace_back(KC, LHSVal.second); 790 } 791 } 792 793 return !Result.empty(); 794 } 795 796 // Handle compare with phi operand, where the PHI is defined in this block. 797 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 798 assert(Preference == WantInteger && "Compares only produce integers"); 799 Type *CmpType = Cmp->getType(); 800 Value *CmpLHS = Cmp->getOperand(0); 801 Value *CmpRHS = Cmp->getOperand(1); 802 CmpInst::Predicate Pred = Cmp->getPredicate(); 803 804 PHINode *PN = dyn_cast<PHINode>(CmpLHS); 805 if (!PN) 806 PN = dyn_cast<PHINode>(CmpRHS); 807 if (PN && PN->getParent() == BB) { 808 const DataLayout &DL = PN->getModule()->getDataLayout(); 809 // We can do this simplification if any comparisons fold to true or false. 810 // See if any do. 811 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 812 BasicBlock *PredBB = PN->getIncomingBlock(i); 813 Value *LHS, *RHS; 814 if (PN == CmpLHS) { 815 LHS = PN->getIncomingValue(i); 816 RHS = CmpRHS->DoPHITranslation(BB, PredBB); 817 } else { 818 LHS = CmpLHS->DoPHITranslation(BB, PredBB); 819 RHS = PN->getIncomingValue(i); 820 } 821 Value *Res = SimplifyCmpInst(Pred, LHS, RHS, {DL}); 822 if (!Res) { 823 if (!isa<Constant>(RHS)) 824 continue; 825 826 // getPredicateOnEdge call will make no sense if LHS is defined in BB. 827 auto LHSInst = dyn_cast<Instruction>(LHS); 828 if (LHSInst && LHSInst->getParent() == BB) 829 continue; 830 831 LazyValueInfo::Tristate 832 ResT = LVI->getPredicateOnEdge(Pred, LHS, 833 cast<Constant>(RHS), PredBB, BB, 834 CxtI ? CxtI : Cmp); 835 if (ResT == LazyValueInfo::Unknown) 836 continue; 837 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT); 838 } 839 840 if (Constant *KC = getKnownConstant(Res, WantInteger)) 841 Result.emplace_back(KC, PredBB); 842 } 843 844 return !Result.empty(); 845 } 846 847 // If comparing a live-in value against a constant, see if we know the 848 // live-in value on any predecessors. 849 if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) { 850 Constant *CmpConst = cast<Constant>(CmpRHS); 851 852 if (!isa<Instruction>(CmpLHS) || 853 cast<Instruction>(CmpLHS)->getParent() != BB) { 854 for (BasicBlock *P : predecessors(BB)) { 855 // If the value is known by LazyValueInfo to be a constant in a 856 // predecessor, use that information to try to thread this block. 857 LazyValueInfo::Tristate Res = 858 LVI->getPredicateOnEdge(Pred, CmpLHS, 859 CmpConst, P, BB, CxtI ? CxtI : Cmp); 860 if (Res == LazyValueInfo::Unknown) 861 continue; 862 863 Constant *ResC = ConstantInt::get(CmpType, Res); 864 Result.emplace_back(ResC, P); 865 } 866 867 return !Result.empty(); 868 } 869 870 // InstCombine can fold some forms of constant range checks into 871 // (icmp (add (x, C1)), C2). See if we have we have such a thing with 872 // x as a live-in. 873 { 874 using namespace PatternMatch; 875 876 Value *AddLHS; 877 ConstantInt *AddConst; 878 if (isa<ConstantInt>(CmpConst) && 879 match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) { 880 if (!isa<Instruction>(AddLHS) || 881 cast<Instruction>(AddLHS)->getParent() != BB) { 882 for (BasicBlock *P : predecessors(BB)) { 883 // If the value is known by LazyValueInfo to be a ConstantRange in 884 // a predecessor, use that information to try to thread this 885 // block. 886 ConstantRange CR = LVI->getConstantRangeOnEdge( 887 AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS)); 888 // Propagate the range through the addition. 889 CR = CR.add(AddConst->getValue()); 890 891 // Get the range where the compare returns true. 892 ConstantRange CmpRange = ConstantRange::makeExactICmpRegion( 893 Pred, cast<ConstantInt>(CmpConst)->getValue()); 894 895 Constant *ResC; 896 if (CmpRange.contains(CR)) 897 ResC = ConstantInt::getTrue(CmpType); 898 else if (CmpRange.inverse().contains(CR)) 899 ResC = ConstantInt::getFalse(CmpType); 900 else 901 continue; 902 903 Result.emplace_back(ResC, P); 904 } 905 906 return !Result.empty(); 907 } 908 } 909 } 910 911 // Try to find a constant value for the LHS of a comparison, 912 // and evaluate it statically if we can. 913 PredValueInfoTy LHSVals; 914 computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals, 915 WantInteger, RecursionSet, CxtI); 916 917 for (const auto &LHSVal : LHSVals) { 918 Constant *V = LHSVal.first; 919 Constant *Folded = ConstantExpr::getCompare(Pred, V, CmpConst); 920 if (Constant *KC = getKnownConstant(Folded, WantInteger)) 921 Result.emplace_back(KC, LHSVal.second); 922 } 923 924 return !Result.empty(); 925 } 926 } 927 928 if (SelectInst *SI = dyn_cast<SelectInst>(I)) { 929 // Handle select instructions where at least one operand is a known constant 930 // and we can figure out the condition value for any predecessor block. 931 Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference); 932 Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference); 933 PredValueInfoTy Conds; 934 if ((TrueVal || FalseVal) && 935 computeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds, 936 WantInteger, RecursionSet, CxtI)) { 937 for (auto &C : Conds) { 938 Constant *Cond = C.first; 939 940 // Figure out what value to use for the condition. 941 bool KnownCond; 942 if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) { 943 // A known boolean. 944 KnownCond = CI->isOne(); 945 } else { 946 assert(isa<UndefValue>(Cond) && "Unexpected condition value"); 947 // Either operand will do, so be sure to pick the one that's a known 948 // constant. 949 // FIXME: Do this more cleverly if both values are known constants? 950 KnownCond = (TrueVal != nullptr); 951 } 952 953 // See if the select has a known constant value for this predecessor. 954 if (Constant *Val = KnownCond ? TrueVal : FalseVal) 955 Result.emplace_back(Val, C.second); 956 } 957 958 return !Result.empty(); 959 } 960 } 961 962 // If all else fails, see if LVI can figure out a constant value for us. 963 assert(CxtI->getParent() == BB && "CxtI should be in BB"); 964 Constant *CI = LVI->getConstant(V, CxtI); 965 if (Constant *KC = getKnownConstant(CI, Preference)) { 966 for (BasicBlock *Pred : predecessors(BB)) 967 Result.emplace_back(KC, Pred); 968 } 969 970 return !Result.empty(); 971 } 972 973 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends 974 /// in an undefined jump, decide which block is best to revector to. 975 /// 976 /// Since we can pick an arbitrary destination, we pick the successor with the 977 /// fewest predecessors. This should reduce the in-degree of the others. 978 static unsigned getBestDestForJumpOnUndef(BasicBlock *BB) { 979 Instruction *BBTerm = BB->getTerminator(); 980 unsigned MinSucc = 0; 981 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc); 982 // Compute the successor with the minimum number of predecessors. 983 unsigned MinNumPreds = pred_size(TestBB); 984 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) { 985 TestBB = BBTerm->getSuccessor(i); 986 unsigned NumPreds = pred_size(TestBB); 987 if (NumPreds < MinNumPreds) { 988 MinSucc = i; 989 MinNumPreds = NumPreds; 990 } 991 } 992 993 return MinSucc; 994 } 995 996 static bool hasAddressTakenAndUsed(BasicBlock *BB) { 997 if (!BB->hasAddressTaken()) return false; 998 999 // If the block has its address taken, it may be a tree of dead constants 1000 // hanging off of it. These shouldn't keep the block alive. 1001 BlockAddress *BA = BlockAddress::get(BB); 1002 BA->removeDeadConstantUsers(); 1003 return !BA->use_empty(); 1004 } 1005 1006 /// processBlock - If there are any predecessors whose control can be threaded 1007 /// through to a successor, transform them now. 1008 bool JumpThreadingPass::processBlock(BasicBlock *BB) { 1009 // If the block is trivially dead, just return and let the caller nuke it. 1010 // This simplifies other transformations. 1011 if (DTU->isBBPendingDeletion(BB) || 1012 (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock())) 1013 return false; 1014 1015 // If this block has a single predecessor, and if that pred has a single 1016 // successor, merge the blocks. This encourages recursive jump threading 1017 // because now the condition in this block can be threaded through 1018 // predecessors of our predecessor block. 1019 if (maybeMergeBasicBlockIntoOnlyPred(BB)) 1020 return true; 1021 1022 if (tryToUnfoldSelectInCurrBB(BB)) 1023 return true; 1024 1025 // Look if we can propagate guards to predecessors. 1026 if (HasGuards && processGuards(BB)) 1027 return true; 1028 1029 // What kind of constant we're looking for. 1030 ConstantPreference Preference = WantInteger; 1031 1032 // Look to see if the terminator is a conditional branch, switch or indirect 1033 // branch, if not we can't thread it. 1034 Value *Condition; 1035 Instruction *Terminator = BB->getTerminator(); 1036 if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) { 1037 // Can't thread an unconditional jump. 1038 if (BI->isUnconditional()) return false; 1039 Condition = BI->getCondition(); 1040 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) { 1041 Condition = SI->getCondition(); 1042 } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) { 1043 // Can't thread indirect branch with no successors. 1044 if (IB->getNumSuccessors() == 0) return false; 1045 Condition = IB->getAddress()->stripPointerCasts(); 1046 Preference = WantBlockAddress; 1047 } else { 1048 return false; // Must be an invoke or callbr. 1049 } 1050 1051 // Keep track if we constant folded the condition in this invocation. 1052 bool ConstantFolded = false; 1053 1054 // Run constant folding to see if we can reduce the condition to a simple 1055 // constant. 1056 if (Instruction *I = dyn_cast<Instruction>(Condition)) { 1057 Value *SimpleVal = 1058 ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI); 1059 if (SimpleVal) { 1060 I->replaceAllUsesWith(SimpleVal); 1061 if (isInstructionTriviallyDead(I, TLI)) 1062 I->eraseFromParent(); 1063 Condition = SimpleVal; 1064 ConstantFolded = true; 1065 } 1066 } 1067 1068 // If the terminator is branching on an undef or freeze undef, we can pick any 1069 // of the successors to branch to. Let getBestDestForJumpOnUndef decide. 1070 auto *FI = dyn_cast<FreezeInst>(Condition); 1071 if (isa<UndefValue>(Condition) || 1072 (FI && isa<UndefValue>(FI->getOperand(0)) && FI->hasOneUse())) { 1073 unsigned BestSucc = getBestDestForJumpOnUndef(BB); 1074 std::vector<DominatorTree::UpdateType> Updates; 1075 1076 // Fold the branch/switch. 1077 Instruction *BBTerm = BB->getTerminator(); 1078 Updates.reserve(BBTerm->getNumSuccessors()); 1079 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) { 1080 if (i == BestSucc) continue; 1081 BasicBlock *Succ = BBTerm->getSuccessor(i); 1082 Succ->removePredecessor(BB, true); 1083 Updates.push_back({DominatorTree::Delete, BB, Succ}); 1084 } 1085 1086 LLVM_DEBUG(dbgs() << " In block '" << BB->getName() 1087 << "' folding undef terminator: " << *BBTerm << '\n'); 1088 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm); 1089 BBTerm->eraseFromParent(); 1090 DTU->applyUpdatesPermissive(Updates); 1091 if (FI) 1092 FI->eraseFromParent(); 1093 return true; 1094 } 1095 1096 // If the terminator of this block is branching on a constant, simplify the 1097 // terminator to an unconditional branch. This can occur due to threading in 1098 // other blocks. 1099 if (getKnownConstant(Condition, Preference)) { 1100 LLVM_DEBUG(dbgs() << " In block '" << BB->getName() 1101 << "' folding terminator: " << *BB->getTerminator() 1102 << '\n'); 1103 ++NumFolds; 1104 ConstantFoldTerminator(BB, true, nullptr, DTU); 1105 return true; 1106 } 1107 1108 Instruction *CondInst = dyn_cast<Instruction>(Condition); 1109 1110 // All the rest of our checks depend on the condition being an instruction. 1111 if (!CondInst) { 1112 // FIXME: Unify this with code below. 1113 if (processThreadableEdges(Condition, BB, Preference, Terminator)) 1114 return true; 1115 return ConstantFolded; 1116 } 1117 1118 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) { 1119 // If we're branching on a conditional, LVI might be able to determine 1120 // it's value at the branch instruction. We only handle comparisons 1121 // against a constant at this time. 1122 // TODO: This should be extended to handle switches as well. 1123 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 1124 Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1)); 1125 if (CondBr && CondConst) { 1126 // We should have returned as soon as we turn a conditional branch to 1127 // unconditional. Because its no longer interesting as far as jump 1128 // threading is concerned. 1129 assert(CondBr->isConditional() && "Threading on unconditional terminator"); 1130 1131 LazyValueInfo::Tristate Ret = 1132 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0), 1133 CondConst, CondBr); 1134 if (Ret != LazyValueInfo::Unknown) { 1135 unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0; 1136 unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1; 1137 BasicBlock *ToRemoveSucc = CondBr->getSuccessor(ToRemove); 1138 ToRemoveSucc->removePredecessor(BB, true); 1139 BranchInst *UncondBr = 1140 BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr); 1141 UncondBr->setDebugLoc(CondBr->getDebugLoc()); 1142 CondBr->eraseFromParent(); 1143 if (CondCmp->use_empty()) 1144 CondCmp->eraseFromParent(); 1145 // We can safely replace *some* uses of the CondInst if it has 1146 // exactly one value as returned by LVI. RAUW is incorrect in the 1147 // presence of guards and assumes, that have the `Cond` as the use. This 1148 // is because we use the guards/assume to reason about the `Cond` value 1149 // at the end of block, but RAUW unconditionally replaces all uses 1150 // including the guards/assumes themselves and the uses before the 1151 // guard/assume. 1152 else if (CondCmp->getParent() == BB) { 1153 auto *CI = Ret == LazyValueInfo::True ? 1154 ConstantInt::getTrue(CondCmp->getType()) : 1155 ConstantInt::getFalse(CondCmp->getType()); 1156 replaceFoldableUses(CondCmp, CI); 1157 } 1158 DTU->applyUpdatesPermissive( 1159 {{DominatorTree::Delete, BB, ToRemoveSucc}}); 1160 return true; 1161 } 1162 1163 // We did not manage to simplify this branch, try to see whether 1164 // CondCmp depends on a known phi-select pattern. 1165 if (tryToUnfoldSelect(CondCmp, BB)) 1166 return true; 1167 } 1168 } 1169 1170 if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) 1171 if (tryToUnfoldSelect(SI, BB)) 1172 return true; 1173 1174 // Check for some cases that are worth simplifying. Right now we want to look 1175 // for loads that are used by a switch or by the condition for the branch. If 1176 // we see one, check to see if it's partially redundant. If so, insert a PHI 1177 // which can then be used to thread the values. 1178 Value *SimplifyValue = CondInst; 1179 1180 if (auto *FI = dyn_cast<FreezeInst>(SimplifyValue)) 1181 // Look into freeze's operand 1182 SimplifyValue = FI->getOperand(0); 1183 1184 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue)) 1185 if (isa<Constant>(CondCmp->getOperand(1))) 1186 SimplifyValue = CondCmp->getOperand(0); 1187 1188 // TODO: There are other places where load PRE would be profitable, such as 1189 // more complex comparisons. 1190 if (LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue)) 1191 if (simplifyPartiallyRedundantLoad(LoadI)) 1192 return true; 1193 1194 // Before threading, try to propagate profile data backwards: 1195 if (PHINode *PN = dyn_cast<PHINode>(CondInst)) 1196 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 1197 updatePredecessorProfileMetadata(PN, BB); 1198 1199 // Handle a variety of cases where we are branching on something derived from 1200 // a PHI node in the current block. If we can prove that any predecessors 1201 // compute a predictable value based on a PHI node, thread those predecessors. 1202 if (processThreadableEdges(CondInst, BB, Preference, Terminator)) 1203 return true; 1204 1205 // If this is an otherwise-unfoldable branch on a phi node or freeze(phi) in 1206 // the current block, see if we can simplify. 1207 PHINode *PN = dyn_cast<PHINode>( 1208 isa<FreezeInst>(CondInst) ? cast<FreezeInst>(CondInst)->getOperand(0) 1209 : CondInst); 1210 1211 if (PN && PN->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 1212 return processBranchOnPHI(PN); 1213 1214 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify. 1215 if (CondInst->getOpcode() == Instruction::Xor && 1216 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 1217 return processBranchOnXOR(cast<BinaryOperator>(CondInst)); 1218 1219 // Search for a stronger dominating condition that can be used to simplify a 1220 // conditional branch leaving BB. 1221 if (processImpliedCondition(BB)) 1222 return true; 1223 1224 return false; 1225 } 1226 1227 bool JumpThreadingPass::processImpliedCondition(BasicBlock *BB) { 1228 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 1229 if (!BI || !BI->isConditional()) 1230 return false; 1231 1232 Value *Cond = BI->getCondition(); 1233 BasicBlock *CurrentBB = BB; 1234 BasicBlock *CurrentPred = BB->getSinglePredecessor(); 1235 unsigned Iter = 0; 1236 1237 auto &DL = BB->getModule()->getDataLayout(); 1238 1239 while (CurrentPred && Iter++ < ImplicationSearchThreshold) { 1240 auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator()); 1241 if (!PBI || !PBI->isConditional()) 1242 return false; 1243 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB) 1244 return false; 1245 1246 bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB; 1247 Optional<bool> Implication = 1248 isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue); 1249 if (Implication) { 1250 BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1); 1251 BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0); 1252 RemoveSucc->removePredecessor(BB); 1253 BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI); 1254 UncondBI->setDebugLoc(BI->getDebugLoc()); 1255 BI->eraseFromParent(); 1256 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}}); 1257 return true; 1258 } 1259 CurrentBB = CurrentPred; 1260 CurrentPred = CurrentBB->getSinglePredecessor(); 1261 } 1262 1263 return false; 1264 } 1265 1266 /// Return true if Op is an instruction defined in the given block. 1267 static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) { 1268 if (Instruction *OpInst = dyn_cast<Instruction>(Op)) 1269 if (OpInst->getParent() == BB) 1270 return true; 1271 return false; 1272 } 1273 1274 /// simplifyPartiallyRedundantLoad - If LoadI is an obviously partially 1275 /// redundant load instruction, eliminate it by replacing it with a PHI node. 1276 /// This is an important optimization that encourages jump threading, and needs 1277 /// to be run interlaced with other jump threading tasks. 1278 bool JumpThreadingPass::simplifyPartiallyRedundantLoad(LoadInst *LoadI) { 1279 // Don't hack volatile and ordered loads. 1280 if (!LoadI->isUnordered()) return false; 1281 1282 // If the load is defined in a block with exactly one predecessor, it can't be 1283 // partially redundant. 1284 BasicBlock *LoadBB = LoadI->getParent(); 1285 if (LoadBB->getSinglePredecessor()) 1286 return false; 1287 1288 // If the load is defined in an EH pad, it can't be partially redundant, 1289 // because the edges between the invoke and the EH pad cannot have other 1290 // instructions between them. 1291 if (LoadBB->isEHPad()) 1292 return false; 1293 1294 Value *LoadedPtr = LoadI->getOperand(0); 1295 1296 // If the loaded operand is defined in the LoadBB and its not a phi, 1297 // it can't be available in predecessors. 1298 if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr)) 1299 return false; 1300 1301 // Scan a few instructions up from the load, to see if it is obviously live at 1302 // the entry to its block. 1303 BasicBlock::iterator BBIt(LoadI); 1304 bool IsLoadCSE; 1305 if (Value *AvailableVal = FindAvailableLoadedValue( 1306 LoadI, LoadBB, BBIt, DefMaxInstsToScan, AA, &IsLoadCSE)) { 1307 // If the value of the load is locally available within the block, just use 1308 // it. This frequently occurs for reg2mem'd allocas. 1309 1310 if (IsLoadCSE) { 1311 LoadInst *NLoadI = cast<LoadInst>(AvailableVal); 1312 combineMetadataForCSE(NLoadI, LoadI, false); 1313 }; 1314 1315 // If the returned value is the load itself, replace with an undef. This can 1316 // only happen in dead loops. 1317 if (AvailableVal == LoadI) 1318 AvailableVal = UndefValue::get(LoadI->getType()); 1319 if (AvailableVal->getType() != LoadI->getType()) 1320 AvailableVal = CastInst::CreateBitOrPointerCast( 1321 AvailableVal, LoadI->getType(), "", LoadI); 1322 LoadI->replaceAllUsesWith(AvailableVal); 1323 LoadI->eraseFromParent(); 1324 return true; 1325 } 1326 1327 // Otherwise, if we scanned the whole block and got to the top of the block, 1328 // we know the block is locally transparent to the load. If not, something 1329 // might clobber its value. 1330 if (BBIt != LoadBB->begin()) 1331 return false; 1332 1333 // If all of the loads and stores that feed the value have the same AA tags, 1334 // then we can propagate them onto any newly inserted loads. 1335 AAMDNodes AATags; 1336 LoadI->getAAMetadata(AATags); 1337 1338 SmallPtrSet<BasicBlock*, 8> PredsScanned; 1339 1340 using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>; 1341 1342 AvailablePredsTy AvailablePreds; 1343 BasicBlock *OneUnavailablePred = nullptr; 1344 SmallVector<LoadInst*, 8> CSELoads; 1345 1346 // If we got here, the loaded value is transparent through to the start of the 1347 // block. Check to see if it is available in any of the predecessor blocks. 1348 for (BasicBlock *PredBB : predecessors(LoadBB)) { 1349 // If we already scanned this predecessor, skip it. 1350 if (!PredsScanned.insert(PredBB).second) 1351 continue; 1352 1353 BBIt = PredBB->end(); 1354 unsigned NumScanedInst = 0; 1355 Value *PredAvailable = nullptr; 1356 // NOTE: We don't CSE load that is volatile or anything stronger than 1357 // unordered, that should have been checked when we entered the function. 1358 assert(LoadI->isUnordered() && 1359 "Attempting to CSE volatile or atomic loads"); 1360 // If this is a load on a phi pointer, phi-translate it and search 1361 // for available load/store to the pointer in predecessors. 1362 Value *Ptr = LoadedPtr->DoPHITranslation(LoadBB, PredBB); 1363 PredAvailable = FindAvailablePtrLoadStore( 1364 Ptr, LoadI->getType(), LoadI->isAtomic(), PredBB, BBIt, 1365 DefMaxInstsToScan, AA, &IsLoadCSE, &NumScanedInst); 1366 1367 // If PredBB has a single predecessor, continue scanning through the 1368 // single predecessor. 1369 BasicBlock *SinglePredBB = PredBB; 1370 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() && 1371 NumScanedInst < DefMaxInstsToScan) { 1372 SinglePredBB = SinglePredBB->getSinglePredecessor(); 1373 if (SinglePredBB) { 1374 BBIt = SinglePredBB->end(); 1375 PredAvailable = FindAvailablePtrLoadStore( 1376 Ptr, LoadI->getType(), LoadI->isAtomic(), SinglePredBB, BBIt, 1377 (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE, 1378 &NumScanedInst); 1379 } 1380 } 1381 1382 if (!PredAvailable) { 1383 OneUnavailablePred = PredBB; 1384 continue; 1385 } 1386 1387 if (IsLoadCSE) 1388 CSELoads.push_back(cast<LoadInst>(PredAvailable)); 1389 1390 // If so, this load is partially redundant. Remember this info so that we 1391 // can create a PHI node. 1392 AvailablePreds.emplace_back(PredBB, PredAvailable); 1393 } 1394 1395 // If the loaded value isn't available in any predecessor, it isn't partially 1396 // redundant. 1397 if (AvailablePreds.empty()) return false; 1398 1399 // Okay, the loaded value is available in at least one (and maybe all!) 1400 // predecessors. If the value is unavailable in more than one unique 1401 // predecessor, we want to insert a merge block for those common predecessors. 1402 // This ensures that we only have to insert one reload, thus not increasing 1403 // code size. 1404 BasicBlock *UnavailablePred = nullptr; 1405 1406 // If the value is unavailable in one of predecessors, we will end up 1407 // inserting a new instruction into them. It is only valid if all the 1408 // instructions before LoadI are guaranteed to pass execution to its 1409 // successor, or if LoadI is safe to speculate. 1410 // TODO: If this logic becomes more complex, and we will perform PRE insertion 1411 // farther than to a predecessor, we need to reuse the code from GVN's PRE. 1412 // It requires domination tree analysis, so for this simple case it is an 1413 // overkill. 1414 if (PredsScanned.size() != AvailablePreds.size() && 1415 !isSafeToSpeculativelyExecute(LoadI)) 1416 for (auto I = LoadBB->begin(); &*I != LoadI; ++I) 1417 if (!isGuaranteedToTransferExecutionToSuccessor(&*I)) 1418 return false; 1419 1420 // If there is exactly one predecessor where the value is unavailable, the 1421 // already computed 'OneUnavailablePred' block is it. If it ends in an 1422 // unconditional branch, we know that it isn't a critical edge. 1423 if (PredsScanned.size() == AvailablePreds.size()+1 && 1424 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) { 1425 UnavailablePred = OneUnavailablePred; 1426 } else if (PredsScanned.size() != AvailablePreds.size()) { 1427 // Otherwise, we had multiple unavailable predecessors or we had a critical 1428 // edge from the one. 1429 SmallVector<BasicBlock*, 8> PredsToSplit; 1430 SmallPtrSet<BasicBlock*, 8> AvailablePredSet; 1431 1432 for (const auto &AvailablePred : AvailablePreds) 1433 AvailablePredSet.insert(AvailablePred.first); 1434 1435 // Add all the unavailable predecessors to the PredsToSplit list. 1436 for (BasicBlock *P : predecessors(LoadBB)) { 1437 // If the predecessor is an indirect goto, we can't split the edge. 1438 // Same for CallBr. 1439 if (isa<IndirectBrInst>(P->getTerminator()) || 1440 isa<CallBrInst>(P->getTerminator())) 1441 return false; 1442 1443 if (!AvailablePredSet.count(P)) 1444 PredsToSplit.push_back(P); 1445 } 1446 1447 // Split them out to their own block. 1448 UnavailablePred = splitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split"); 1449 } 1450 1451 // If the value isn't available in all predecessors, then there will be 1452 // exactly one where it isn't available. Insert a load on that edge and add 1453 // it to the AvailablePreds list. 1454 if (UnavailablePred) { 1455 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 && 1456 "Can't handle critical edge here!"); 1457 LoadInst *NewVal = new LoadInst( 1458 LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred), 1459 LoadI->getName() + ".pr", false, LoadI->getAlign(), 1460 LoadI->getOrdering(), LoadI->getSyncScopeID(), 1461 UnavailablePred->getTerminator()); 1462 NewVal->setDebugLoc(LoadI->getDebugLoc()); 1463 if (AATags) 1464 NewVal->setAAMetadata(AATags); 1465 1466 AvailablePreds.emplace_back(UnavailablePred, NewVal); 1467 } 1468 1469 // Now we know that each predecessor of this block has a value in 1470 // AvailablePreds, sort them for efficient access as we're walking the preds. 1471 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end()); 1472 1473 // Create a PHI node at the start of the block for the PRE'd load value. 1474 pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB); 1475 PHINode *PN = PHINode::Create(LoadI->getType(), std::distance(PB, PE), "", 1476 &LoadBB->front()); 1477 PN->takeName(LoadI); 1478 PN->setDebugLoc(LoadI->getDebugLoc()); 1479 1480 // Insert new entries into the PHI for each predecessor. A single block may 1481 // have multiple entries here. 1482 for (pred_iterator PI = PB; PI != PE; ++PI) { 1483 BasicBlock *P = *PI; 1484 AvailablePredsTy::iterator I = 1485 llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr)); 1486 1487 assert(I != AvailablePreds.end() && I->first == P && 1488 "Didn't find entry for predecessor!"); 1489 1490 // If we have an available predecessor but it requires casting, insert the 1491 // cast in the predecessor and use the cast. Note that we have to update the 1492 // AvailablePreds vector as we go so that all of the PHI entries for this 1493 // predecessor use the same bitcast. 1494 Value *&PredV = I->second; 1495 if (PredV->getType() != LoadI->getType()) 1496 PredV = CastInst::CreateBitOrPointerCast(PredV, LoadI->getType(), "", 1497 P->getTerminator()); 1498 1499 PN->addIncoming(PredV, I->first); 1500 } 1501 1502 for (LoadInst *PredLoadI : CSELoads) { 1503 combineMetadataForCSE(PredLoadI, LoadI, true); 1504 } 1505 1506 LoadI->replaceAllUsesWith(PN); 1507 LoadI->eraseFromParent(); 1508 1509 return true; 1510 } 1511 1512 /// findMostPopularDest - The specified list contains multiple possible 1513 /// threadable destinations. Pick the one that occurs the most frequently in 1514 /// the list. 1515 static BasicBlock * 1516 findMostPopularDest(BasicBlock *BB, 1517 const SmallVectorImpl<std::pair<BasicBlock *, 1518 BasicBlock *>> &PredToDestList) { 1519 assert(!PredToDestList.empty()); 1520 1521 // Determine popularity. If there are multiple possible destinations, we 1522 // explicitly choose to ignore 'undef' destinations. We prefer to thread 1523 // blocks with known and real destinations to threading undef. We'll handle 1524 // them later if interesting. 1525 MapVector<BasicBlock *, unsigned> DestPopularity; 1526 1527 // Populate DestPopularity with the successors in the order they appear in the 1528 // successor list. This way, we ensure determinism by iterating it in the 1529 // same order in std::max_element below. We map nullptr to 0 so that we can 1530 // return nullptr when PredToDestList contains nullptr only. 1531 DestPopularity[nullptr] = 0; 1532 for (auto *SuccBB : successors(BB)) 1533 DestPopularity[SuccBB] = 0; 1534 1535 for (const auto &PredToDest : PredToDestList) 1536 if (PredToDest.second) 1537 DestPopularity[PredToDest.second]++; 1538 1539 // Find the most popular dest. 1540 using VT = decltype(DestPopularity)::value_type; 1541 auto MostPopular = std::max_element( 1542 DestPopularity.begin(), DestPopularity.end(), 1543 [](const VT &L, const VT &R) { return L.second < R.second; }); 1544 1545 // Okay, we have finally picked the most popular destination. 1546 return MostPopular->first; 1547 } 1548 1549 // Try to evaluate the value of V when the control flows from PredPredBB to 1550 // BB->getSinglePredecessor() and then on to BB. 1551 Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB, 1552 BasicBlock *PredPredBB, 1553 Value *V) { 1554 BasicBlock *PredBB = BB->getSinglePredecessor(); 1555 assert(PredBB && "Expected a single predecessor"); 1556 1557 if (Constant *Cst = dyn_cast<Constant>(V)) { 1558 return Cst; 1559 } 1560 1561 // Consult LVI if V is not an instruction in BB or PredBB. 1562 Instruction *I = dyn_cast<Instruction>(V); 1563 if (!I || (I->getParent() != BB && I->getParent() != PredBB)) { 1564 return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr); 1565 } 1566 1567 // Look into a PHI argument. 1568 if (PHINode *PHI = dyn_cast<PHINode>(V)) { 1569 if (PHI->getParent() == PredBB) 1570 return dyn_cast<Constant>(PHI->getIncomingValueForBlock(PredPredBB)); 1571 return nullptr; 1572 } 1573 1574 // If we have a CmpInst, try to fold it for each incoming edge into PredBB. 1575 if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) { 1576 if (CondCmp->getParent() == BB) { 1577 Constant *Op0 = 1578 evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0)); 1579 Constant *Op1 = 1580 evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1)); 1581 if (Op0 && Op1) { 1582 return ConstantExpr::getCompare(CondCmp->getPredicate(), Op0, Op1); 1583 } 1584 } 1585 return nullptr; 1586 } 1587 1588 return nullptr; 1589 } 1590 1591 bool JumpThreadingPass::processThreadableEdges(Value *Cond, BasicBlock *BB, 1592 ConstantPreference Preference, 1593 Instruction *CxtI) { 1594 // If threading this would thread across a loop header, don't even try to 1595 // thread the edge. 1596 if (LoopHeaders.count(BB)) 1597 return false; 1598 1599 PredValueInfoTy PredValues; 1600 if (!computeValueKnownInPredecessors(Cond, BB, PredValues, Preference, 1601 CxtI)) { 1602 // We don't have known values in predecessors. See if we can thread through 1603 // BB and its sole predecessor. 1604 return maybethreadThroughTwoBasicBlocks(BB, Cond); 1605 } 1606 1607 assert(!PredValues.empty() && 1608 "computeValueKnownInPredecessors returned true with no values"); 1609 1610 LLVM_DEBUG(dbgs() << "IN BB: " << *BB; 1611 for (const auto &PredValue : PredValues) { 1612 dbgs() << " BB '" << BB->getName() 1613 << "': FOUND condition = " << *PredValue.first 1614 << " for pred '" << PredValue.second->getName() << "'.\n"; 1615 }); 1616 1617 // Decide what we want to thread through. Convert our list of known values to 1618 // a list of known destinations for each pred. This also discards duplicate 1619 // predecessors and keeps track of the undefined inputs (which are represented 1620 // as a null dest in the PredToDestList). 1621 SmallPtrSet<BasicBlock*, 16> SeenPreds; 1622 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList; 1623 1624 BasicBlock *OnlyDest = nullptr; 1625 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL; 1626 Constant *OnlyVal = nullptr; 1627 Constant *MultipleVal = (Constant *)(intptr_t)~0ULL; 1628 1629 for (const auto &PredValue : PredValues) { 1630 BasicBlock *Pred = PredValue.second; 1631 if (!SeenPreds.insert(Pred).second) 1632 continue; // Duplicate predecessor entry. 1633 1634 Constant *Val = PredValue.first; 1635 1636 BasicBlock *DestBB; 1637 if (isa<UndefValue>(Val)) 1638 DestBB = nullptr; 1639 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 1640 assert(isa<ConstantInt>(Val) && "Expecting a constant integer"); 1641 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero()); 1642 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 1643 assert(isa<ConstantInt>(Val) && "Expecting a constant integer"); 1644 DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor(); 1645 } else { 1646 assert(isa<IndirectBrInst>(BB->getTerminator()) 1647 && "Unexpected terminator"); 1648 assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress"); 1649 DestBB = cast<BlockAddress>(Val)->getBasicBlock(); 1650 } 1651 1652 // If we have exactly one destination, remember it for efficiency below. 1653 if (PredToDestList.empty()) { 1654 OnlyDest = DestBB; 1655 OnlyVal = Val; 1656 } else { 1657 if (OnlyDest != DestBB) 1658 OnlyDest = MultipleDestSentinel; 1659 // It possible we have same destination, but different value, e.g. default 1660 // case in switchinst. 1661 if (Val != OnlyVal) 1662 OnlyVal = MultipleVal; 1663 } 1664 1665 // If the predecessor ends with an indirect goto, we can't change its 1666 // destination. Same for CallBr. 1667 if (isa<IndirectBrInst>(Pred->getTerminator()) || 1668 isa<CallBrInst>(Pred->getTerminator())) 1669 continue; 1670 1671 PredToDestList.emplace_back(Pred, DestBB); 1672 } 1673 1674 // If all edges were unthreadable, we fail. 1675 if (PredToDestList.empty()) 1676 return false; 1677 1678 // If all the predecessors go to a single known successor, we want to fold, 1679 // not thread. By doing so, we do not need to duplicate the current block and 1680 // also miss potential opportunities in case we dont/cant duplicate. 1681 if (OnlyDest && OnlyDest != MultipleDestSentinel) { 1682 if (BB->hasNPredecessors(PredToDestList.size())) { 1683 bool SeenFirstBranchToOnlyDest = false; 1684 std::vector <DominatorTree::UpdateType> Updates; 1685 Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1); 1686 for (BasicBlock *SuccBB : successors(BB)) { 1687 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) { 1688 SeenFirstBranchToOnlyDest = true; // Don't modify the first branch. 1689 } else { 1690 SuccBB->removePredecessor(BB, true); // This is unreachable successor. 1691 Updates.push_back({DominatorTree::Delete, BB, SuccBB}); 1692 } 1693 } 1694 1695 // Finally update the terminator. 1696 Instruction *Term = BB->getTerminator(); 1697 BranchInst::Create(OnlyDest, Term); 1698 Term->eraseFromParent(); 1699 DTU->applyUpdatesPermissive(Updates); 1700 if (HasProfileData) 1701 BPI->eraseBlock(BB); 1702 1703 // If the condition is now dead due to the removal of the old terminator, 1704 // erase it. 1705 if (auto *CondInst = dyn_cast<Instruction>(Cond)) { 1706 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects()) 1707 CondInst->eraseFromParent(); 1708 // We can safely replace *some* uses of the CondInst if it has 1709 // exactly one value as returned by LVI. RAUW is incorrect in the 1710 // presence of guards and assumes, that have the `Cond` as the use. This 1711 // is because we use the guards/assume to reason about the `Cond` value 1712 // at the end of block, but RAUW unconditionally replaces all uses 1713 // including the guards/assumes themselves and the uses before the 1714 // guard/assume. 1715 else if (OnlyVal && OnlyVal != MultipleVal && 1716 CondInst->getParent() == BB) 1717 replaceFoldableUses(CondInst, OnlyVal); 1718 } 1719 return true; 1720 } 1721 } 1722 1723 // Determine which is the most common successor. If we have many inputs and 1724 // this block is a switch, we want to start by threading the batch that goes 1725 // to the most popular destination first. If we only know about one 1726 // threadable destination (the common case) we can avoid this. 1727 BasicBlock *MostPopularDest = OnlyDest; 1728 1729 if (MostPopularDest == MultipleDestSentinel) { 1730 // Remove any loop headers from the Dest list, threadEdge conservatively 1731 // won't process them, but we might have other destination that are eligible 1732 // and we still want to process. 1733 erase_if(PredToDestList, 1734 [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) { 1735 return LoopHeaders.count(PredToDest.second) != 0; 1736 }); 1737 1738 if (PredToDestList.empty()) 1739 return false; 1740 1741 MostPopularDest = findMostPopularDest(BB, PredToDestList); 1742 } 1743 1744 // Now that we know what the most popular destination is, factor all 1745 // predecessors that will jump to it into a single predecessor. 1746 SmallVector<BasicBlock*, 16> PredsToFactor; 1747 for (const auto &PredToDest : PredToDestList) 1748 if (PredToDest.second == MostPopularDest) { 1749 BasicBlock *Pred = PredToDest.first; 1750 1751 // This predecessor may be a switch or something else that has multiple 1752 // edges to the block. Factor each of these edges by listing them 1753 // according to # occurrences in PredsToFactor. 1754 for (BasicBlock *Succ : successors(Pred)) 1755 if (Succ == BB) 1756 PredsToFactor.push_back(Pred); 1757 } 1758 1759 // If the threadable edges are branching on an undefined value, we get to pick 1760 // the destination that these predecessors should get to. 1761 if (!MostPopularDest) 1762 MostPopularDest = BB->getTerminator()-> 1763 getSuccessor(getBestDestForJumpOnUndef(BB)); 1764 1765 // Ok, try to thread it! 1766 return tryThreadEdge(BB, PredsToFactor, MostPopularDest); 1767 } 1768 1769 /// processBranchOnPHI - We have an otherwise unthreadable conditional branch on 1770 /// a PHI node (or freeze PHI) in the current block. See if there are any 1771 /// simplifications we can do based on inputs to the phi node. 1772 bool JumpThreadingPass::processBranchOnPHI(PHINode *PN) { 1773 BasicBlock *BB = PN->getParent(); 1774 1775 // TODO: We could make use of this to do it once for blocks with common PHI 1776 // values. 1777 SmallVector<BasicBlock*, 1> PredBBs; 1778 PredBBs.resize(1); 1779 1780 // If any of the predecessor blocks end in an unconditional branch, we can 1781 // *duplicate* the conditional branch into that block in order to further 1782 // encourage jump threading and to eliminate cases where we have branch on a 1783 // phi of an icmp (branch on icmp is much better). 1784 // This is still beneficial when a frozen phi is used as the branch condition 1785 // because it allows CodeGenPrepare to further canonicalize br(freeze(icmp)) 1786 // to br(icmp(freeze ...)). 1787 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1788 BasicBlock *PredBB = PN->getIncomingBlock(i); 1789 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator())) 1790 if (PredBr->isUnconditional()) { 1791 PredBBs[0] = PredBB; 1792 // Try to duplicate BB into PredBB. 1793 if (duplicateCondBranchOnPHIIntoPred(BB, PredBBs)) 1794 return true; 1795 } 1796 } 1797 1798 return false; 1799 } 1800 1801 /// processBranchOnXOR - We have an otherwise unthreadable conditional branch on 1802 /// a xor instruction in the current block. See if there are any 1803 /// simplifications we can do based on inputs to the xor. 1804 bool JumpThreadingPass::processBranchOnXOR(BinaryOperator *BO) { 1805 BasicBlock *BB = BO->getParent(); 1806 1807 // If either the LHS or RHS of the xor is a constant, don't do this 1808 // optimization. 1809 if (isa<ConstantInt>(BO->getOperand(0)) || 1810 isa<ConstantInt>(BO->getOperand(1))) 1811 return false; 1812 1813 // If the first instruction in BB isn't a phi, we won't be able to infer 1814 // anything special about any particular predecessor. 1815 if (!isa<PHINode>(BB->front())) 1816 return false; 1817 1818 // If this BB is a landing pad, we won't be able to split the edge into it. 1819 if (BB->isEHPad()) 1820 return false; 1821 1822 // If we have a xor as the branch input to this block, and we know that the 1823 // LHS or RHS of the xor in any predecessor is true/false, then we can clone 1824 // the condition into the predecessor and fix that value to true, saving some 1825 // logical ops on that path and encouraging other paths to simplify. 1826 // 1827 // This copies something like this: 1828 // 1829 // BB: 1830 // %X = phi i1 [1], [%X'] 1831 // %Y = icmp eq i32 %A, %B 1832 // %Z = xor i1 %X, %Y 1833 // br i1 %Z, ... 1834 // 1835 // Into: 1836 // BB': 1837 // %Y = icmp ne i32 %A, %B 1838 // br i1 %Y, ... 1839 1840 PredValueInfoTy XorOpValues; 1841 bool isLHS = true; 1842 if (!computeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues, 1843 WantInteger, BO)) { 1844 assert(XorOpValues.empty()); 1845 if (!computeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues, 1846 WantInteger, BO)) 1847 return false; 1848 isLHS = false; 1849 } 1850 1851 assert(!XorOpValues.empty() && 1852 "computeValueKnownInPredecessors returned true with no values"); 1853 1854 // Scan the information to see which is most popular: true or false. The 1855 // predecessors can be of the set true, false, or undef. 1856 unsigned NumTrue = 0, NumFalse = 0; 1857 for (const auto &XorOpValue : XorOpValues) { 1858 if (isa<UndefValue>(XorOpValue.first)) 1859 // Ignore undefs for the count. 1860 continue; 1861 if (cast<ConstantInt>(XorOpValue.first)->isZero()) 1862 ++NumFalse; 1863 else 1864 ++NumTrue; 1865 } 1866 1867 // Determine which value to split on, true, false, or undef if neither. 1868 ConstantInt *SplitVal = nullptr; 1869 if (NumTrue > NumFalse) 1870 SplitVal = ConstantInt::getTrue(BB->getContext()); 1871 else if (NumTrue != 0 || NumFalse != 0) 1872 SplitVal = ConstantInt::getFalse(BB->getContext()); 1873 1874 // Collect all of the blocks that this can be folded into so that we can 1875 // factor this once and clone it once. 1876 SmallVector<BasicBlock*, 8> BlocksToFoldInto; 1877 for (const auto &XorOpValue : XorOpValues) { 1878 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first)) 1879 continue; 1880 1881 BlocksToFoldInto.push_back(XorOpValue.second); 1882 } 1883 1884 // If we inferred a value for all of the predecessors, then duplication won't 1885 // help us. However, we can just replace the LHS or RHS with the constant. 1886 if (BlocksToFoldInto.size() == 1887 cast<PHINode>(BB->front()).getNumIncomingValues()) { 1888 if (!SplitVal) { 1889 // If all preds provide undef, just nuke the xor, because it is undef too. 1890 BO->replaceAllUsesWith(UndefValue::get(BO->getType())); 1891 BO->eraseFromParent(); 1892 } else if (SplitVal->isZero()) { 1893 // If all preds provide 0, replace the xor with the other input. 1894 BO->replaceAllUsesWith(BO->getOperand(isLHS)); 1895 BO->eraseFromParent(); 1896 } else { 1897 // If all preds provide 1, set the computed value to 1. 1898 BO->setOperand(!isLHS, SplitVal); 1899 } 1900 1901 return true; 1902 } 1903 1904 // If any of predecessors end with an indirect goto, we can't change its 1905 // destination. Same for CallBr. 1906 if (any_of(BlocksToFoldInto, [](BasicBlock *Pred) { 1907 return isa<IndirectBrInst>(Pred->getTerminator()) || 1908 isa<CallBrInst>(Pred->getTerminator()); 1909 })) 1910 return false; 1911 1912 // Try to duplicate BB into PredBB. 1913 return duplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto); 1914 } 1915 1916 /// addPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new 1917 /// predecessor to the PHIBB block. If it has PHI nodes, add entries for 1918 /// NewPred using the entries from OldPred (suitably mapped). 1919 static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, 1920 BasicBlock *OldPred, 1921 BasicBlock *NewPred, 1922 DenseMap<Instruction*, Value*> &ValueMap) { 1923 for (PHINode &PN : PHIBB->phis()) { 1924 // Ok, we have a PHI node. Figure out what the incoming value was for the 1925 // DestBlock. 1926 Value *IV = PN.getIncomingValueForBlock(OldPred); 1927 1928 // Remap the value if necessary. 1929 if (Instruction *Inst = dyn_cast<Instruction>(IV)) { 1930 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst); 1931 if (I != ValueMap.end()) 1932 IV = I->second; 1933 } 1934 1935 PN.addIncoming(IV, NewPred); 1936 } 1937 } 1938 1939 /// Merge basic block BB into its sole predecessor if possible. 1940 bool JumpThreadingPass::maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) { 1941 BasicBlock *SinglePred = BB->getSinglePredecessor(); 1942 if (!SinglePred) 1943 return false; 1944 1945 const Instruction *TI = SinglePred->getTerminator(); 1946 if (TI->isExceptionalTerminator() || TI->getNumSuccessors() != 1 || 1947 SinglePred == BB || hasAddressTakenAndUsed(BB)) 1948 return false; 1949 1950 // If SinglePred was a loop header, BB becomes one. 1951 if (LoopHeaders.erase(SinglePred)) 1952 LoopHeaders.insert(BB); 1953 1954 LVI->eraseBlock(SinglePred); 1955 MergeBasicBlockIntoOnlyPred(BB, DTU); 1956 1957 // Now that BB is merged into SinglePred (i.e. SinglePred code followed by 1958 // BB code within one basic block `BB`), we need to invalidate the LVI 1959 // information associated with BB, because the LVI information need not be 1960 // true for all of BB after the merge. For example, 1961 // Before the merge, LVI info and code is as follows: 1962 // SinglePred: <LVI info1 for %p val> 1963 // %y = use of %p 1964 // call @exit() // need not transfer execution to successor. 1965 // assume(%p) // from this point on %p is true 1966 // br label %BB 1967 // BB: <LVI info2 for %p val, i.e. %p is true> 1968 // %x = use of %p 1969 // br label exit 1970 // 1971 // Note that this LVI info for blocks BB and SinglPred is correct for %p 1972 // (info2 and info1 respectively). After the merge and the deletion of the 1973 // LVI info1 for SinglePred. We have the following code: 1974 // BB: <LVI info2 for %p val> 1975 // %y = use of %p 1976 // call @exit() 1977 // assume(%p) 1978 // %x = use of %p <-- LVI info2 is correct from here onwards. 1979 // br label exit 1980 // LVI info2 for BB is incorrect at the beginning of BB. 1981 1982 // Invalidate LVI information for BB if the LVI is not provably true for 1983 // all of BB. 1984 if (!isGuaranteedToTransferExecutionToSuccessor(BB)) 1985 LVI->eraseBlock(BB); 1986 return true; 1987 } 1988 1989 /// Update the SSA form. NewBB contains instructions that are copied from BB. 1990 /// ValueMapping maps old values in BB to new ones in NewBB. 1991 void JumpThreadingPass::updateSSA( 1992 BasicBlock *BB, BasicBlock *NewBB, 1993 DenseMap<Instruction *, Value *> &ValueMapping) { 1994 // If there were values defined in BB that are used outside the block, then we 1995 // now have to update all uses of the value to use either the original value, 1996 // the cloned value, or some PHI derived value. This can require arbitrary 1997 // PHI insertion, of which we are prepared to do, clean these up now. 1998 SSAUpdater SSAUpdate; 1999 SmallVector<Use *, 16> UsesToRename; 2000 2001 for (Instruction &I : *BB) { 2002 // Scan all uses of this instruction to see if it is used outside of its 2003 // block, and if so, record them in UsesToRename. 2004 for (Use &U : I.uses()) { 2005 Instruction *User = cast<Instruction>(U.getUser()); 2006 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 2007 if (UserPN->getIncomingBlock(U) == BB) 2008 continue; 2009 } else if (User->getParent() == BB) 2010 continue; 2011 2012 UsesToRename.push_back(&U); 2013 } 2014 2015 // If there are no uses outside the block, we're done with this instruction. 2016 if (UsesToRename.empty()) 2017 continue; 2018 LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n"); 2019 2020 // We found a use of I outside of BB. Rename all uses of I that are outside 2021 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 2022 // with the two values we know. 2023 SSAUpdate.Initialize(I.getType(), I.getName()); 2024 SSAUpdate.AddAvailableValue(BB, &I); 2025 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]); 2026 2027 while (!UsesToRename.empty()) 2028 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 2029 LLVM_DEBUG(dbgs() << "\n"); 2030 } 2031 } 2032 2033 /// Clone instructions in range [BI, BE) to NewBB. For PHI nodes, we only clone 2034 /// arguments that come from PredBB. Return the map from the variables in the 2035 /// source basic block to the variables in the newly created basic block. 2036 DenseMap<Instruction *, Value *> 2037 JumpThreadingPass::cloneInstructions(BasicBlock::iterator BI, 2038 BasicBlock::iterator BE, BasicBlock *NewBB, 2039 BasicBlock *PredBB) { 2040 // We are going to have to map operands from the source basic block to the new 2041 // copy of the block 'NewBB'. If there are PHI nodes in the source basic 2042 // block, evaluate them to account for entry from PredBB. 2043 DenseMap<Instruction *, Value *> ValueMapping; 2044 2045 // Clone the phi nodes of the source basic block into NewBB. The resulting 2046 // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater 2047 // might need to rewrite the operand of the cloned phi. 2048 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) { 2049 PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB); 2050 NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB); 2051 ValueMapping[PN] = NewPN; 2052 } 2053 2054 // Clone the non-phi instructions of the source basic block into NewBB, 2055 // keeping track of the mapping and using it to remap operands in the cloned 2056 // instructions. 2057 for (; BI != BE; ++BI) { 2058 Instruction *New = BI->clone(); 2059 New->setName(BI->getName()); 2060 NewBB->getInstList().push_back(New); 2061 ValueMapping[&*BI] = New; 2062 2063 // Remap operands to patch up intra-block references. 2064 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 2065 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 2066 DenseMap<Instruction *, Value *>::iterator I = ValueMapping.find(Inst); 2067 if (I != ValueMapping.end()) 2068 New->setOperand(i, I->second); 2069 } 2070 } 2071 2072 return ValueMapping; 2073 } 2074 2075 /// Attempt to thread through two successive basic blocks. 2076 bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB, 2077 Value *Cond) { 2078 // Consider: 2079 // 2080 // PredBB: 2081 // %var = phi i32* [ null, %bb1 ], [ @a, %bb2 ] 2082 // %tobool = icmp eq i32 %cond, 0 2083 // br i1 %tobool, label %BB, label ... 2084 // 2085 // BB: 2086 // %cmp = icmp eq i32* %var, null 2087 // br i1 %cmp, label ..., label ... 2088 // 2089 // We don't know the value of %var at BB even if we know which incoming edge 2090 // we take to BB. However, once we duplicate PredBB for each of its incoming 2091 // edges (say, PredBB1 and PredBB2), we know the value of %var in each copy of 2092 // PredBB. Then we can thread edges PredBB1->BB and PredBB2->BB through BB. 2093 2094 // Require that BB end with a Branch for simplicity. 2095 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 2096 if (!CondBr) 2097 return false; 2098 2099 // BB must have exactly one predecessor. 2100 BasicBlock *PredBB = BB->getSinglePredecessor(); 2101 if (!PredBB) 2102 return false; 2103 2104 // Require that PredBB end with a conditional Branch. If PredBB ends with an 2105 // unconditional branch, we should be merging PredBB and BB instead. For 2106 // simplicity, we don't deal with a switch. 2107 BranchInst *PredBBBranch = dyn_cast<BranchInst>(PredBB->getTerminator()); 2108 if (!PredBBBranch || PredBBBranch->isUnconditional()) 2109 return false; 2110 2111 // If PredBB has exactly one incoming edge, we don't gain anything by copying 2112 // PredBB. 2113 if (PredBB->getSinglePredecessor()) 2114 return false; 2115 2116 // Don't thread through PredBB if it contains a successor edge to itself, in 2117 // which case we would infinite loop. Suppose we are threading an edge from 2118 // PredPredBB through PredBB and BB to SuccBB with PredBB containing a 2119 // successor edge to itself. If we allowed jump threading in this case, we 2120 // could duplicate PredBB and BB as, say, PredBB.thread and BB.thread. Since 2121 // PredBB.thread has a successor edge to PredBB, we would immediately come up 2122 // with another jump threading opportunity from PredBB.thread through PredBB 2123 // and BB to SuccBB. This jump threading would repeatedly occur. That is, we 2124 // would keep peeling one iteration from PredBB. 2125 if (llvm::is_contained(successors(PredBB), PredBB)) 2126 return false; 2127 2128 // Don't thread across a loop header. 2129 if (LoopHeaders.count(PredBB)) 2130 return false; 2131 2132 // Avoid complication with duplicating EH pads. 2133 if (PredBB->isEHPad()) 2134 return false; 2135 2136 // Find a predecessor that we can thread. For simplicity, we only consider a 2137 // successor edge out of BB to which we thread exactly one incoming edge into 2138 // PredBB. 2139 unsigned ZeroCount = 0; 2140 unsigned OneCount = 0; 2141 BasicBlock *ZeroPred = nullptr; 2142 BasicBlock *OnePred = nullptr; 2143 for (BasicBlock *P : predecessors(PredBB)) { 2144 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>( 2145 evaluateOnPredecessorEdge(BB, P, Cond))) { 2146 if (CI->isZero()) { 2147 ZeroCount++; 2148 ZeroPred = P; 2149 } else if (CI->isOne()) { 2150 OneCount++; 2151 OnePred = P; 2152 } 2153 } 2154 } 2155 2156 // Disregard complicated cases where we have to thread multiple edges. 2157 BasicBlock *PredPredBB; 2158 if (ZeroCount == 1) { 2159 PredPredBB = ZeroPred; 2160 } else if (OneCount == 1) { 2161 PredPredBB = OnePred; 2162 } else { 2163 return false; 2164 } 2165 2166 BasicBlock *SuccBB = CondBr->getSuccessor(PredPredBB == ZeroPred); 2167 2168 // If threading to the same block as we come from, we would infinite loop. 2169 if (SuccBB == BB) { 2170 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName() 2171 << "' - would thread to self!\n"); 2172 return false; 2173 } 2174 2175 // If threading this would thread across a loop header, don't thread the edge. 2176 // See the comments above findLoopHeaders for justifications and caveats. 2177 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) { 2178 LLVM_DEBUG({ 2179 bool BBIsHeader = LoopHeaders.count(BB); 2180 bool SuccIsHeader = LoopHeaders.count(SuccBB); 2181 dbgs() << " Not threading across " 2182 << (BBIsHeader ? "loop header BB '" : "block BB '") 2183 << BB->getName() << "' to dest " 2184 << (SuccIsHeader ? "loop header BB '" : "block BB '") 2185 << SuccBB->getName() 2186 << "' - it might create an irreducible loop!\n"; 2187 }); 2188 return false; 2189 } 2190 2191 // Compute the cost of duplicating BB and PredBB. 2192 unsigned BBCost = 2193 getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold); 2194 unsigned PredBBCost = getJumpThreadDuplicationCost( 2195 PredBB, PredBB->getTerminator(), BBDupThreshold); 2196 2197 // Give up if costs are too high. We need to check BBCost and PredBBCost 2198 // individually before checking their sum because getJumpThreadDuplicationCost 2199 // return (unsigned)~0 for those basic blocks that cannot be duplicated. 2200 if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold || 2201 BBCost + PredBBCost > BBDupThreshold) { 2202 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName() 2203 << "' - Cost is too high: " << PredBBCost 2204 << " for PredBB, " << BBCost << "for BB\n"); 2205 return false; 2206 } 2207 2208 // Now we are ready to duplicate PredBB. 2209 threadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB); 2210 return true; 2211 } 2212 2213 void JumpThreadingPass::threadThroughTwoBasicBlocks(BasicBlock *PredPredBB, 2214 BasicBlock *PredBB, 2215 BasicBlock *BB, 2216 BasicBlock *SuccBB) { 2217 LLVM_DEBUG(dbgs() << " Threading through '" << PredBB->getName() << "' and '" 2218 << BB->getName() << "'\n"); 2219 2220 BranchInst *CondBr = cast<BranchInst>(BB->getTerminator()); 2221 BranchInst *PredBBBranch = cast<BranchInst>(PredBB->getTerminator()); 2222 2223 BasicBlock *NewBB = 2224 BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread", 2225 PredBB->getParent(), PredBB); 2226 NewBB->moveAfter(PredBB); 2227 2228 // Set the block frequency of NewBB. 2229 if (HasProfileData) { 2230 auto NewBBFreq = BFI->getBlockFreq(PredPredBB) * 2231 BPI->getEdgeProbability(PredPredBB, PredBB); 2232 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency()); 2233 } 2234 2235 // We are going to have to map operands from the original BB block to the new 2236 // copy of the block 'NewBB'. If there are PHI nodes in PredBB, evaluate them 2237 // to account for entry from PredPredBB. 2238 DenseMap<Instruction *, Value *> ValueMapping = 2239 cloneInstructions(PredBB->begin(), PredBB->end(), NewBB, PredPredBB); 2240 2241 // Copy the edge probabilities from PredBB to NewBB. 2242 if (HasProfileData) { 2243 SmallVector<BranchProbability, 4> Probs; 2244 for (BasicBlock *Succ : successors(PredBB)) 2245 Probs.push_back(BPI->getEdgeProbability(PredBB, Succ)); 2246 BPI->setEdgeProbability(NewBB, Probs); 2247 } 2248 2249 // Update the terminator of PredPredBB to jump to NewBB instead of PredBB. 2250 // This eliminates predecessors from PredPredBB, which requires us to simplify 2251 // any PHI nodes in PredBB. 2252 Instruction *PredPredTerm = PredPredBB->getTerminator(); 2253 for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i) 2254 if (PredPredTerm->getSuccessor(i) == PredBB) { 2255 PredBB->removePredecessor(PredPredBB, true); 2256 PredPredTerm->setSuccessor(i, NewBB); 2257 } 2258 2259 addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB, 2260 ValueMapping); 2261 addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB, 2262 ValueMapping); 2263 2264 DTU->applyUpdatesPermissive( 2265 {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)}, 2266 {DominatorTree::Insert, NewBB, CondBr->getSuccessor(1)}, 2267 {DominatorTree::Insert, PredPredBB, NewBB}, 2268 {DominatorTree::Delete, PredPredBB, PredBB}}); 2269 2270 updateSSA(PredBB, NewBB, ValueMapping); 2271 2272 // Clean up things like PHI nodes with single operands, dead instructions, 2273 // etc. 2274 SimplifyInstructionsInBlock(NewBB, TLI); 2275 SimplifyInstructionsInBlock(PredBB, TLI); 2276 2277 SmallVector<BasicBlock *, 1> PredsToFactor; 2278 PredsToFactor.push_back(NewBB); 2279 threadEdge(BB, PredsToFactor, SuccBB); 2280 } 2281 2282 /// tryThreadEdge - Thread an edge if it's safe and profitable to do so. 2283 bool JumpThreadingPass::tryThreadEdge( 2284 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs, 2285 BasicBlock *SuccBB) { 2286 // If threading to the same block as we come from, we would infinite loop. 2287 if (SuccBB == BB) { 2288 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName() 2289 << "' - would thread to self!\n"); 2290 return false; 2291 } 2292 2293 // If threading this would thread across a loop header, don't thread the edge. 2294 // See the comments above findLoopHeaders for justifications and caveats. 2295 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) { 2296 LLVM_DEBUG({ 2297 bool BBIsHeader = LoopHeaders.count(BB); 2298 bool SuccIsHeader = LoopHeaders.count(SuccBB); 2299 dbgs() << " Not threading across " 2300 << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName() 2301 << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '") 2302 << SuccBB->getName() << "' - it might create an irreducible loop!\n"; 2303 }); 2304 return false; 2305 } 2306 2307 unsigned JumpThreadCost = 2308 getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold); 2309 if (JumpThreadCost > BBDupThreshold) { 2310 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName() 2311 << "' - Cost is too high: " << JumpThreadCost << "\n"); 2312 return false; 2313 } 2314 2315 threadEdge(BB, PredBBs, SuccBB); 2316 return true; 2317 } 2318 2319 /// threadEdge - We have decided that it is safe and profitable to factor the 2320 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB 2321 /// across BB. Transform the IR to reflect this change. 2322 void JumpThreadingPass::threadEdge(BasicBlock *BB, 2323 const SmallVectorImpl<BasicBlock *> &PredBBs, 2324 BasicBlock *SuccBB) { 2325 assert(SuccBB != BB && "Don't create an infinite loop"); 2326 2327 assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) && 2328 "Don't thread across loop headers"); 2329 2330 // And finally, do it! Start by factoring the predecessors if needed. 2331 BasicBlock *PredBB; 2332 if (PredBBs.size() == 1) 2333 PredBB = PredBBs[0]; 2334 else { 2335 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size() 2336 << " common predecessors.\n"); 2337 PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm"); 2338 } 2339 2340 // And finally, do it! 2341 LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() 2342 << "' to '" << SuccBB->getName() 2343 << ", across block:\n " << *BB << "\n"); 2344 2345 LVI->threadEdge(PredBB, BB, SuccBB); 2346 2347 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), 2348 BB->getName()+".thread", 2349 BB->getParent(), BB); 2350 NewBB->moveAfter(PredBB); 2351 2352 // Set the block frequency of NewBB. 2353 if (HasProfileData) { 2354 auto NewBBFreq = 2355 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB); 2356 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency()); 2357 } 2358 2359 // Copy all the instructions from BB to NewBB except the terminator. 2360 DenseMap<Instruction *, Value *> ValueMapping = 2361 cloneInstructions(BB->begin(), std::prev(BB->end()), NewBB, PredBB); 2362 2363 // We didn't copy the terminator from BB over to NewBB, because there is now 2364 // an unconditional jump to SuccBB. Insert the unconditional jump. 2365 BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB); 2366 NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc()); 2367 2368 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the 2369 // PHI nodes for NewBB now. 2370 addPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping); 2371 2372 // Update the terminator of PredBB to jump to NewBB instead of BB. This 2373 // eliminates predecessors from BB, which requires us to simplify any PHI 2374 // nodes in BB. 2375 Instruction *PredTerm = PredBB->getTerminator(); 2376 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) 2377 if (PredTerm->getSuccessor(i) == BB) { 2378 BB->removePredecessor(PredBB, true); 2379 PredTerm->setSuccessor(i, NewBB); 2380 } 2381 2382 // Enqueue required DT updates. 2383 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB}, 2384 {DominatorTree::Insert, PredBB, NewBB}, 2385 {DominatorTree::Delete, PredBB, BB}}); 2386 2387 updateSSA(BB, NewBB, ValueMapping); 2388 2389 // At this point, the IR is fully up to date and consistent. Do a quick scan 2390 // over the new instructions and zap any that are constants or dead. This 2391 // frequently happens because of phi translation. 2392 SimplifyInstructionsInBlock(NewBB, TLI); 2393 2394 // Update the edge weight from BB to SuccBB, which should be less than before. 2395 updateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB); 2396 2397 // Threaded an edge! 2398 ++NumThreads; 2399 } 2400 2401 /// Create a new basic block that will be the predecessor of BB and successor of 2402 /// all blocks in Preds. When profile data is available, update the frequency of 2403 /// this new block. 2404 BasicBlock *JumpThreadingPass::splitBlockPreds(BasicBlock *BB, 2405 ArrayRef<BasicBlock *> Preds, 2406 const char *Suffix) { 2407 SmallVector<BasicBlock *, 2> NewBBs; 2408 2409 // Collect the frequencies of all predecessors of BB, which will be used to 2410 // update the edge weight of the result of splitting predecessors. 2411 DenseMap<BasicBlock *, BlockFrequency> FreqMap; 2412 if (HasProfileData) 2413 for (auto Pred : Preds) 2414 FreqMap.insert(std::make_pair( 2415 Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB))); 2416 2417 // In the case when BB is a LandingPad block we create 2 new predecessors 2418 // instead of just one. 2419 if (BB->isLandingPad()) { 2420 std::string NewName = std::string(Suffix) + ".split-lp"; 2421 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs); 2422 } else { 2423 NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix)); 2424 } 2425 2426 std::vector<DominatorTree::UpdateType> Updates; 2427 Updates.reserve((2 * Preds.size()) + NewBBs.size()); 2428 for (auto NewBB : NewBBs) { 2429 BlockFrequency NewBBFreq(0); 2430 Updates.push_back({DominatorTree::Insert, NewBB, BB}); 2431 for (auto Pred : predecessors(NewBB)) { 2432 Updates.push_back({DominatorTree::Delete, Pred, BB}); 2433 Updates.push_back({DominatorTree::Insert, Pred, NewBB}); 2434 if (HasProfileData) // Update frequencies between Pred -> NewBB. 2435 NewBBFreq += FreqMap.lookup(Pred); 2436 } 2437 if (HasProfileData) // Apply the summed frequency to NewBB. 2438 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency()); 2439 } 2440 2441 DTU->applyUpdatesPermissive(Updates); 2442 return NewBBs[0]; 2443 } 2444 2445 bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) { 2446 const Instruction *TI = BB->getTerminator(); 2447 assert(TI->getNumSuccessors() > 1 && "not a split"); 2448 2449 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof); 2450 if (!WeightsNode) 2451 return false; 2452 2453 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0)); 2454 if (MDName->getString() != "branch_weights") 2455 return false; 2456 2457 // Ensure there are weights for all of the successors. Note that the first 2458 // operand to the metadata node is a name, not a weight. 2459 return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1; 2460 } 2461 2462 /// Update the block frequency of BB and branch weight and the metadata on the 2463 /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 - 2464 /// Freq(PredBB->BB) / Freq(BB->SuccBB). 2465 void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB, 2466 BasicBlock *BB, 2467 BasicBlock *NewBB, 2468 BasicBlock *SuccBB) { 2469 if (!HasProfileData) 2470 return; 2471 2472 assert(BFI && BPI && "BFI & BPI should have been created here"); 2473 2474 // As the edge from PredBB to BB is deleted, we have to update the block 2475 // frequency of BB. 2476 auto BBOrigFreq = BFI->getBlockFreq(BB); 2477 auto NewBBFreq = BFI->getBlockFreq(NewBB); 2478 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB); 2479 auto BBNewFreq = BBOrigFreq - NewBBFreq; 2480 BFI->setBlockFreq(BB, BBNewFreq.getFrequency()); 2481 2482 // Collect updated outgoing edges' frequencies from BB and use them to update 2483 // edge probabilities. 2484 SmallVector<uint64_t, 4> BBSuccFreq; 2485 for (BasicBlock *Succ : successors(BB)) { 2486 auto SuccFreq = (Succ == SuccBB) 2487 ? BB2SuccBBFreq - NewBBFreq 2488 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ); 2489 BBSuccFreq.push_back(SuccFreq.getFrequency()); 2490 } 2491 2492 uint64_t MaxBBSuccFreq = 2493 *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end()); 2494 2495 SmallVector<BranchProbability, 4> BBSuccProbs; 2496 if (MaxBBSuccFreq == 0) 2497 BBSuccProbs.assign(BBSuccFreq.size(), 2498 {1, static_cast<unsigned>(BBSuccFreq.size())}); 2499 else { 2500 for (uint64_t Freq : BBSuccFreq) 2501 BBSuccProbs.push_back( 2502 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq)); 2503 // Normalize edge probabilities so that they sum up to one. 2504 BranchProbability::normalizeProbabilities(BBSuccProbs.begin(), 2505 BBSuccProbs.end()); 2506 } 2507 2508 // Update edge probabilities in BPI. 2509 BPI->setEdgeProbability(BB, BBSuccProbs); 2510 2511 // Update the profile metadata as well. 2512 // 2513 // Don't do this if the profile of the transformed blocks was statically 2514 // estimated. (This could occur despite the function having an entry 2515 // frequency in completely cold parts of the CFG.) 2516 // 2517 // In this case we don't want to suggest to subsequent passes that the 2518 // calculated weights are fully consistent. Consider this graph: 2519 // 2520 // check_1 2521 // 50% / | 2522 // eq_1 | 50% 2523 // \ | 2524 // check_2 2525 // 50% / | 2526 // eq_2 | 50% 2527 // \ | 2528 // check_3 2529 // 50% / | 2530 // eq_3 | 50% 2531 // \ | 2532 // 2533 // Assuming the blocks check_* all compare the same value against 1, 2 and 3, 2534 // the overall probabilities are inconsistent; the total probability that the 2535 // value is either 1, 2 or 3 is 150%. 2536 // 2537 // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3 2538 // becomes 0%. This is even worse if the edge whose probability becomes 0% is 2539 // the loop exit edge. Then based solely on static estimation we would assume 2540 // the loop was extremely hot. 2541 // 2542 // FIXME this locally as well so that BPI and BFI are consistent as well. We 2543 // shouldn't make edges extremely likely or unlikely based solely on static 2544 // estimation. 2545 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) { 2546 SmallVector<uint32_t, 4> Weights; 2547 for (auto Prob : BBSuccProbs) 2548 Weights.push_back(Prob.getNumerator()); 2549 2550 auto TI = BB->getTerminator(); 2551 TI->setMetadata( 2552 LLVMContext::MD_prof, 2553 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights)); 2554 } 2555 } 2556 2557 /// duplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch 2558 /// to BB which contains an i1 PHI node and a conditional branch on that PHI. 2559 /// If we can duplicate the contents of BB up into PredBB do so now, this 2560 /// improves the odds that the branch will be on an analyzable instruction like 2561 /// a compare. 2562 bool JumpThreadingPass::duplicateCondBranchOnPHIIntoPred( 2563 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) { 2564 assert(!PredBBs.empty() && "Can't handle an empty set"); 2565 2566 // If BB is a loop header, then duplicating this block outside the loop would 2567 // cause us to transform this into an irreducible loop, don't do this. 2568 // See the comments above findLoopHeaders for justifications and caveats. 2569 if (LoopHeaders.count(BB)) { 2570 LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName() 2571 << "' into predecessor block '" << PredBBs[0]->getName() 2572 << "' - it might create an irreducible loop!\n"); 2573 return false; 2574 } 2575 2576 unsigned DuplicationCost = 2577 getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold); 2578 if (DuplicationCost > BBDupThreshold) { 2579 LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName() 2580 << "' - Cost is too high: " << DuplicationCost << "\n"); 2581 return false; 2582 } 2583 2584 // And finally, do it! Start by factoring the predecessors if needed. 2585 std::vector<DominatorTree::UpdateType> Updates; 2586 BasicBlock *PredBB; 2587 if (PredBBs.size() == 1) 2588 PredBB = PredBBs[0]; 2589 else { 2590 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size() 2591 << " common predecessors.\n"); 2592 PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm"); 2593 } 2594 Updates.push_back({DominatorTree::Delete, PredBB, BB}); 2595 2596 // Okay, we decided to do this! Clone all the instructions in BB onto the end 2597 // of PredBB. 2598 LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName() 2599 << "' into end of '" << PredBB->getName() 2600 << "' to eliminate branch on phi. Cost: " 2601 << DuplicationCost << " block is:" << *BB << "\n"); 2602 2603 // Unless PredBB ends with an unconditional branch, split the edge so that we 2604 // can just clone the bits from BB into the end of the new PredBB. 2605 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator()); 2606 2607 if (!OldPredBranch || !OldPredBranch->isUnconditional()) { 2608 BasicBlock *OldPredBB = PredBB; 2609 PredBB = SplitEdge(OldPredBB, BB); 2610 Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB}); 2611 Updates.push_back({DominatorTree::Insert, PredBB, BB}); 2612 Updates.push_back({DominatorTree::Delete, OldPredBB, BB}); 2613 OldPredBranch = cast<BranchInst>(PredBB->getTerminator()); 2614 } 2615 2616 // We are going to have to map operands from the original BB block into the 2617 // PredBB block. Evaluate PHI nodes in BB. 2618 DenseMap<Instruction*, Value*> ValueMapping; 2619 2620 BasicBlock::iterator BI = BB->begin(); 2621 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 2622 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 2623 // Clone the non-phi instructions of BB into PredBB, keeping track of the 2624 // mapping and using it to remap operands in the cloned instructions. 2625 for (; BI != BB->end(); ++BI) { 2626 Instruction *New = BI->clone(); 2627 2628 // Remap operands to patch up intra-block references. 2629 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 2630 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 2631 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 2632 if (I != ValueMapping.end()) 2633 New->setOperand(i, I->second); 2634 } 2635 2636 // If this instruction can be simplified after the operands are updated, 2637 // just use the simplified value instead. This frequently happens due to 2638 // phi translation. 2639 if (Value *IV = SimplifyInstruction( 2640 New, 2641 {BB->getModule()->getDataLayout(), TLI, nullptr, nullptr, New})) { 2642 ValueMapping[&*BI] = IV; 2643 if (!New->mayHaveSideEffects()) { 2644 New->deleteValue(); 2645 New = nullptr; 2646 } 2647 } else { 2648 ValueMapping[&*BI] = New; 2649 } 2650 if (New) { 2651 // Otherwise, insert the new instruction into the block. 2652 New->setName(BI->getName()); 2653 PredBB->getInstList().insert(OldPredBranch->getIterator(), New); 2654 // Update Dominance from simplified New instruction operands. 2655 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 2656 if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i))) 2657 Updates.push_back({DominatorTree::Insert, PredBB, SuccBB}); 2658 } 2659 } 2660 2661 // Check to see if the targets of the branch had PHI nodes. If so, we need to 2662 // add entries to the PHI nodes for branch from PredBB now. 2663 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator()); 2664 addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB, 2665 ValueMapping); 2666 addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB, 2667 ValueMapping); 2668 2669 updateSSA(BB, PredBB, ValueMapping); 2670 2671 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge 2672 // that we nuked. 2673 BB->removePredecessor(PredBB, true); 2674 2675 // Remove the unconditional branch at the end of the PredBB block. 2676 OldPredBranch->eraseFromParent(); 2677 DTU->applyUpdatesPermissive(Updates); 2678 2679 ++NumDupes; 2680 return true; 2681 } 2682 2683 // Pred is a predecessor of BB with an unconditional branch to BB. SI is 2684 // a Select instruction in Pred. BB has other predecessors and SI is used in 2685 // a PHI node in BB. SI has no other use. 2686 // A new basic block, NewBB, is created and SI is converted to compare and 2687 // conditional branch. SI is erased from parent. 2688 void JumpThreadingPass::unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB, 2689 SelectInst *SI, PHINode *SIUse, 2690 unsigned Idx) { 2691 // Expand the select. 2692 // 2693 // Pred -- 2694 // | v 2695 // | NewBB 2696 // | | 2697 // |----- 2698 // v 2699 // BB 2700 BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator()); 2701 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold", 2702 BB->getParent(), BB); 2703 // Move the unconditional branch to NewBB. 2704 PredTerm->removeFromParent(); 2705 NewBB->getInstList().insert(NewBB->end(), PredTerm); 2706 // Create a conditional branch and update PHI nodes. 2707 BranchInst::Create(NewBB, BB, SI->getCondition(), Pred); 2708 SIUse->setIncomingValue(Idx, SI->getFalseValue()); 2709 SIUse->addIncoming(SI->getTrueValue(), NewBB); 2710 2711 // The select is now dead. 2712 SI->eraseFromParent(); 2713 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB}, 2714 {DominatorTree::Insert, Pred, NewBB}}); 2715 2716 // Update any other PHI nodes in BB. 2717 for (BasicBlock::iterator BI = BB->begin(); 2718 PHINode *Phi = dyn_cast<PHINode>(BI); ++BI) 2719 if (Phi != SIUse) 2720 Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB); 2721 } 2722 2723 bool JumpThreadingPass::tryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) { 2724 PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition()); 2725 2726 if (!CondPHI || CondPHI->getParent() != BB) 2727 return false; 2728 2729 for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) { 2730 BasicBlock *Pred = CondPHI->getIncomingBlock(I); 2731 SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I)); 2732 2733 // The second and third condition can be potentially relaxed. Currently 2734 // the conditions help to simplify the code and allow us to reuse existing 2735 // code, developed for tryToUnfoldSelect(CmpInst *, BasicBlock *) 2736 if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse()) 2737 continue; 2738 2739 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator()); 2740 if (!PredTerm || !PredTerm->isUnconditional()) 2741 continue; 2742 2743 unfoldSelectInstr(Pred, BB, PredSI, CondPHI, I); 2744 return true; 2745 } 2746 return false; 2747 } 2748 2749 /// tryToUnfoldSelect - Look for blocks of the form 2750 /// bb1: 2751 /// %a = select 2752 /// br bb2 2753 /// 2754 /// bb2: 2755 /// %p = phi [%a, %bb1] ... 2756 /// %c = icmp %p 2757 /// br i1 %c 2758 /// 2759 /// And expand the select into a branch structure if one of its arms allows %c 2760 /// to be folded. This later enables threading from bb1 over bb2. 2761 bool JumpThreadingPass::tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) { 2762 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 2763 PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0)); 2764 Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1)); 2765 2766 if (!CondBr || !CondBr->isConditional() || !CondLHS || 2767 CondLHS->getParent() != BB) 2768 return false; 2769 2770 for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) { 2771 BasicBlock *Pred = CondLHS->getIncomingBlock(I); 2772 SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I)); 2773 2774 // Look if one of the incoming values is a select in the corresponding 2775 // predecessor. 2776 if (!SI || SI->getParent() != Pred || !SI->hasOneUse()) 2777 continue; 2778 2779 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator()); 2780 if (!PredTerm || !PredTerm->isUnconditional()) 2781 continue; 2782 2783 // Now check if one of the select values would allow us to constant fold the 2784 // terminator in BB. We don't do the transform if both sides fold, those 2785 // cases will be threaded in any case. 2786 LazyValueInfo::Tristate LHSFolds = 2787 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1), 2788 CondRHS, Pred, BB, CondCmp); 2789 LazyValueInfo::Tristate RHSFolds = 2790 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2), 2791 CondRHS, Pred, BB, CondCmp); 2792 if ((LHSFolds != LazyValueInfo::Unknown || 2793 RHSFolds != LazyValueInfo::Unknown) && 2794 LHSFolds != RHSFolds) { 2795 unfoldSelectInstr(Pred, BB, SI, CondLHS, I); 2796 return true; 2797 } 2798 } 2799 return false; 2800 } 2801 2802 /// tryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the 2803 /// same BB in the form 2804 /// bb: 2805 /// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ... 2806 /// %s = select %p, trueval, falseval 2807 /// 2808 /// or 2809 /// 2810 /// bb: 2811 /// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ... 2812 /// %c = cmp %p, 0 2813 /// %s = select %c, trueval, falseval 2814 /// 2815 /// And expand the select into a branch structure. This later enables 2816 /// jump-threading over bb in this pass. 2817 /// 2818 /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold 2819 /// select if the associated PHI has at least one constant. If the unfolded 2820 /// select is not jump-threaded, it will be folded again in the later 2821 /// optimizations. 2822 bool JumpThreadingPass::tryToUnfoldSelectInCurrBB(BasicBlock *BB) { 2823 // This transform would reduce the quality of msan diagnostics. 2824 // Disable this transform under MemorySanitizer. 2825 if (BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory)) 2826 return false; 2827 2828 // If threading this would thread across a loop header, don't thread the edge. 2829 // See the comments above findLoopHeaders for justifications and caveats. 2830 if (LoopHeaders.count(BB)) 2831 return false; 2832 2833 for (BasicBlock::iterator BI = BB->begin(); 2834 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) { 2835 // Look for a Phi having at least one constant incoming value. 2836 if (llvm::all_of(PN->incoming_values(), 2837 [](Value *V) { return !isa<ConstantInt>(V); })) 2838 continue; 2839 2840 auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) { 2841 // Check if SI is in BB and use V as condition. 2842 if (SI->getParent() != BB) 2843 return false; 2844 Value *Cond = SI->getCondition(); 2845 return (Cond && Cond == V && Cond->getType()->isIntegerTy(1)); 2846 }; 2847 2848 SelectInst *SI = nullptr; 2849 for (Use &U : PN->uses()) { 2850 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) { 2851 // Look for a ICmp in BB that compares PN with a constant and is the 2852 // condition of a Select. 2853 if (Cmp->getParent() == BB && Cmp->hasOneUse() && 2854 isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo()))) 2855 if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back())) 2856 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) { 2857 SI = SelectI; 2858 break; 2859 } 2860 } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) { 2861 // Look for a Select in BB that uses PN as condition. 2862 if (isUnfoldCandidate(SelectI, U.get())) { 2863 SI = SelectI; 2864 break; 2865 } 2866 } 2867 } 2868 2869 if (!SI) 2870 continue; 2871 // Expand the select. 2872 Value *Cond = SI->getCondition(); 2873 if (InsertFreezeWhenUnfoldingSelect && 2874 !isGuaranteedNotToBeUndefOrPoison(Cond, nullptr, SI, 2875 &DTU->getDomTree())) 2876 Cond = new FreezeInst(Cond, "cond.fr", SI); 2877 Instruction *Term = SplitBlockAndInsertIfThen(Cond, SI, false); 2878 BasicBlock *SplitBB = SI->getParent(); 2879 BasicBlock *NewBB = Term->getParent(); 2880 PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI); 2881 NewPN->addIncoming(SI->getTrueValue(), Term->getParent()); 2882 NewPN->addIncoming(SI->getFalseValue(), BB); 2883 SI->replaceAllUsesWith(NewPN); 2884 SI->eraseFromParent(); 2885 // NewBB and SplitBB are newly created blocks which require insertion. 2886 std::vector<DominatorTree::UpdateType> Updates; 2887 Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3); 2888 Updates.push_back({DominatorTree::Insert, BB, SplitBB}); 2889 Updates.push_back({DominatorTree::Insert, BB, NewBB}); 2890 Updates.push_back({DominatorTree::Insert, NewBB, SplitBB}); 2891 // BB's successors were moved to SplitBB, update DTU accordingly. 2892 for (auto *Succ : successors(SplitBB)) { 2893 Updates.push_back({DominatorTree::Delete, BB, Succ}); 2894 Updates.push_back({DominatorTree::Insert, SplitBB, Succ}); 2895 } 2896 DTU->applyUpdatesPermissive(Updates); 2897 return true; 2898 } 2899 return false; 2900 } 2901 2902 /// Try to propagate a guard from the current BB into one of its predecessors 2903 /// in case if another branch of execution implies that the condition of this 2904 /// guard is always true. Currently we only process the simplest case that 2905 /// looks like: 2906 /// 2907 /// Start: 2908 /// %cond = ... 2909 /// br i1 %cond, label %T1, label %F1 2910 /// T1: 2911 /// br label %Merge 2912 /// F1: 2913 /// br label %Merge 2914 /// Merge: 2915 /// %condGuard = ... 2916 /// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ] 2917 /// 2918 /// And cond either implies condGuard or !condGuard. In this case all the 2919 /// instructions before the guard can be duplicated in both branches, and the 2920 /// guard is then threaded to one of them. 2921 bool JumpThreadingPass::processGuards(BasicBlock *BB) { 2922 using namespace PatternMatch; 2923 2924 // We only want to deal with two predecessors. 2925 BasicBlock *Pred1, *Pred2; 2926 auto PI = pred_begin(BB), PE = pred_end(BB); 2927 if (PI == PE) 2928 return false; 2929 Pred1 = *PI++; 2930 if (PI == PE) 2931 return false; 2932 Pred2 = *PI++; 2933 if (PI != PE) 2934 return false; 2935 if (Pred1 == Pred2) 2936 return false; 2937 2938 // Try to thread one of the guards of the block. 2939 // TODO: Look up deeper than to immediate predecessor? 2940 auto *Parent = Pred1->getSinglePredecessor(); 2941 if (!Parent || Parent != Pred2->getSinglePredecessor()) 2942 return false; 2943 2944 if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator())) 2945 for (auto &I : *BB) 2946 if (isGuard(&I) && threadGuard(BB, cast<IntrinsicInst>(&I), BI)) 2947 return true; 2948 2949 return false; 2950 } 2951 2952 /// Try to propagate the guard from BB which is the lower block of a diamond 2953 /// to one of its branches, in case if diamond's condition implies guard's 2954 /// condition. 2955 bool JumpThreadingPass::threadGuard(BasicBlock *BB, IntrinsicInst *Guard, 2956 BranchInst *BI) { 2957 assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?"); 2958 assert(BI->isConditional() && "Unconditional branch has 2 successors?"); 2959 Value *GuardCond = Guard->getArgOperand(0); 2960 Value *BranchCond = BI->getCondition(); 2961 BasicBlock *TrueDest = BI->getSuccessor(0); 2962 BasicBlock *FalseDest = BI->getSuccessor(1); 2963 2964 auto &DL = BB->getModule()->getDataLayout(); 2965 bool TrueDestIsSafe = false; 2966 bool FalseDestIsSafe = false; 2967 2968 // True dest is safe if BranchCond => GuardCond. 2969 auto Impl = isImpliedCondition(BranchCond, GuardCond, DL); 2970 if (Impl && *Impl) 2971 TrueDestIsSafe = true; 2972 else { 2973 // False dest is safe if !BranchCond => GuardCond. 2974 Impl = isImpliedCondition(BranchCond, GuardCond, DL, /* LHSIsTrue */ false); 2975 if (Impl && *Impl) 2976 FalseDestIsSafe = true; 2977 } 2978 2979 if (!TrueDestIsSafe && !FalseDestIsSafe) 2980 return false; 2981 2982 BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest; 2983 BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest; 2984 2985 ValueToValueMapTy UnguardedMapping, GuardedMapping; 2986 Instruction *AfterGuard = Guard->getNextNode(); 2987 unsigned Cost = getJumpThreadDuplicationCost(BB, AfterGuard, BBDupThreshold); 2988 if (Cost > BBDupThreshold) 2989 return false; 2990 // Duplicate all instructions before the guard and the guard itself to the 2991 // branch where implication is not proved. 2992 BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween( 2993 BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU); 2994 assert(GuardedBlock && "Could not create the guarded block?"); 2995 // Duplicate all instructions before the guard in the unguarded branch. 2996 // Since we have successfully duplicated the guarded block and this block 2997 // has fewer instructions, we expect it to succeed. 2998 BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween( 2999 BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU); 3000 assert(UnguardedBlock && "Could not create the unguarded block?"); 3001 LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block " 3002 << GuardedBlock->getName() << "\n"); 3003 // Some instructions before the guard may still have uses. For them, we need 3004 // to create Phi nodes merging their copies in both guarded and unguarded 3005 // branches. Those instructions that have no uses can be just removed. 3006 SmallVector<Instruction *, 4> ToRemove; 3007 for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI) 3008 if (!isa<PHINode>(&*BI)) 3009 ToRemove.push_back(&*BI); 3010 3011 Instruction *InsertionPoint = &*BB->getFirstInsertionPt(); 3012 assert(InsertionPoint && "Empty block?"); 3013 // Substitute with Phis & remove. 3014 for (auto *Inst : reverse(ToRemove)) { 3015 if (!Inst->use_empty()) { 3016 PHINode *NewPN = PHINode::Create(Inst->getType(), 2); 3017 NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock); 3018 NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock); 3019 NewPN->insertBefore(InsertionPoint); 3020 Inst->replaceAllUsesWith(NewPN); 3021 } 3022 Inst->eraseFromParent(); 3023 } 3024 return true; 3025 } 3026