1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Jump Threading pass. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar/JumpThreading.h" 15 #include "llvm/Transforms/Scalar.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/DenseSet.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/GlobalsModRef.h" 21 #include "llvm/Analysis/CFG.h" 22 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 23 #include "llvm/Analysis/ConstantFolding.h" 24 #include "llvm/Analysis/InstructionSimplify.h" 25 #include "llvm/Analysis/Loads.h" 26 #include "llvm/Analysis/LoopInfo.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/MDBuilder.h" 32 #include "llvm/IR/Metadata.h" 33 #include "llvm/Pass.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38 #include "llvm/Transforms/Utils/Local.h" 39 #include "llvm/Transforms/Utils/SSAUpdater.h" 40 #include <algorithm> 41 #include <memory> 42 using namespace llvm; 43 using namespace jumpthreading; 44 45 #define DEBUG_TYPE "jump-threading" 46 47 STATISTIC(NumThreads, "Number of jumps threaded"); 48 STATISTIC(NumFolds, "Number of terminators folded"); 49 STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi"); 50 51 static cl::opt<unsigned> 52 BBDuplicateThreshold("jump-threading-threshold", 53 cl::desc("Max block size to duplicate for jump threading"), 54 cl::init(6), cl::Hidden); 55 56 static cl::opt<unsigned> 57 ImplicationSearchThreshold( 58 "jump-threading-implication-search-threshold", 59 cl::desc("The number of predecessors to search for a stronger " 60 "condition to use to thread over a weaker condition"), 61 cl::init(3), cl::Hidden); 62 63 namespace { 64 /// This pass performs 'jump threading', which looks at blocks that have 65 /// multiple predecessors and multiple successors. If one or more of the 66 /// predecessors of the block can be proven to always jump to one of the 67 /// successors, we forward the edge from the predecessor to the successor by 68 /// duplicating the contents of this block. 69 /// 70 /// An example of when this can occur is code like this: 71 /// 72 /// if () { ... 73 /// X = 4; 74 /// } 75 /// if (X < 3) { 76 /// 77 /// In this case, the unconditional branch at the end of the first if can be 78 /// revectored to the false side of the second if. 79 /// 80 class JumpThreading : public FunctionPass { 81 JumpThreadingPass Impl; 82 83 public: 84 static char ID; // Pass identification 85 JumpThreading(int T = -1) : FunctionPass(ID), Impl(T) { 86 initializeJumpThreadingPass(*PassRegistry::getPassRegistry()); 87 } 88 89 bool runOnFunction(Function &F) override; 90 91 void getAnalysisUsage(AnalysisUsage &AU) const override { 92 AU.addRequired<LazyValueInfoWrapperPass>(); 93 AU.addPreserved<LazyValueInfoWrapperPass>(); 94 AU.addPreserved<GlobalsAAWrapperPass>(); 95 AU.addRequired<TargetLibraryInfoWrapperPass>(); 96 } 97 98 void releaseMemory() override { Impl.releaseMemory(); } 99 }; 100 } 101 102 char JumpThreading::ID = 0; 103 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading", 104 "Jump Threading", false, false) 105 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 106 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 107 INITIALIZE_PASS_END(JumpThreading, "jump-threading", 108 "Jump Threading", false, false) 109 110 // Public interface to the Jump Threading pass 111 FunctionPass *llvm::createJumpThreadingPass(int Threshold) { return new JumpThreading(Threshold); } 112 113 JumpThreadingPass::JumpThreadingPass(int T) { 114 BBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T); 115 } 116 117 /// runOnFunction - Top level algorithm. 118 /// 119 bool JumpThreading::runOnFunction(Function &F) { 120 if (skipFunction(F)) 121 return false; 122 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 123 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI(); 124 std::unique_ptr<BlockFrequencyInfo> BFI; 125 std::unique_ptr<BranchProbabilityInfo> BPI; 126 bool HasProfileData = F.getEntryCount().hasValue(); 127 if (HasProfileData) { 128 LoopInfo LI{DominatorTree(F)}; 129 BPI.reset(new BranchProbabilityInfo(F, LI)); 130 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); 131 } 132 return Impl.runImpl(F, TLI, LVI, HasProfileData, std::move(BFI), 133 std::move(BPI)); 134 } 135 136 PreservedAnalyses JumpThreadingPass::run(Function &F, 137 FunctionAnalysisManager &AM) { 138 139 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 140 auto &LVI = AM.getResult<LazyValueAnalysis>(F); 141 std::unique_ptr<BlockFrequencyInfo> BFI; 142 std::unique_ptr<BranchProbabilityInfo> BPI; 143 bool HasProfileData = F.getEntryCount().hasValue(); 144 if (HasProfileData) { 145 LoopInfo LI{DominatorTree(F)}; 146 BPI.reset(new BranchProbabilityInfo(F, LI)); 147 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); 148 } 149 bool Changed = 150 runImpl(F, &TLI, &LVI, HasProfileData, std::move(BFI), std::move(BPI)); 151 152 if (!Changed) 153 return PreservedAnalyses::all(); 154 PreservedAnalyses PA; 155 PA.preserve<GlobalsAA>(); 156 return PA; 157 } 158 159 bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_, 160 LazyValueInfo *LVI_, bool HasProfileData_, 161 std::unique_ptr<BlockFrequencyInfo> BFI_, 162 std::unique_ptr<BranchProbabilityInfo> BPI_) { 163 164 DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n"); 165 TLI = TLI_; 166 LVI = LVI_; 167 BFI.reset(); 168 BPI.reset(); 169 // When profile data is available, we need to update edge weights after 170 // successful jump threading, which requires both BPI and BFI being available. 171 HasProfileData = HasProfileData_; 172 if (HasProfileData) { 173 BPI = std::move(BPI_); 174 BFI = std::move(BFI_); 175 } 176 177 // Remove unreachable blocks from function as they may result in infinite 178 // loop. We do threading if we found something profitable. Jump threading a 179 // branch can create other opportunities. If these opportunities form a cycle 180 // i.e. if any jump threading is undoing previous threading in the path, then 181 // we will loop forever. We take care of this issue by not jump threading for 182 // back edges. This works for normal cases but not for unreachable blocks as 183 // they may have cycle with no back edge. 184 bool EverChanged = false; 185 EverChanged |= removeUnreachableBlocks(F, LVI); 186 187 FindLoopHeaders(F); 188 189 bool Changed; 190 do { 191 Changed = false; 192 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 193 BasicBlock *BB = &*I; 194 // Thread all of the branches we can over this block. 195 while (ProcessBlock(BB)) 196 Changed = true; 197 198 ++I; 199 200 // If the block is trivially dead, zap it. This eliminates the successor 201 // edges which simplifies the CFG. 202 if (pred_empty(BB) && 203 BB != &BB->getParent()->getEntryBlock()) { 204 DEBUG(dbgs() << " JT: Deleting dead block '" << BB->getName() 205 << "' with terminator: " << *BB->getTerminator() << '\n'); 206 LoopHeaders.erase(BB); 207 LVI->eraseBlock(BB); 208 DeleteDeadBlock(BB); 209 Changed = true; 210 continue; 211 } 212 213 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); 214 215 // Can't thread an unconditional jump, but if the block is "almost 216 // empty", we can replace uses of it with uses of the successor and make 217 // this dead. 218 // We should not eliminate the loop header either, because eliminating 219 // a loop header might later prevent LoopSimplify from transforming nested 220 // loops into simplified form. 221 if (BI && BI->isUnconditional() && 222 BB != &BB->getParent()->getEntryBlock() && 223 // If the terminator is the only non-phi instruction, try to nuke it. 224 BB->getFirstNonPHIOrDbg()->isTerminator() && !LoopHeaders.count(BB)) { 225 // FIXME: It is always conservatively correct to drop the info 226 // for a block even if it doesn't get erased. This isn't totally 227 // awesome, but it allows us to use AssertingVH to prevent nasty 228 // dangling pointer issues within LazyValueInfo. 229 LVI->eraseBlock(BB); 230 if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) 231 Changed = true; 232 } 233 } 234 EverChanged |= Changed; 235 } while (Changed); 236 237 LoopHeaders.clear(); 238 return EverChanged; 239 } 240 241 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to 242 /// thread across it. Stop scanning the block when passing the threshold. 243 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB, 244 unsigned Threshold) { 245 /// Ignore PHI nodes, these will be flattened when duplication happens. 246 BasicBlock::const_iterator I(BB->getFirstNonPHI()); 247 248 // FIXME: THREADING will delete values that are just used to compute the 249 // branch, so they shouldn't count against the duplication cost. 250 251 unsigned Bonus = 0; 252 const TerminatorInst *BBTerm = BB->getTerminator(); 253 // Threading through a switch statement is particularly profitable. If this 254 // block ends in a switch, decrease its cost to make it more likely to happen. 255 if (isa<SwitchInst>(BBTerm)) 256 Bonus = 6; 257 258 // The same holds for indirect branches, but slightly more so. 259 if (isa<IndirectBrInst>(BBTerm)) 260 Bonus = 8; 261 262 // Bump the threshold up so the early exit from the loop doesn't skip the 263 // terminator-based Size adjustment at the end. 264 Threshold += Bonus; 265 266 // Sum up the cost of each instruction until we get to the terminator. Don't 267 // include the terminator because the copy won't include it. 268 unsigned Size = 0; 269 for (; !isa<TerminatorInst>(I); ++I) { 270 271 // Stop scanning the block if we've reached the threshold. 272 if (Size > Threshold) 273 return Size; 274 275 // Debugger intrinsics don't incur code size. 276 if (isa<DbgInfoIntrinsic>(I)) continue; 277 278 // If this is a pointer->pointer bitcast, it is free. 279 if (isa<BitCastInst>(I) && I->getType()->isPointerTy()) 280 continue; 281 282 // Bail out if this instruction gives back a token type, it is not possible 283 // to duplicate it if it is used outside this BB. 284 if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB)) 285 return ~0U; 286 287 // All other instructions count for at least one unit. 288 ++Size; 289 290 // Calls are more expensive. If they are non-intrinsic calls, we model them 291 // as having cost of 4. If they are a non-vector intrinsic, we model them 292 // as having cost of 2 total, and if they are a vector intrinsic, we model 293 // them as having cost 1. 294 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 295 if (CI->cannotDuplicate() || CI->isConvergent()) 296 // Blocks with NoDuplicate are modelled as having infinite cost, so they 297 // are never duplicated. 298 return ~0U; 299 else if (!isa<IntrinsicInst>(CI)) 300 Size += 3; 301 else if (!CI->getType()->isVectorTy()) 302 Size += 1; 303 } 304 } 305 306 return Size > Bonus ? Size - Bonus : 0; 307 } 308 309 /// FindLoopHeaders - We do not want jump threading to turn proper loop 310 /// structures into irreducible loops. Doing this breaks up the loop nesting 311 /// hierarchy and pessimizes later transformations. To prevent this from 312 /// happening, we first have to find the loop headers. Here we approximate this 313 /// by finding targets of backedges in the CFG. 314 /// 315 /// Note that there definitely are cases when we want to allow threading of 316 /// edges across a loop header. For example, threading a jump from outside the 317 /// loop (the preheader) to an exit block of the loop is definitely profitable. 318 /// It is also almost always profitable to thread backedges from within the loop 319 /// to exit blocks, and is often profitable to thread backedges to other blocks 320 /// within the loop (forming a nested loop). This simple analysis is not rich 321 /// enough to track all of these properties and keep it up-to-date as the CFG 322 /// mutates, so we don't allow any of these transformations. 323 /// 324 void JumpThreadingPass::FindLoopHeaders(Function &F) { 325 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges; 326 FindFunctionBackedges(F, Edges); 327 328 for (const auto &Edge : Edges) 329 LoopHeaders.insert(Edge.second); 330 } 331 332 /// getKnownConstant - Helper method to determine if we can thread over a 333 /// terminator with the given value as its condition, and if so what value to 334 /// use for that. What kind of value this is depends on whether we want an 335 /// integer or a block address, but an undef is always accepted. 336 /// Returns null if Val is null or not an appropriate constant. 337 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) { 338 if (!Val) 339 return nullptr; 340 341 // Undef is "known" enough. 342 if (UndefValue *U = dyn_cast<UndefValue>(Val)) 343 return U; 344 345 if (Preference == WantBlockAddress) 346 return dyn_cast<BlockAddress>(Val->stripPointerCasts()); 347 348 return dyn_cast<ConstantInt>(Val); 349 } 350 351 /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see 352 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef 353 /// in any of our predecessors. If so, return the known list of value and pred 354 /// BB in the result vector. 355 /// 356 /// This returns true if there were any known values. 357 /// 358 bool JumpThreadingPass::ComputeValueKnownInPredecessors( 359 Value *V, BasicBlock *BB, PredValueInfo &Result, 360 ConstantPreference Preference, Instruction *CxtI) { 361 // This method walks up use-def chains recursively. Because of this, we could 362 // get into an infinite loop going around loops in the use-def chain. To 363 // prevent this, keep track of what (value, block) pairs we've already visited 364 // and terminate the search if we loop back to them 365 if (!RecursionSet.insert(std::make_pair(V, BB)).second) 366 return false; 367 368 // An RAII help to remove this pair from the recursion set once the recursion 369 // stack pops back out again. 370 RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB)); 371 372 // If V is a constant, then it is known in all predecessors. 373 if (Constant *KC = getKnownConstant(V, Preference)) { 374 for (BasicBlock *Pred : predecessors(BB)) 375 Result.push_back(std::make_pair(KC, Pred)); 376 377 return !Result.empty(); 378 } 379 380 // If V is a non-instruction value, or an instruction in a different block, 381 // then it can't be derived from a PHI. 382 Instruction *I = dyn_cast<Instruction>(V); 383 if (!I || I->getParent() != BB) { 384 385 // Okay, if this is a live-in value, see if it has a known value at the end 386 // of any of our predecessors. 387 // 388 // FIXME: This should be an edge property, not a block end property. 389 /// TODO: Per PR2563, we could infer value range information about a 390 /// predecessor based on its terminator. 391 // 392 // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if 393 // "I" is a non-local compare-with-a-constant instruction. This would be 394 // able to handle value inequalities better, for example if the compare is 395 // "X < 4" and "X < 3" is known true but "X < 4" itself is not available. 396 // Perhaps getConstantOnEdge should be smart enough to do this? 397 398 for (BasicBlock *P : predecessors(BB)) { 399 // If the value is known by LazyValueInfo to be a constant in a 400 // predecessor, use that information to try to thread this block. 401 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI); 402 if (Constant *KC = getKnownConstant(PredCst, Preference)) 403 Result.push_back(std::make_pair(KC, P)); 404 } 405 406 return !Result.empty(); 407 } 408 409 /// If I is a PHI node, then we know the incoming values for any constants. 410 if (PHINode *PN = dyn_cast<PHINode>(I)) { 411 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 412 Value *InVal = PN->getIncomingValue(i); 413 if (Constant *KC = getKnownConstant(InVal, Preference)) { 414 Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i))); 415 } else { 416 Constant *CI = LVI->getConstantOnEdge(InVal, 417 PN->getIncomingBlock(i), 418 BB, CxtI); 419 if (Constant *KC = getKnownConstant(CI, Preference)) 420 Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i))); 421 } 422 } 423 424 return !Result.empty(); 425 } 426 427 // Handle Cast instructions. Only see through Cast when the source operand is 428 // PHI or Cmp and the source type is i1 to save the compilation time. 429 if (CastInst *CI = dyn_cast<CastInst>(I)) { 430 Value *Source = CI->getOperand(0); 431 if (!Source->getType()->isIntegerTy(1)) 432 return false; 433 if (!isa<PHINode>(Source) && !isa<CmpInst>(Source)) 434 return false; 435 ComputeValueKnownInPredecessors(Source, BB, Result, Preference, CxtI); 436 if (Result.empty()) 437 return false; 438 439 // Convert the known values. 440 for (auto &R : Result) 441 R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType()); 442 443 return true; 444 } 445 446 PredValueInfoTy LHSVals, RHSVals; 447 448 // Handle some boolean conditions. 449 if (I->getType()->getPrimitiveSizeInBits() == 1) { 450 assert(Preference == WantInteger && "One-bit non-integer type?"); 451 // X | true -> true 452 // X & false -> false 453 if (I->getOpcode() == Instruction::Or || 454 I->getOpcode() == Instruction::And) { 455 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals, 456 WantInteger, CxtI); 457 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals, 458 WantInteger, CxtI); 459 460 if (LHSVals.empty() && RHSVals.empty()) 461 return false; 462 463 ConstantInt *InterestingVal; 464 if (I->getOpcode() == Instruction::Or) 465 InterestingVal = ConstantInt::getTrue(I->getContext()); 466 else 467 InterestingVal = ConstantInt::getFalse(I->getContext()); 468 469 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs; 470 471 // Scan for the sentinel. If we find an undef, force it to the 472 // interesting value: x|undef -> true and x&undef -> false. 473 for (const auto &LHSVal : LHSVals) 474 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) { 475 Result.emplace_back(InterestingVal, LHSVal.second); 476 LHSKnownBBs.insert(LHSVal.second); 477 } 478 for (const auto &RHSVal : RHSVals) 479 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) { 480 // If we already inferred a value for this block on the LHS, don't 481 // re-add it. 482 if (!LHSKnownBBs.count(RHSVal.second)) 483 Result.emplace_back(InterestingVal, RHSVal.second); 484 } 485 486 return !Result.empty(); 487 } 488 489 // Handle the NOT form of XOR. 490 if (I->getOpcode() == Instruction::Xor && 491 isa<ConstantInt>(I->getOperand(1)) && 492 cast<ConstantInt>(I->getOperand(1))->isOne()) { 493 ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result, 494 WantInteger, CxtI); 495 if (Result.empty()) 496 return false; 497 498 // Invert the known values. 499 for (auto &R : Result) 500 R.first = ConstantExpr::getNot(R.first); 501 502 return true; 503 } 504 505 // Try to simplify some other binary operator values. 506 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 507 assert(Preference != WantBlockAddress 508 && "A binary operator creating a block address?"); 509 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) { 510 PredValueInfoTy LHSVals; 511 ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals, 512 WantInteger, CxtI); 513 514 // Try to use constant folding to simplify the binary operator. 515 for (const auto &LHSVal : LHSVals) { 516 Constant *V = LHSVal.first; 517 Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI); 518 519 if (Constant *KC = getKnownConstant(Folded, WantInteger)) 520 Result.push_back(std::make_pair(KC, LHSVal.second)); 521 } 522 } 523 524 return !Result.empty(); 525 } 526 527 // Handle compare with phi operand, where the PHI is defined in this block. 528 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 529 assert(Preference == WantInteger && "Compares only produce integers"); 530 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0)); 531 if (PN && PN->getParent() == BB) { 532 const DataLayout &DL = PN->getModule()->getDataLayout(); 533 // We can do this simplification if any comparisons fold to true or false. 534 // See if any do. 535 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 536 BasicBlock *PredBB = PN->getIncomingBlock(i); 537 Value *LHS = PN->getIncomingValue(i); 538 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB); 539 540 Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, DL); 541 if (!Res) { 542 if (!isa<Constant>(RHS)) 543 continue; 544 545 LazyValueInfo::Tristate 546 ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS, 547 cast<Constant>(RHS), PredBB, BB, 548 CxtI ? CxtI : Cmp); 549 if (ResT == LazyValueInfo::Unknown) 550 continue; 551 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT); 552 } 553 554 if (Constant *KC = getKnownConstant(Res, WantInteger)) 555 Result.push_back(std::make_pair(KC, PredBB)); 556 } 557 558 return !Result.empty(); 559 } 560 561 // If comparing a live-in value against a constant, see if we know the 562 // live-in value on any predecessors. 563 if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) { 564 if (!isa<Instruction>(Cmp->getOperand(0)) || 565 cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) { 566 Constant *RHSCst = cast<Constant>(Cmp->getOperand(1)); 567 568 for (BasicBlock *P : predecessors(BB)) { 569 // If the value is known by LazyValueInfo to be a constant in a 570 // predecessor, use that information to try to thread this block. 571 LazyValueInfo::Tristate Res = 572 LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0), 573 RHSCst, P, BB, CxtI ? CxtI : Cmp); 574 if (Res == LazyValueInfo::Unknown) 575 continue; 576 577 Constant *ResC = ConstantInt::get(Cmp->getType(), Res); 578 Result.push_back(std::make_pair(ResC, P)); 579 } 580 581 return !Result.empty(); 582 } 583 584 // Try to find a constant value for the LHS of a comparison, 585 // and evaluate it statically if we can. 586 if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) { 587 PredValueInfoTy LHSVals; 588 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals, 589 WantInteger, CxtI); 590 591 for (const auto &LHSVal : LHSVals) { 592 Constant *V = LHSVal.first; 593 Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(), 594 V, CmpConst); 595 if (Constant *KC = getKnownConstant(Folded, WantInteger)) 596 Result.push_back(std::make_pair(KC, LHSVal.second)); 597 } 598 599 return !Result.empty(); 600 } 601 } 602 } 603 604 if (SelectInst *SI = dyn_cast<SelectInst>(I)) { 605 // Handle select instructions where at least one operand is a known constant 606 // and we can figure out the condition value for any predecessor block. 607 Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference); 608 Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference); 609 PredValueInfoTy Conds; 610 if ((TrueVal || FalseVal) && 611 ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds, 612 WantInteger, CxtI)) { 613 for (auto &C : Conds) { 614 Constant *Cond = C.first; 615 616 // Figure out what value to use for the condition. 617 bool KnownCond; 618 if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) { 619 // A known boolean. 620 KnownCond = CI->isOne(); 621 } else { 622 assert(isa<UndefValue>(Cond) && "Unexpected condition value"); 623 // Either operand will do, so be sure to pick the one that's a known 624 // constant. 625 // FIXME: Do this more cleverly if both values are known constants? 626 KnownCond = (TrueVal != nullptr); 627 } 628 629 // See if the select has a known constant value for this predecessor. 630 if (Constant *Val = KnownCond ? TrueVal : FalseVal) 631 Result.push_back(std::make_pair(Val, C.second)); 632 } 633 634 return !Result.empty(); 635 } 636 } 637 638 // If all else fails, see if LVI can figure out a constant value for us. 639 Constant *CI = LVI->getConstant(V, BB, CxtI); 640 if (Constant *KC = getKnownConstant(CI, Preference)) { 641 for (BasicBlock *Pred : predecessors(BB)) 642 Result.push_back(std::make_pair(KC, Pred)); 643 } 644 645 return !Result.empty(); 646 } 647 648 649 650 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends 651 /// in an undefined jump, decide which block is best to revector to. 652 /// 653 /// Since we can pick an arbitrary destination, we pick the successor with the 654 /// fewest predecessors. This should reduce the in-degree of the others. 655 /// 656 static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) { 657 TerminatorInst *BBTerm = BB->getTerminator(); 658 unsigned MinSucc = 0; 659 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc); 660 // Compute the successor with the minimum number of predecessors. 661 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); 662 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) { 663 TestBB = BBTerm->getSuccessor(i); 664 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); 665 if (NumPreds < MinNumPreds) { 666 MinSucc = i; 667 MinNumPreds = NumPreds; 668 } 669 } 670 671 return MinSucc; 672 } 673 674 static bool hasAddressTakenAndUsed(BasicBlock *BB) { 675 if (!BB->hasAddressTaken()) return false; 676 677 // If the block has its address taken, it may be a tree of dead constants 678 // hanging off of it. These shouldn't keep the block alive. 679 BlockAddress *BA = BlockAddress::get(BB); 680 BA->removeDeadConstantUsers(); 681 return !BA->use_empty(); 682 } 683 684 /// ProcessBlock - If there are any predecessors whose control can be threaded 685 /// through to a successor, transform them now. 686 bool JumpThreadingPass::ProcessBlock(BasicBlock *BB) { 687 // If the block is trivially dead, just return and let the caller nuke it. 688 // This simplifies other transformations. 689 if (pred_empty(BB) && 690 BB != &BB->getParent()->getEntryBlock()) 691 return false; 692 693 // If this block has a single predecessor, and if that pred has a single 694 // successor, merge the blocks. This encourages recursive jump threading 695 // because now the condition in this block can be threaded through 696 // predecessors of our predecessor block. 697 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) { 698 const TerminatorInst *TI = SinglePred->getTerminator(); 699 if (!TI->isExceptional() && TI->getNumSuccessors() == 1 && 700 SinglePred != BB && !hasAddressTakenAndUsed(BB)) { 701 // If SinglePred was a loop header, BB becomes one. 702 if (LoopHeaders.erase(SinglePred)) 703 LoopHeaders.insert(BB); 704 705 LVI->eraseBlock(SinglePred); 706 MergeBasicBlockIntoOnlyPred(BB); 707 708 return true; 709 } 710 } 711 712 if (TryToUnfoldSelectInCurrBB(BB)) 713 return true; 714 715 // What kind of constant we're looking for. 716 ConstantPreference Preference = WantInteger; 717 718 // Look to see if the terminator is a conditional branch, switch or indirect 719 // branch, if not we can't thread it. 720 Value *Condition; 721 Instruction *Terminator = BB->getTerminator(); 722 if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) { 723 // Can't thread an unconditional jump. 724 if (BI->isUnconditional()) return false; 725 Condition = BI->getCondition(); 726 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) { 727 Condition = SI->getCondition(); 728 } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) { 729 // Can't thread indirect branch with no successors. 730 if (IB->getNumSuccessors() == 0) return false; 731 Condition = IB->getAddress()->stripPointerCasts(); 732 Preference = WantBlockAddress; 733 } else { 734 return false; // Must be an invoke. 735 } 736 737 // Run constant folding to see if we can reduce the condition to a simple 738 // constant. 739 if (Instruction *I = dyn_cast<Instruction>(Condition)) { 740 Value *SimpleVal = 741 ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI); 742 if (SimpleVal) { 743 I->replaceAllUsesWith(SimpleVal); 744 if (isInstructionTriviallyDead(I, TLI)) 745 I->eraseFromParent(); 746 Condition = SimpleVal; 747 } 748 } 749 750 // If the terminator is branching on an undef, we can pick any of the 751 // successors to branch to. Let GetBestDestForJumpOnUndef decide. 752 if (isa<UndefValue>(Condition)) { 753 unsigned BestSucc = GetBestDestForJumpOnUndef(BB); 754 755 // Fold the branch/switch. 756 TerminatorInst *BBTerm = BB->getTerminator(); 757 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) { 758 if (i == BestSucc) continue; 759 BBTerm->getSuccessor(i)->removePredecessor(BB, true); 760 } 761 762 DEBUG(dbgs() << " In block '" << BB->getName() 763 << "' folding undef terminator: " << *BBTerm << '\n'); 764 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm); 765 BBTerm->eraseFromParent(); 766 return true; 767 } 768 769 // If the terminator of this block is branching on a constant, simplify the 770 // terminator to an unconditional branch. This can occur due to threading in 771 // other blocks. 772 if (getKnownConstant(Condition, Preference)) { 773 DEBUG(dbgs() << " In block '" << BB->getName() 774 << "' folding terminator: " << *BB->getTerminator() << '\n'); 775 ++NumFolds; 776 ConstantFoldTerminator(BB, true); 777 return true; 778 } 779 780 Instruction *CondInst = dyn_cast<Instruction>(Condition); 781 782 // All the rest of our checks depend on the condition being an instruction. 783 if (!CondInst) { 784 // FIXME: Unify this with code below. 785 if (ProcessThreadableEdges(Condition, BB, Preference, Terminator)) 786 return true; 787 return false; 788 } 789 790 791 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) { 792 // If we're branching on a conditional, LVI might be able to determine 793 // it's value at the branch instruction. We only handle comparisons 794 // against a constant at this time. 795 // TODO: This should be extended to handle switches as well. 796 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 797 Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1)); 798 if (CondBr && CondConst && CondBr->isConditional()) { 799 LazyValueInfo::Tristate Ret = 800 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0), 801 CondConst, CondBr); 802 if (Ret != LazyValueInfo::Unknown) { 803 unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0; 804 unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1; 805 CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true); 806 BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr); 807 CondBr->eraseFromParent(); 808 if (CondCmp->use_empty()) 809 CondCmp->eraseFromParent(); 810 else if (CondCmp->getParent() == BB) { 811 // If the fact we just learned is true for all uses of the 812 // condition, replace it with a constant value 813 auto *CI = Ret == LazyValueInfo::True ? 814 ConstantInt::getTrue(CondCmp->getType()) : 815 ConstantInt::getFalse(CondCmp->getType()); 816 CondCmp->replaceAllUsesWith(CI); 817 CondCmp->eraseFromParent(); 818 } 819 return true; 820 } 821 } 822 823 if (CondBr && CondConst && TryToUnfoldSelect(CondCmp, BB)) 824 return true; 825 } 826 827 // Check for some cases that are worth simplifying. Right now we want to look 828 // for loads that are used by a switch or by the condition for the branch. If 829 // we see one, check to see if it's partially redundant. If so, insert a PHI 830 // which can then be used to thread the values. 831 // 832 Value *SimplifyValue = CondInst; 833 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue)) 834 if (isa<Constant>(CondCmp->getOperand(1))) 835 SimplifyValue = CondCmp->getOperand(0); 836 837 // TODO: There are other places where load PRE would be profitable, such as 838 // more complex comparisons. 839 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue)) 840 if (SimplifyPartiallyRedundantLoad(LI)) 841 return true; 842 843 844 // Handle a variety of cases where we are branching on something derived from 845 // a PHI node in the current block. If we can prove that any predecessors 846 // compute a predictable value based on a PHI node, thread those predecessors. 847 // 848 if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator)) 849 return true; 850 851 // If this is an otherwise-unfoldable branch on a phi node in the current 852 // block, see if we can simplify. 853 if (PHINode *PN = dyn_cast<PHINode>(CondInst)) 854 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 855 return ProcessBranchOnPHI(PN); 856 857 858 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify. 859 if (CondInst->getOpcode() == Instruction::Xor && 860 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator())) 861 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst)); 862 863 // Search for a stronger dominating condition that can be used to simplify a 864 // conditional branch leaving BB. 865 if (ProcessImpliedCondition(BB)) 866 return true; 867 868 return false; 869 } 870 871 bool JumpThreadingPass::ProcessImpliedCondition(BasicBlock *BB) { 872 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 873 if (!BI || !BI->isConditional()) 874 return false; 875 876 Value *Cond = BI->getCondition(); 877 BasicBlock *CurrentBB = BB; 878 BasicBlock *CurrentPred = BB->getSinglePredecessor(); 879 unsigned Iter = 0; 880 881 auto &DL = BB->getModule()->getDataLayout(); 882 883 while (CurrentPred && Iter++ < ImplicationSearchThreshold) { 884 auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator()); 885 if (!PBI || !PBI->isConditional()) 886 return false; 887 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB) 888 return false; 889 890 bool FalseDest = PBI->getSuccessor(1) == CurrentBB; 891 Optional<bool> Implication = 892 isImpliedCondition(PBI->getCondition(), Cond, DL, FalseDest); 893 if (Implication) { 894 BI->getSuccessor(*Implication ? 1 : 0)->removePredecessor(BB); 895 BranchInst::Create(BI->getSuccessor(*Implication ? 0 : 1), BI); 896 BI->eraseFromParent(); 897 return true; 898 } 899 CurrentBB = CurrentPred; 900 CurrentPred = CurrentBB->getSinglePredecessor(); 901 } 902 903 return false; 904 } 905 906 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant 907 /// load instruction, eliminate it by replacing it with a PHI node. This is an 908 /// important optimization that encourages jump threading, and needs to be run 909 /// interlaced with other jump threading tasks. 910 bool JumpThreadingPass::SimplifyPartiallyRedundantLoad(LoadInst *LI) { 911 // Don't hack volatile and ordered loads. 912 if (!LI->isUnordered()) return false; 913 914 // If the load is defined in a block with exactly one predecessor, it can't be 915 // partially redundant. 916 BasicBlock *LoadBB = LI->getParent(); 917 if (LoadBB->getSinglePredecessor()) 918 return false; 919 920 // If the load is defined in an EH pad, it can't be partially redundant, 921 // because the edges between the invoke and the EH pad cannot have other 922 // instructions between them. 923 if (LoadBB->isEHPad()) 924 return false; 925 926 Value *LoadedPtr = LI->getOperand(0); 927 928 // If the loaded operand is defined in the LoadBB, it can't be available. 929 // TODO: Could do simple PHI translation, that would be fun :) 930 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr)) 931 if (PtrOp->getParent() == LoadBB) 932 return false; 933 934 // Scan a few instructions up from the load, to see if it is obviously live at 935 // the entry to its block. 936 BasicBlock::iterator BBIt(LI); 937 bool IsLoadCSE; 938 if (Value *AvailableVal = 939 FindAvailableLoadedValue(LI, LoadBB, BBIt, DefMaxInstsToScan, nullptr, &IsLoadCSE)) { 940 // If the value of the load is locally available within the block, just use 941 // it. This frequently occurs for reg2mem'd allocas. 942 943 if (IsLoadCSE) { 944 LoadInst *NLI = cast<LoadInst>(AvailableVal); 945 combineMetadataForCSE(NLI, LI); 946 }; 947 948 // If the returned value is the load itself, replace with an undef. This can 949 // only happen in dead loops. 950 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType()); 951 if (AvailableVal->getType() != LI->getType()) 952 AvailableVal = 953 CastInst::CreateBitOrPointerCast(AvailableVal, LI->getType(), "", LI); 954 LI->replaceAllUsesWith(AvailableVal); 955 LI->eraseFromParent(); 956 return true; 957 } 958 959 // Otherwise, if we scanned the whole block and got to the top of the block, 960 // we know the block is locally transparent to the load. If not, something 961 // might clobber its value. 962 if (BBIt != LoadBB->begin()) 963 return false; 964 965 // If all of the loads and stores that feed the value have the same AA tags, 966 // then we can propagate them onto any newly inserted loads. 967 AAMDNodes AATags; 968 LI->getAAMetadata(AATags); 969 970 SmallPtrSet<BasicBlock*, 8> PredsScanned; 971 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy; 972 AvailablePredsTy AvailablePreds; 973 BasicBlock *OneUnavailablePred = nullptr; 974 SmallVector<LoadInst*, 8> CSELoads; 975 976 // If we got here, the loaded value is transparent through to the start of the 977 // block. Check to see if it is available in any of the predecessor blocks. 978 for (BasicBlock *PredBB : predecessors(LoadBB)) { 979 // If we already scanned this predecessor, skip it. 980 if (!PredsScanned.insert(PredBB).second) 981 continue; 982 983 // Scan the predecessor to see if the value is available in the pred. 984 BBIt = PredBB->end(); 985 unsigned NumScanedInst = 0; 986 Value *PredAvailable = 987 FindAvailableLoadedValue(LI, PredBB, BBIt, DefMaxInstsToScan, nullptr, 988 &IsLoadCSE, &NumScanedInst); 989 990 // If PredBB has a single predecessor, continue scanning through the single 991 // precessor. 992 BasicBlock *SinglePredBB = PredBB; 993 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() && 994 NumScanedInst < DefMaxInstsToScan) { 995 SinglePredBB = SinglePredBB->getSinglePredecessor(); 996 if (SinglePredBB) { 997 BBIt = SinglePredBB->end(); 998 PredAvailable = FindAvailableLoadedValue( 999 LI, SinglePredBB, BBIt, (DefMaxInstsToScan - NumScanedInst), 1000 nullptr, &IsLoadCSE, &NumScanedInst); 1001 } 1002 } 1003 1004 if (!PredAvailable) { 1005 OneUnavailablePred = PredBB; 1006 continue; 1007 } 1008 1009 if (IsLoadCSE) 1010 CSELoads.push_back(cast<LoadInst>(PredAvailable)); 1011 1012 // If so, this load is partially redundant. Remember this info so that we 1013 // can create a PHI node. 1014 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable)); 1015 } 1016 1017 // If the loaded value isn't available in any predecessor, it isn't partially 1018 // redundant. 1019 if (AvailablePreds.empty()) return false; 1020 1021 // Okay, the loaded value is available in at least one (and maybe all!) 1022 // predecessors. If the value is unavailable in more than one unique 1023 // predecessor, we want to insert a merge block for those common predecessors. 1024 // This ensures that we only have to insert one reload, thus not increasing 1025 // code size. 1026 BasicBlock *UnavailablePred = nullptr; 1027 1028 // If there is exactly one predecessor where the value is unavailable, the 1029 // already computed 'OneUnavailablePred' block is it. If it ends in an 1030 // unconditional branch, we know that it isn't a critical edge. 1031 if (PredsScanned.size() == AvailablePreds.size()+1 && 1032 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) { 1033 UnavailablePred = OneUnavailablePred; 1034 } else if (PredsScanned.size() != AvailablePreds.size()) { 1035 // Otherwise, we had multiple unavailable predecessors or we had a critical 1036 // edge from the one. 1037 SmallVector<BasicBlock*, 8> PredsToSplit; 1038 SmallPtrSet<BasicBlock*, 8> AvailablePredSet; 1039 1040 for (const auto &AvailablePred : AvailablePreds) 1041 AvailablePredSet.insert(AvailablePred.first); 1042 1043 // Add all the unavailable predecessors to the PredsToSplit list. 1044 for (BasicBlock *P : predecessors(LoadBB)) { 1045 // If the predecessor is an indirect goto, we can't split the edge. 1046 if (isa<IndirectBrInst>(P->getTerminator())) 1047 return false; 1048 1049 if (!AvailablePredSet.count(P)) 1050 PredsToSplit.push_back(P); 1051 } 1052 1053 // Split them out to their own block. 1054 UnavailablePred = SplitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split"); 1055 } 1056 1057 // If the value isn't available in all predecessors, then there will be 1058 // exactly one where it isn't available. Insert a load on that edge and add 1059 // it to the AvailablePreds list. 1060 if (UnavailablePred) { 1061 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 && 1062 "Can't handle critical edge here!"); 1063 LoadInst *NewVal = 1064 new LoadInst(LoadedPtr, LI->getName() + ".pr", false, 1065 LI->getAlignment(), LI->getOrdering(), LI->getSynchScope(), 1066 UnavailablePred->getTerminator()); 1067 NewVal->setDebugLoc(LI->getDebugLoc()); 1068 if (AATags) 1069 NewVal->setAAMetadata(AATags); 1070 1071 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal)); 1072 } 1073 1074 // Now we know that each predecessor of this block has a value in 1075 // AvailablePreds, sort them for efficient access as we're walking the preds. 1076 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end()); 1077 1078 // Create a PHI node at the start of the block for the PRE'd load value. 1079 pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB); 1080 PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "", 1081 &LoadBB->front()); 1082 PN->takeName(LI); 1083 PN->setDebugLoc(LI->getDebugLoc()); 1084 1085 // Insert new entries into the PHI for each predecessor. A single block may 1086 // have multiple entries here. 1087 for (pred_iterator PI = PB; PI != PE; ++PI) { 1088 BasicBlock *P = *PI; 1089 AvailablePredsTy::iterator I = 1090 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(), 1091 std::make_pair(P, (Value*)nullptr)); 1092 1093 assert(I != AvailablePreds.end() && I->first == P && 1094 "Didn't find entry for predecessor!"); 1095 1096 // If we have an available predecessor but it requires casting, insert the 1097 // cast in the predecessor and use the cast. Note that we have to update the 1098 // AvailablePreds vector as we go so that all of the PHI entries for this 1099 // predecessor use the same bitcast. 1100 Value *&PredV = I->second; 1101 if (PredV->getType() != LI->getType()) 1102 PredV = CastInst::CreateBitOrPointerCast(PredV, LI->getType(), "", 1103 P->getTerminator()); 1104 1105 PN->addIncoming(PredV, I->first); 1106 } 1107 1108 for (LoadInst *PredLI : CSELoads) { 1109 combineMetadataForCSE(PredLI, LI); 1110 } 1111 1112 LI->replaceAllUsesWith(PN); 1113 LI->eraseFromParent(); 1114 1115 return true; 1116 } 1117 1118 /// FindMostPopularDest - The specified list contains multiple possible 1119 /// threadable destinations. Pick the one that occurs the most frequently in 1120 /// the list. 1121 static BasicBlock * 1122 FindMostPopularDest(BasicBlock *BB, 1123 const SmallVectorImpl<std::pair<BasicBlock*, 1124 BasicBlock*> > &PredToDestList) { 1125 assert(!PredToDestList.empty()); 1126 1127 // Determine popularity. If there are multiple possible destinations, we 1128 // explicitly choose to ignore 'undef' destinations. We prefer to thread 1129 // blocks with known and real destinations to threading undef. We'll handle 1130 // them later if interesting. 1131 DenseMap<BasicBlock*, unsigned> DestPopularity; 1132 for (const auto &PredToDest : PredToDestList) 1133 if (PredToDest.second) 1134 DestPopularity[PredToDest.second]++; 1135 1136 // Find the most popular dest. 1137 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin(); 1138 BasicBlock *MostPopularDest = DPI->first; 1139 unsigned Popularity = DPI->second; 1140 SmallVector<BasicBlock*, 4> SamePopularity; 1141 1142 for (++DPI; DPI != DestPopularity.end(); ++DPI) { 1143 // If the popularity of this entry isn't higher than the popularity we've 1144 // seen so far, ignore it. 1145 if (DPI->second < Popularity) 1146 ; // ignore. 1147 else if (DPI->second == Popularity) { 1148 // If it is the same as what we've seen so far, keep track of it. 1149 SamePopularity.push_back(DPI->first); 1150 } else { 1151 // If it is more popular, remember it. 1152 SamePopularity.clear(); 1153 MostPopularDest = DPI->first; 1154 Popularity = DPI->second; 1155 } 1156 } 1157 1158 // Okay, now we know the most popular destination. If there is more than one 1159 // destination, we need to determine one. This is arbitrary, but we need 1160 // to make a deterministic decision. Pick the first one that appears in the 1161 // successor list. 1162 if (!SamePopularity.empty()) { 1163 SamePopularity.push_back(MostPopularDest); 1164 TerminatorInst *TI = BB->getTerminator(); 1165 for (unsigned i = 0; ; ++i) { 1166 assert(i != TI->getNumSuccessors() && "Didn't find any successor!"); 1167 1168 if (!is_contained(SamePopularity, TI->getSuccessor(i))) 1169 continue; 1170 1171 MostPopularDest = TI->getSuccessor(i); 1172 break; 1173 } 1174 } 1175 1176 // Okay, we have finally picked the most popular destination. 1177 return MostPopularDest; 1178 } 1179 1180 bool JumpThreadingPass::ProcessThreadableEdges(Value *Cond, BasicBlock *BB, 1181 ConstantPreference Preference, 1182 Instruction *CxtI) { 1183 // If threading this would thread across a loop header, don't even try to 1184 // thread the edge. 1185 if (LoopHeaders.count(BB)) 1186 return false; 1187 1188 PredValueInfoTy PredValues; 1189 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI)) 1190 return false; 1191 1192 assert(!PredValues.empty() && 1193 "ComputeValueKnownInPredecessors returned true with no values"); 1194 1195 DEBUG(dbgs() << "IN BB: " << *BB; 1196 for (const auto &PredValue : PredValues) { 1197 dbgs() << " BB '" << BB->getName() << "': FOUND condition = " 1198 << *PredValue.first 1199 << " for pred '" << PredValue.second->getName() << "'.\n"; 1200 }); 1201 1202 // Decide what we want to thread through. Convert our list of known values to 1203 // a list of known destinations for each pred. This also discards duplicate 1204 // predecessors and keeps track of the undefined inputs (which are represented 1205 // as a null dest in the PredToDestList). 1206 SmallPtrSet<BasicBlock*, 16> SeenPreds; 1207 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList; 1208 1209 BasicBlock *OnlyDest = nullptr; 1210 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL; 1211 1212 for (const auto &PredValue : PredValues) { 1213 BasicBlock *Pred = PredValue.second; 1214 if (!SeenPreds.insert(Pred).second) 1215 continue; // Duplicate predecessor entry. 1216 1217 // If the predecessor ends with an indirect goto, we can't change its 1218 // destination. 1219 if (isa<IndirectBrInst>(Pred->getTerminator())) 1220 continue; 1221 1222 Constant *Val = PredValue.first; 1223 1224 BasicBlock *DestBB; 1225 if (isa<UndefValue>(Val)) 1226 DestBB = nullptr; 1227 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) 1228 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero()); 1229 else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 1230 DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor(); 1231 } else { 1232 assert(isa<IndirectBrInst>(BB->getTerminator()) 1233 && "Unexpected terminator"); 1234 DestBB = cast<BlockAddress>(Val)->getBasicBlock(); 1235 } 1236 1237 // If we have exactly one destination, remember it for efficiency below. 1238 if (PredToDestList.empty()) 1239 OnlyDest = DestBB; 1240 else if (OnlyDest != DestBB) 1241 OnlyDest = MultipleDestSentinel; 1242 1243 PredToDestList.push_back(std::make_pair(Pred, DestBB)); 1244 } 1245 1246 // If all edges were unthreadable, we fail. 1247 if (PredToDestList.empty()) 1248 return false; 1249 1250 // Determine which is the most common successor. If we have many inputs and 1251 // this block is a switch, we want to start by threading the batch that goes 1252 // to the most popular destination first. If we only know about one 1253 // threadable destination (the common case) we can avoid this. 1254 BasicBlock *MostPopularDest = OnlyDest; 1255 1256 if (MostPopularDest == MultipleDestSentinel) 1257 MostPopularDest = FindMostPopularDest(BB, PredToDestList); 1258 1259 // Now that we know what the most popular destination is, factor all 1260 // predecessors that will jump to it into a single predecessor. 1261 SmallVector<BasicBlock*, 16> PredsToFactor; 1262 for (const auto &PredToDest : PredToDestList) 1263 if (PredToDest.second == MostPopularDest) { 1264 BasicBlock *Pred = PredToDest.first; 1265 1266 // This predecessor may be a switch or something else that has multiple 1267 // edges to the block. Factor each of these edges by listing them 1268 // according to # occurrences in PredsToFactor. 1269 for (BasicBlock *Succ : successors(Pred)) 1270 if (Succ == BB) 1271 PredsToFactor.push_back(Pred); 1272 } 1273 1274 // If the threadable edges are branching on an undefined value, we get to pick 1275 // the destination that these predecessors should get to. 1276 if (!MostPopularDest) 1277 MostPopularDest = BB->getTerminator()-> 1278 getSuccessor(GetBestDestForJumpOnUndef(BB)); 1279 1280 // Ok, try to thread it! 1281 return ThreadEdge(BB, PredsToFactor, MostPopularDest); 1282 } 1283 1284 /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on 1285 /// a PHI node in the current block. See if there are any simplifications we 1286 /// can do based on inputs to the phi node. 1287 /// 1288 bool JumpThreadingPass::ProcessBranchOnPHI(PHINode *PN) { 1289 BasicBlock *BB = PN->getParent(); 1290 1291 // TODO: We could make use of this to do it once for blocks with common PHI 1292 // values. 1293 SmallVector<BasicBlock*, 1> PredBBs; 1294 PredBBs.resize(1); 1295 1296 // If any of the predecessor blocks end in an unconditional branch, we can 1297 // *duplicate* the conditional branch into that block in order to further 1298 // encourage jump threading and to eliminate cases where we have branch on a 1299 // phi of an icmp (branch on icmp is much better). 1300 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1301 BasicBlock *PredBB = PN->getIncomingBlock(i); 1302 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator())) 1303 if (PredBr->isUnconditional()) { 1304 PredBBs[0] = PredBB; 1305 // Try to duplicate BB into PredBB. 1306 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs)) 1307 return true; 1308 } 1309 } 1310 1311 return false; 1312 } 1313 1314 /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on 1315 /// a xor instruction in the current block. See if there are any 1316 /// simplifications we can do based on inputs to the xor. 1317 /// 1318 bool JumpThreadingPass::ProcessBranchOnXOR(BinaryOperator *BO) { 1319 BasicBlock *BB = BO->getParent(); 1320 1321 // If either the LHS or RHS of the xor is a constant, don't do this 1322 // optimization. 1323 if (isa<ConstantInt>(BO->getOperand(0)) || 1324 isa<ConstantInt>(BO->getOperand(1))) 1325 return false; 1326 1327 // If the first instruction in BB isn't a phi, we won't be able to infer 1328 // anything special about any particular predecessor. 1329 if (!isa<PHINode>(BB->front())) 1330 return false; 1331 1332 // If this BB is a landing pad, we won't be able to split the edge into it. 1333 if (BB->isEHPad()) 1334 return false; 1335 1336 // If we have a xor as the branch input to this block, and we know that the 1337 // LHS or RHS of the xor in any predecessor is true/false, then we can clone 1338 // the condition into the predecessor and fix that value to true, saving some 1339 // logical ops on that path and encouraging other paths to simplify. 1340 // 1341 // This copies something like this: 1342 // 1343 // BB: 1344 // %X = phi i1 [1], [%X'] 1345 // %Y = icmp eq i32 %A, %B 1346 // %Z = xor i1 %X, %Y 1347 // br i1 %Z, ... 1348 // 1349 // Into: 1350 // BB': 1351 // %Y = icmp ne i32 %A, %B 1352 // br i1 %Y, ... 1353 1354 PredValueInfoTy XorOpValues; 1355 bool isLHS = true; 1356 if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues, 1357 WantInteger, BO)) { 1358 assert(XorOpValues.empty()); 1359 if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues, 1360 WantInteger, BO)) 1361 return false; 1362 isLHS = false; 1363 } 1364 1365 assert(!XorOpValues.empty() && 1366 "ComputeValueKnownInPredecessors returned true with no values"); 1367 1368 // Scan the information to see which is most popular: true or false. The 1369 // predecessors can be of the set true, false, or undef. 1370 unsigned NumTrue = 0, NumFalse = 0; 1371 for (const auto &XorOpValue : XorOpValues) { 1372 if (isa<UndefValue>(XorOpValue.first)) 1373 // Ignore undefs for the count. 1374 continue; 1375 if (cast<ConstantInt>(XorOpValue.first)->isZero()) 1376 ++NumFalse; 1377 else 1378 ++NumTrue; 1379 } 1380 1381 // Determine which value to split on, true, false, or undef if neither. 1382 ConstantInt *SplitVal = nullptr; 1383 if (NumTrue > NumFalse) 1384 SplitVal = ConstantInt::getTrue(BB->getContext()); 1385 else if (NumTrue != 0 || NumFalse != 0) 1386 SplitVal = ConstantInt::getFalse(BB->getContext()); 1387 1388 // Collect all of the blocks that this can be folded into so that we can 1389 // factor this once and clone it once. 1390 SmallVector<BasicBlock*, 8> BlocksToFoldInto; 1391 for (const auto &XorOpValue : XorOpValues) { 1392 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first)) 1393 continue; 1394 1395 BlocksToFoldInto.push_back(XorOpValue.second); 1396 } 1397 1398 // If we inferred a value for all of the predecessors, then duplication won't 1399 // help us. However, we can just replace the LHS or RHS with the constant. 1400 if (BlocksToFoldInto.size() == 1401 cast<PHINode>(BB->front()).getNumIncomingValues()) { 1402 if (!SplitVal) { 1403 // If all preds provide undef, just nuke the xor, because it is undef too. 1404 BO->replaceAllUsesWith(UndefValue::get(BO->getType())); 1405 BO->eraseFromParent(); 1406 } else if (SplitVal->isZero()) { 1407 // If all preds provide 0, replace the xor with the other input. 1408 BO->replaceAllUsesWith(BO->getOperand(isLHS)); 1409 BO->eraseFromParent(); 1410 } else { 1411 // If all preds provide 1, set the computed value to 1. 1412 BO->setOperand(!isLHS, SplitVal); 1413 } 1414 1415 return true; 1416 } 1417 1418 // Try to duplicate BB into PredBB. 1419 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto); 1420 } 1421 1422 1423 /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new 1424 /// predecessor to the PHIBB block. If it has PHI nodes, add entries for 1425 /// NewPred using the entries from OldPred (suitably mapped). 1426 static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, 1427 BasicBlock *OldPred, 1428 BasicBlock *NewPred, 1429 DenseMap<Instruction*, Value*> &ValueMap) { 1430 for (BasicBlock::iterator PNI = PHIBB->begin(); 1431 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) { 1432 // Ok, we have a PHI node. Figure out what the incoming value was for the 1433 // DestBlock. 1434 Value *IV = PN->getIncomingValueForBlock(OldPred); 1435 1436 // Remap the value if necessary. 1437 if (Instruction *Inst = dyn_cast<Instruction>(IV)) { 1438 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst); 1439 if (I != ValueMap.end()) 1440 IV = I->second; 1441 } 1442 1443 PN->addIncoming(IV, NewPred); 1444 } 1445 } 1446 1447 /// ThreadEdge - We have decided that it is safe and profitable to factor the 1448 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB 1449 /// across BB. Transform the IR to reflect this change. 1450 bool JumpThreadingPass::ThreadEdge(BasicBlock *BB, 1451 const SmallVectorImpl<BasicBlock *> &PredBBs, 1452 BasicBlock *SuccBB) { 1453 // If threading to the same block as we come from, we would infinite loop. 1454 if (SuccBB == BB) { 1455 DEBUG(dbgs() << " Not threading across BB '" << BB->getName() 1456 << "' - would thread to self!\n"); 1457 return false; 1458 } 1459 1460 // If threading this would thread across a loop header, don't thread the edge. 1461 // See the comments above FindLoopHeaders for justifications and caveats. 1462 if (LoopHeaders.count(BB)) { 1463 DEBUG(dbgs() << " Not threading across loop header BB '" << BB->getName() 1464 << "' to dest BB '" << SuccBB->getName() 1465 << "' - it might create an irreducible loop!\n"); 1466 return false; 1467 } 1468 1469 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, BBDupThreshold); 1470 if (JumpThreadCost > BBDupThreshold) { 1471 DEBUG(dbgs() << " Not threading BB '" << BB->getName() 1472 << "' - Cost is too high: " << JumpThreadCost << "\n"); 1473 return false; 1474 } 1475 1476 // And finally, do it! Start by factoring the predecessors if needed. 1477 BasicBlock *PredBB; 1478 if (PredBBs.size() == 1) 1479 PredBB = PredBBs[0]; 1480 else { 1481 DEBUG(dbgs() << " Factoring out " << PredBBs.size() 1482 << " common predecessors.\n"); 1483 PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm"); 1484 } 1485 1486 // And finally, do it! 1487 DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() << "' to '" 1488 << SuccBB->getName() << "' with cost: " << JumpThreadCost 1489 << ", across block:\n " 1490 << *BB << "\n"); 1491 1492 LVI->threadEdge(PredBB, BB, SuccBB); 1493 1494 // We are going to have to map operands from the original BB block to the new 1495 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to 1496 // account for entry from PredBB. 1497 DenseMap<Instruction*, Value*> ValueMapping; 1498 1499 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), 1500 BB->getName()+".thread", 1501 BB->getParent(), BB); 1502 NewBB->moveAfter(PredBB); 1503 1504 // Set the block frequency of NewBB. 1505 if (HasProfileData) { 1506 auto NewBBFreq = 1507 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB); 1508 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency()); 1509 } 1510 1511 BasicBlock::iterator BI = BB->begin(); 1512 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 1513 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 1514 1515 // Clone the non-phi instructions of BB into NewBB, keeping track of the 1516 // mapping and using it to remap operands in the cloned instructions. 1517 for (; !isa<TerminatorInst>(BI); ++BI) { 1518 Instruction *New = BI->clone(); 1519 New->setName(BI->getName()); 1520 NewBB->getInstList().push_back(New); 1521 ValueMapping[&*BI] = New; 1522 1523 // Remap operands to patch up intra-block references. 1524 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 1525 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 1526 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 1527 if (I != ValueMapping.end()) 1528 New->setOperand(i, I->second); 1529 } 1530 } 1531 1532 // We didn't copy the terminator from BB over to NewBB, because there is now 1533 // an unconditional jump to SuccBB. Insert the unconditional jump. 1534 BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB); 1535 NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc()); 1536 1537 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the 1538 // PHI nodes for NewBB now. 1539 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping); 1540 1541 // If there were values defined in BB that are used outside the block, then we 1542 // now have to update all uses of the value to use either the original value, 1543 // the cloned value, or some PHI derived value. This can require arbitrary 1544 // PHI insertion, of which we are prepared to do, clean these up now. 1545 SSAUpdater SSAUpdate; 1546 SmallVector<Use*, 16> UsesToRename; 1547 for (Instruction &I : *BB) { 1548 // Scan all uses of this instruction to see if it is used outside of its 1549 // block, and if so, record them in UsesToRename. 1550 for (Use &U : I.uses()) { 1551 Instruction *User = cast<Instruction>(U.getUser()); 1552 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 1553 if (UserPN->getIncomingBlock(U) == BB) 1554 continue; 1555 } else if (User->getParent() == BB) 1556 continue; 1557 1558 UsesToRename.push_back(&U); 1559 } 1560 1561 // If there are no uses outside the block, we're done with this instruction. 1562 if (UsesToRename.empty()) 1563 continue; 1564 1565 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n"); 1566 1567 // We found a use of I outside of BB. Rename all uses of I that are outside 1568 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 1569 // with the two values we know. 1570 SSAUpdate.Initialize(I.getType(), I.getName()); 1571 SSAUpdate.AddAvailableValue(BB, &I); 1572 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]); 1573 1574 while (!UsesToRename.empty()) 1575 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 1576 DEBUG(dbgs() << "\n"); 1577 } 1578 1579 1580 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to 1581 // NewBB instead of BB. This eliminates predecessors from BB, which requires 1582 // us to simplify any PHI nodes in BB. 1583 TerminatorInst *PredTerm = PredBB->getTerminator(); 1584 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) 1585 if (PredTerm->getSuccessor(i) == BB) { 1586 BB->removePredecessor(PredBB, true); 1587 PredTerm->setSuccessor(i, NewBB); 1588 } 1589 1590 // At this point, the IR is fully up to date and consistent. Do a quick scan 1591 // over the new instructions and zap any that are constants or dead. This 1592 // frequently happens because of phi translation. 1593 SimplifyInstructionsInBlock(NewBB, TLI); 1594 1595 // Update the edge weight from BB to SuccBB, which should be less than before. 1596 UpdateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB); 1597 1598 // Threaded an edge! 1599 ++NumThreads; 1600 return true; 1601 } 1602 1603 /// Create a new basic block that will be the predecessor of BB and successor of 1604 /// all blocks in Preds. When profile data is available, update the frequency of 1605 /// this new block. 1606 BasicBlock *JumpThreadingPass::SplitBlockPreds(BasicBlock *BB, 1607 ArrayRef<BasicBlock *> Preds, 1608 const char *Suffix) { 1609 // Collect the frequencies of all predecessors of BB, which will be used to 1610 // update the edge weight on BB->SuccBB. 1611 BlockFrequency PredBBFreq(0); 1612 if (HasProfileData) 1613 for (auto Pred : Preds) 1614 PredBBFreq += BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB); 1615 1616 BasicBlock *PredBB = SplitBlockPredecessors(BB, Preds, Suffix); 1617 1618 // Set the block frequency of the newly created PredBB, which is the sum of 1619 // frequencies of Preds. 1620 if (HasProfileData) 1621 BFI->setBlockFreq(PredBB, PredBBFreq.getFrequency()); 1622 return PredBB; 1623 } 1624 1625 bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) { 1626 const TerminatorInst *TI = BB->getTerminator(); 1627 assert(TI->getNumSuccessors() > 1 && "not a split"); 1628 1629 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof); 1630 if (!WeightsNode) 1631 return false; 1632 1633 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0)); 1634 if (MDName->getString() != "branch_weights") 1635 return false; 1636 1637 // Ensure there are weights for all of the successors. Note that the first 1638 // operand to the metadata node is a name, not a weight. 1639 return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1; 1640 } 1641 1642 /// Update the block frequency of BB and branch weight and the metadata on the 1643 /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 - 1644 /// Freq(PredBB->BB) / Freq(BB->SuccBB). 1645 void JumpThreadingPass::UpdateBlockFreqAndEdgeWeight(BasicBlock *PredBB, 1646 BasicBlock *BB, 1647 BasicBlock *NewBB, 1648 BasicBlock *SuccBB) { 1649 if (!HasProfileData) 1650 return; 1651 1652 assert(BFI && BPI && "BFI & BPI should have been created here"); 1653 1654 // As the edge from PredBB to BB is deleted, we have to update the block 1655 // frequency of BB. 1656 auto BBOrigFreq = BFI->getBlockFreq(BB); 1657 auto NewBBFreq = BFI->getBlockFreq(NewBB); 1658 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB); 1659 auto BBNewFreq = BBOrigFreq - NewBBFreq; 1660 BFI->setBlockFreq(BB, BBNewFreq.getFrequency()); 1661 1662 // Collect updated outgoing edges' frequencies from BB and use them to update 1663 // edge probabilities. 1664 SmallVector<uint64_t, 4> BBSuccFreq; 1665 for (BasicBlock *Succ : successors(BB)) { 1666 auto SuccFreq = (Succ == SuccBB) 1667 ? BB2SuccBBFreq - NewBBFreq 1668 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ); 1669 BBSuccFreq.push_back(SuccFreq.getFrequency()); 1670 } 1671 1672 uint64_t MaxBBSuccFreq = 1673 *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end()); 1674 1675 SmallVector<BranchProbability, 4> BBSuccProbs; 1676 if (MaxBBSuccFreq == 0) 1677 BBSuccProbs.assign(BBSuccFreq.size(), 1678 {1, static_cast<unsigned>(BBSuccFreq.size())}); 1679 else { 1680 for (uint64_t Freq : BBSuccFreq) 1681 BBSuccProbs.push_back( 1682 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq)); 1683 // Normalize edge probabilities so that they sum up to one. 1684 BranchProbability::normalizeProbabilities(BBSuccProbs.begin(), 1685 BBSuccProbs.end()); 1686 } 1687 1688 // Update edge probabilities in BPI. 1689 for (int I = 0, E = BBSuccProbs.size(); I < E; I++) 1690 BPI->setEdgeProbability(BB, I, BBSuccProbs[I]); 1691 1692 // Update the profile metadata as well. 1693 // 1694 // Don't do this if the profile of the transformed blocks was statically 1695 // estimated. (This could occur despite the function having an entry 1696 // frequency in completely cold parts of the CFG.) 1697 // 1698 // In this case we don't want to suggest to subsequent passes that the 1699 // calculated weights are fully consistent. Consider this graph: 1700 // 1701 // check_1 1702 // 50% / | 1703 // eq_1 | 50% 1704 // \ | 1705 // check_2 1706 // 50% / | 1707 // eq_2 | 50% 1708 // \ | 1709 // check_3 1710 // 50% / | 1711 // eq_3 | 50% 1712 // \ | 1713 // 1714 // Assuming the blocks check_* all compare the same value against 1, 2 and 3, 1715 // the overall probabilities are inconsistent; the total probability that the 1716 // value is either 1, 2 or 3 is 150%. 1717 // 1718 // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3 1719 // becomes 0%. This is even worse if the edge whose probability becomes 0% is 1720 // the loop exit edge. Then based solely on static estimation we would assume 1721 // the loop was extremely hot. 1722 // 1723 // FIXME this locally as well so that BPI and BFI are consistent as well. We 1724 // shouldn't make edges extremely likely or unlikely based solely on static 1725 // estimation. 1726 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) { 1727 SmallVector<uint32_t, 4> Weights; 1728 for (auto Prob : BBSuccProbs) 1729 Weights.push_back(Prob.getNumerator()); 1730 1731 auto TI = BB->getTerminator(); 1732 TI->setMetadata( 1733 LLVMContext::MD_prof, 1734 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights)); 1735 } 1736 } 1737 1738 /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch 1739 /// to BB which contains an i1 PHI node and a conditional branch on that PHI. 1740 /// If we can duplicate the contents of BB up into PredBB do so now, this 1741 /// improves the odds that the branch will be on an analyzable instruction like 1742 /// a compare. 1743 bool JumpThreadingPass::DuplicateCondBranchOnPHIIntoPred( 1744 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) { 1745 assert(!PredBBs.empty() && "Can't handle an empty set"); 1746 1747 // If BB is a loop header, then duplicating this block outside the loop would 1748 // cause us to transform this into an irreducible loop, don't do this. 1749 // See the comments above FindLoopHeaders for justifications and caveats. 1750 if (LoopHeaders.count(BB)) { 1751 DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName() 1752 << "' into predecessor block '" << PredBBs[0]->getName() 1753 << "' - it might create an irreducible loop!\n"); 1754 return false; 1755 } 1756 1757 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, BBDupThreshold); 1758 if (DuplicationCost > BBDupThreshold) { 1759 DEBUG(dbgs() << " Not duplicating BB '" << BB->getName() 1760 << "' - Cost is too high: " << DuplicationCost << "\n"); 1761 return false; 1762 } 1763 1764 // And finally, do it! Start by factoring the predecessors if needed. 1765 BasicBlock *PredBB; 1766 if (PredBBs.size() == 1) 1767 PredBB = PredBBs[0]; 1768 else { 1769 DEBUG(dbgs() << " Factoring out " << PredBBs.size() 1770 << " common predecessors.\n"); 1771 PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm"); 1772 } 1773 1774 // Okay, we decided to do this! Clone all the instructions in BB onto the end 1775 // of PredBB. 1776 DEBUG(dbgs() << " Duplicating block '" << BB->getName() << "' into end of '" 1777 << PredBB->getName() << "' to eliminate branch on phi. Cost: " 1778 << DuplicationCost << " block is:" << *BB << "\n"); 1779 1780 // Unless PredBB ends with an unconditional branch, split the edge so that we 1781 // can just clone the bits from BB into the end of the new PredBB. 1782 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator()); 1783 1784 if (!OldPredBranch || !OldPredBranch->isUnconditional()) { 1785 PredBB = SplitEdge(PredBB, BB); 1786 OldPredBranch = cast<BranchInst>(PredBB->getTerminator()); 1787 } 1788 1789 // We are going to have to map operands from the original BB block into the 1790 // PredBB block. Evaluate PHI nodes in BB. 1791 DenseMap<Instruction*, Value*> ValueMapping; 1792 1793 BasicBlock::iterator BI = BB->begin(); 1794 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 1795 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 1796 // Clone the non-phi instructions of BB into PredBB, keeping track of the 1797 // mapping and using it to remap operands in the cloned instructions. 1798 for (; BI != BB->end(); ++BI) { 1799 Instruction *New = BI->clone(); 1800 1801 // Remap operands to patch up intra-block references. 1802 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 1803 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 1804 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 1805 if (I != ValueMapping.end()) 1806 New->setOperand(i, I->second); 1807 } 1808 1809 // If this instruction can be simplified after the operands are updated, 1810 // just use the simplified value instead. This frequently happens due to 1811 // phi translation. 1812 if (Value *IV = 1813 SimplifyInstruction(New, BB->getModule()->getDataLayout())) { 1814 ValueMapping[&*BI] = IV; 1815 if (!New->mayHaveSideEffects()) { 1816 delete New; 1817 New = nullptr; 1818 } 1819 } else { 1820 ValueMapping[&*BI] = New; 1821 } 1822 if (New) { 1823 // Otherwise, insert the new instruction into the block. 1824 New->setName(BI->getName()); 1825 PredBB->getInstList().insert(OldPredBranch->getIterator(), New); 1826 } 1827 } 1828 1829 // Check to see if the targets of the branch had PHI nodes. If so, we need to 1830 // add entries to the PHI nodes for branch from PredBB now. 1831 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator()); 1832 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB, 1833 ValueMapping); 1834 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB, 1835 ValueMapping); 1836 1837 // If there were values defined in BB that are used outside the block, then we 1838 // now have to update all uses of the value to use either the original value, 1839 // the cloned value, or some PHI derived value. This can require arbitrary 1840 // PHI insertion, of which we are prepared to do, clean these up now. 1841 SSAUpdater SSAUpdate; 1842 SmallVector<Use*, 16> UsesToRename; 1843 for (Instruction &I : *BB) { 1844 // Scan all uses of this instruction to see if it is used outside of its 1845 // block, and if so, record them in UsesToRename. 1846 for (Use &U : I.uses()) { 1847 Instruction *User = cast<Instruction>(U.getUser()); 1848 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 1849 if (UserPN->getIncomingBlock(U) == BB) 1850 continue; 1851 } else if (User->getParent() == BB) 1852 continue; 1853 1854 UsesToRename.push_back(&U); 1855 } 1856 1857 // If there are no uses outside the block, we're done with this instruction. 1858 if (UsesToRename.empty()) 1859 continue; 1860 1861 DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n"); 1862 1863 // We found a use of I outside of BB. Rename all uses of I that are outside 1864 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 1865 // with the two values we know. 1866 SSAUpdate.Initialize(I.getType(), I.getName()); 1867 SSAUpdate.AddAvailableValue(BB, &I); 1868 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[&I]); 1869 1870 while (!UsesToRename.empty()) 1871 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 1872 DEBUG(dbgs() << "\n"); 1873 } 1874 1875 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge 1876 // that we nuked. 1877 BB->removePredecessor(PredBB, true); 1878 1879 // Remove the unconditional branch at the end of the PredBB block. 1880 OldPredBranch->eraseFromParent(); 1881 1882 ++NumDupes; 1883 return true; 1884 } 1885 1886 /// TryToUnfoldSelect - Look for blocks of the form 1887 /// bb1: 1888 /// %a = select 1889 /// br bb 1890 /// 1891 /// bb2: 1892 /// %p = phi [%a, %bb] ... 1893 /// %c = icmp %p 1894 /// br i1 %c 1895 /// 1896 /// And expand the select into a branch structure if one of its arms allows %c 1897 /// to be folded. This later enables threading from bb1 over bb2. 1898 bool JumpThreadingPass::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) { 1899 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator()); 1900 PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0)); 1901 Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1)); 1902 1903 if (!CondBr || !CondBr->isConditional() || !CondLHS || 1904 CondLHS->getParent() != BB) 1905 return false; 1906 1907 for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) { 1908 BasicBlock *Pred = CondLHS->getIncomingBlock(I); 1909 SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I)); 1910 1911 // Look if one of the incoming values is a select in the corresponding 1912 // predecessor. 1913 if (!SI || SI->getParent() != Pred || !SI->hasOneUse()) 1914 continue; 1915 1916 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator()); 1917 if (!PredTerm || !PredTerm->isUnconditional()) 1918 continue; 1919 1920 // Now check if one of the select values would allow us to constant fold the 1921 // terminator in BB. We don't do the transform if both sides fold, those 1922 // cases will be threaded in any case. 1923 LazyValueInfo::Tristate LHSFolds = 1924 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1), 1925 CondRHS, Pred, BB, CondCmp); 1926 LazyValueInfo::Tristate RHSFolds = 1927 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2), 1928 CondRHS, Pred, BB, CondCmp); 1929 if ((LHSFolds != LazyValueInfo::Unknown || 1930 RHSFolds != LazyValueInfo::Unknown) && 1931 LHSFolds != RHSFolds) { 1932 // Expand the select. 1933 // 1934 // Pred -- 1935 // | v 1936 // | NewBB 1937 // | | 1938 // |----- 1939 // v 1940 // BB 1941 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold", 1942 BB->getParent(), BB); 1943 // Move the unconditional branch to NewBB. 1944 PredTerm->removeFromParent(); 1945 NewBB->getInstList().insert(NewBB->end(), PredTerm); 1946 // Create a conditional branch and update PHI nodes. 1947 BranchInst::Create(NewBB, BB, SI->getCondition(), Pred); 1948 CondLHS->setIncomingValue(I, SI->getFalseValue()); 1949 CondLHS->addIncoming(SI->getTrueValue(), NewBB); 1950 // The select is now dead. 1951 SI->eraseFromParent(); 1952 1953 // Update any other PHI nodes in BB. 1954 for (BasicBlock::iterator BI = BB->begin(); 1955 PHINode *Phi = dyn_cast<PHINode>(BI); ++BI) 1956 if (Phi != CondLHS) 1957 Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB); 1958 return true; 1959 } 1960 } 1961 return false; 1962 } 1963 1964 /// TryToUnfoldSelectInCurrBB - Look for PHI/Select in the same BB of the form 1965 /// bb: 1966 /// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ... 1967 /// %s = select p, trueval, falseval 1968 /// 1969 /// And expand the select into a branch structure. This later enables 1970 /// jump-threading over bb in this pass. 1971 /// 1972 /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold 1973 /// select if the associated PHI has at least one constant. If the unfolded 1974 /// select is not jump-threaded, it will be folded again in the later 1975 /// optimizations. 1976 bool JumpThreadingPass::TryToUnfoldSelectInCurrBB(BasicBlock *BB) { 1977 // If threading this would thread across a loop header, don't thread the edge. 1978 // See the comments above FindLoopHeaders for justifications and caveats. 1979 if (LoopHeaders.count(BB)) 1980 return false; 1981 1982 // Look for a Phi/Select pair in the same basic block. The Phi feeds the 1983 // condition of the Select and at least one of the incoming values is a 1984 // constant. 1985 for (BasicBlock::iterator BI = BB->begin(); 1986 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) { 1987 unsigned NumPHIValues = PN->getNumIncomingValues(); 1988 if (NumPHIValues == 0 || !PN->hasOneUse()) 1989 continue; 1990 1991 SelectInst *SI = dyn_cast<SelectInst>(PN->user_back()); 1992 if (!SI || SI->getParent() != BB) 1993 continue; 1994 1995 Value *Cond = SI->getCondition(); 1996 if (!Cond || Cond != PN || !Cond->getType()->isIntegerTy(1)) 1997 continue; 1998 1999 bool HasConst = false; 2000 for (unsigned i = 0; i != NumPHIValues; ++i) { 2001 if (PN->getIncomingBlock(i) == BB) 2002 return false; 2003 if (isa<ConstantInt>(PN->getIncomingValue(i))) 2004 HasConst = true; 2005 } 2006 2007 if (HasConst) { 2008 // Expand the select. 2009 TerminatorInst *Term = 2010 SplitBlockAndInsertIfThen(SI->getCondition(), SI, false); 2011 PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI); 2012 NewPN->addIncoming(SI->getTrueValue(), Term->getParent()); 2013 NewPN->addIncoming(SI->getFalseValue(), BB); 2014 SI->replaceAllUsesWith(NewPN); 2015 SI->eraseFromParent(); 2016 return true; 2017 } 2018 } 2019 2020 return false; 2021 } 2022