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