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