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