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