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