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