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