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