JumpThreading.cpp revision b14b88a40ab12996c2982c4bc10fd35bb9a371d4
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#define DEBUG_TYPE "jump-threading" 15#include "llvm/Transforms/Scalar.h" 16#include "llvm/IntrinsicInst.h" 17#include "llvm/LLVMContext.h" 18#include "llvm/Pass.h" 19#include "llvm/Analysis/InstructionSimplify.h" 20#include "llvm/Transforms/Utils/BasicBlockUtils.h" 21#include "llvm/Transforms/Utils/Local.h" 22#include "llvm/Transforms/Utils/SSAUpdater.h" 23#include "llvm/Target/TargetData.h" 24#include "llvm/ADT/DenseMap.h" 25#include "llvm/ADT/Statistic.h" 26#include "llvm/ADT/STLExtras.h" 27#include "llvm/ADT/SmallPtrSet.h" 28#include "llvm/ADT/SmallSet.h" 29#include "llvm/Support/CommandLine.h" 30#include "llvm/Support/Debug.h" 31#include "llvm/Support/raw_ostream.h" 32using namespace llvm; 33 34STATISTIC(NumThreads, "Number of jumps threaded"); 35STATISTIC(NumFolds, "Number of terminators folded"); 36STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi"); 37 38static cl::opt<unsigned> 39Threshold("jump-threading-threshold", 40 cl::desc("Max block size to duplicate for jump threading"), 41 cl::init(6), cl::Hidden); 42 43namespace { 44 /// This pass performs 'jump threading', which looks at blocks that have 45 /// multiple predecessors and multiple successors. If one or more of the 46 /// predecessors of the block can be proven to always jump to one of the 47 /// successors, we forward the edge from the predecessor to the successor by 48 /// duplicating the contents of this block. 49 /// 50 /// An example of when this can occur is code like this: 51 /// 52 /// if () { ... 53 /// X = 4; 54 /// } 55 /// if (X < 3) { 56 /// 57 /// In this case, the unconditional branch at the end of the first if can be 58 /// revectored to the false side of the second if. 59 /// 60 class JumpThreading : public FunctionPass { 61 TargetData *TD; 62#ifdef NDEBUG 63 SmallPtrSet<BasicBlock*, 16> LoopHeaders; 64#else 65 SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders; 66#endif 67 public: 68 static char ID; // Pass identification 69 JumpThreading() : FunctionPass(&ID) {} 70 71 bool runOnFunction(Function &F); 72 void FindLoopHeaders(Function &F); 73 74 bool ProcessBlock(BasicBlock *BB); 75 bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs, 76 BasicBlock *SuccBB); 77 bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB, 78 BasicBlock *PredBB); 79 80 typedef SmallVectorImpl<std::pair<ConstantInt*, 81 BasicBlock*> > PredValueInfo; 82 83 bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB, 84 PredValueInfo &Result); 85 bool ProcessThreadableEdges(Instruction *CondInst, BasicBlock *BB); 86 87 88 bool ProcessBranchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB); 89 bool ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, BasicBlock *DestBB); 90 91 bool ProcessJumpOnPHI(PHINode *PN); 92 93 bool SimplifyPartiallyRedundantLoad(LoadInst *LI); 94 }; 95} 96 97char JumpThreading::ID = 0; 98static RegisterPass<JumpThreading> 99X("jump-threading", "Jump Threading"); 100 101// Public interface to the Jump Threading pass 102FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); } 103 104/// runOnFunction - Top level algorithm. 105/// 106bool JumpThreading::runOnFunction(Function &F) { 107 DEBUG(errs() << "Jump threading on function '" << F.getName() << "'\n"); 108 TD = getAnalysisIfAvailable<TargetData>(); 109 110 FindLoopHeaders(F); 111 112 bool AnotherIteration = true, EverChanged = false; 113 while (AnotherIteration) { 114 AnotherIteration = false; 115 bool Changed = false; 116 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 117 BasicBlock *BB = I; 118 // Thread all of the branches we can over this block. 119 while (ProcessBlock(BB)) 120 Changed = true; 121 122 ++I; 123 124 // If the block is trivially dead, zap it. This eliminates the successor 125 // edges which simplifies the CFG. 126 if (pred_begin(BB) == pred_end(BB) && 127 BB != &BB->getParent()->getEntryBlock()) { 128 DEBUG(errs() << " JT: Deleting dead block '" << BB->getName() 129 << "' with terminator: " << *BB->getTerminator() << '\n'); 130 LoopHeaders.erase(BB); 131 DeleteDeadBlock(BB); 132 Changed = true; 133 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 134 // Can't thread an unconditional jump, but if the block is "almost 135 // empty", we can replace uses of it with uses of the successor and make 136 // this dead. 137 if (BI->isUnconditional() && 138 BB != &BB->getParent()->getEntryBlock()) { 139 BasicBlock::iterator BBI = BB->getFirstNonPHI(); 140 // Ignore dbg intrinsics. 141 while (isa<DbgInfoIntrinsic>(BBI)) 142 ++BBI; 143 // If the terminator is the only non-phi instruction, try to nuke it. 144 if (BBI->isTerminator()) { 145 // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the 146 // block, we have to make sure it isn't in the LoopHeaders set. We 147 // reinsert afterward in the rare case when the block isn't deleted. 148 bool ErasedFromLoopHeaders = LoopHeaders.erase(BB); 149 150 if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) 151 Changed = true; 152 else if (ErasedFromLoopHeaders) 153 LoopHeaders.insert(BB); 154 } 155 } 156 } 157 } 158 AnotherIteration = Changed; 159 EverChanged |= Changed; 160 } 161 162 LoopHeaders.clear(); 163 return EverChanged; 164} 165 166/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to 167/// thread across it. 168static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) { 169 /// Ignore PHI nodes, these will be flattened when duplication happens. 170 BasicBlock::const_iterator I = BB->getFirstNonPHI(); 171 172 // FIXME: THREADING will delete values that are just used to compute the 173 // branch, so they shouldn't count against the duplication cost. 174 175 176 // Sum up the cost of each instruction until we get to the terminator. Don't 177 // include the terminator because the copy won't include it. 178 unsigned Size = 0; 179 for (; !isa<TerminatorInst>(I); ++I) { 180 // Debugger intrinsics don't incur code size. 181 if (isa<DbgInfoIntrinsic>(I)) continue; 182 183 // If this is a pointer->pointer bitcast, it is free. 184 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType())) 185 continue; 186 187 // All other instructions count for at least one unit. 188 ++Size; 189 190 // Calls are more expensive. If they are non-intrinsic calls, we model them 191 // as having cost of 4. If they are a non-vector intrinsic, we model them 192 // as having cost of 2 total, and if they are a vector intrinsic, we model 193 // them as having cost 1. 194 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 195 if (!isa<IntrinsicInst>(CI)) 196 Size += 3; 197 else if (!isa<VectorType>(CI->getType())) 198 Size += 1; 199 } 200 } 201 202 // Threading through a switch statement is particularly profitable. If this 203 // block ends in a switch, decrease its cost to make it more likely to happen. 204 if (isa<SwitchInst>(I)) 205 Size = Size > 6 ? Size-6 : 0; 206 207 return Size; 208} 209 210/// FindLoopHeaders - We do not want jump threading to turn proper loop 211/// structures into irreducible loops. Doing this breaks up the loop nesting 212/// hierarchy and pessimizes later transformations. To prevent this from 213/// happening, we first have to find the loop headers. Here we approximate this 214/// by finding targets of backedges in the CFG. 215/// 216/// Note that there definitely are cases when we want to allow threading of 217/// edges across a loop header. For example, threading a jump from outside the 218/// loop (the preheader) to an exit block of the loop is definitely profitable. 219/// It is also almost always profitable to thread backedges from within the loop 220/// to exit blocks, and is often profitable to thread backedges to other blocks 221/// within the loop (forming a nested loop). This simple analysis is not rich 222/// enough to track all of these properties and keep it up-to-date as the CFG 223/// mutates, so we don't allow any of these transformations. 224/// 225void JumpThreading::FindLoopHeaders(Function &F) { 226 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges; 227 FindFunctionBackedges(F, Edges); 228 229 for (unsigned i = 0, e = Edges.size(); i != e; ++i) 230 LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second)); 231} 232 233/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see 234/// if we can infer that the value is a known ConstantInt in any of our 235/// predecessors. If so, return the known list of value and pred BB in the 236/// result vector. If a value is known to be undef, it is returned as null. 237/// 238/// The BB basic block is known to start with a PHI node. 239/// 240/// This returns true if there were any known values. 241/// 242/// 243/// TODO: Per PR2563, we could infer value range information about a predecessor 244/// based on its terminator. 245bool JumpThreading:: 246ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){ 247 PHINode *TheFirstPHI = cast<PHINode>(BB->begin()); 248 249 // If V is a constantint, then it is known in all predecessors. 250 if (isa<ConstantInt>(V) || isa<UndefValue>(V)) { 251 ConstantInt *CI = dyn_cast<ConstantInt>(V); 252 Result.resize(TheFirstPHI->getNumIncomingValues()); 253 for (unsigned i = 0, e = Result.size(); i != e; ++i) 254 Result[i] = std::make_pair(CI, TheFirstPHI->getIncomingBlock(i)); 255 return true; 256 } 257 258 // If V is a non-instruction value, or an instruction in a different block, 259 // then it can't be derived from a PHI. 260 Instruction *I = dyn_cast<Instruction>(V); 261 if (I == 0 || I->getParent() != BB) 262 return false; 263 264 /// If I is a PHI node, then we know the incoming values for any constants. 265 if (PHINode *PN = dyn_cast<PHINode>(I)) { 266 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 267 Value *InVal = PN->getIncomingValue(i); 268 if (isa<ConstantInt>(InVal) || isa<UndefValue>(InVal)) { 269 ConstantInt *CI = dyn_cast<ConstantInt>(InVal); 270 Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i))); 271 } 272 } 273 return !Result.empty(); 274 } 275 276 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals, RHSVals; 277 278 // Handle some boolean conditions. 279 if (I->getType()->getPrimitiveSizeInBits() == 1) { 280 // X | true -> true 281 // X & false -> false 282 if (I->getOpcode() == Instruction::Or || 283 I->getOpcode() == Instruction::And) { 284 ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals); 285 ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals); 286 287 if (LHSVals.empty() && RHSVals.empty()) 288 return false; 289 290 ConstantInt *InterestingVal; 291 if (I->getOpcode() == Instruction::Or) 292 InterestingVal = ConstantInt::getTrue(I->getContext()); 293 else 294 InterestingVal = ConstantInt::getFalse(I->getContext()); 295 296 // Scan for the sentinel. 297 for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) 298 if (LHSVals[i].first == InterestingVal || LHSVals[i].first == 0) 299 Result.push_back(LHSVals[i]); 300 for (unsigned i = 0, e = RHSVals.size(); i != e; ++i) 301 if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0) 302 Result.push_back(RHSVals[i]); 303 return !Result.empty(); 304 } 305 306 // Handle the NOT form of XOR. 307 if (I->getOpcode() == Instruction::Xor && 308 isa<ConstantInt>(I->getOperand(1)) && 309 cast<ConstantInt>(I->getOperand(1))->isOne()) { 310 ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result); 311 if (Result.empty()) 312 return false; 313 314 // Invert the known values. 315 for (unsigned i = 0, e = Result.size(); i != e; ++i) 316 Result[i].first = 317 cast<ConstantInt>(ConstantExpr::getNot(Result[i].first)); 318 return true; 319 } 320 } 321 322 // Handle compare with phi operand, where the PHI is defined in this block. 323 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 324 PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0)); 325 if (PN && PN->getParent() == BB) { 326 // We can do this simplification if any comparisons fold to true or false. 327 // See if any do. 328 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 329 BasicBlock *PredBB = PN->getIncomingBlock(i); 330 Value *LHS = PN->getIncomingValue(i); 331 Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB); 332 333 Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS); 334 if (Res == 0) continue; 335 336 if (isa<UndefValue>(Res)) 337 Result.push_back(std::make_pair((ConstantInt*)0, PredBB)); 338 else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res)) 339 Result.push_back(std::make_pair(CI, PredBB)); 340 } 341 342 return !Result.empty(); 343 } 344 345 // TODO: We could also recurse to see if we can determine constants another 346 // way. 347 } 348 return false; 349} 350 351 352 353/// GetBestDestForBranchOnUndef - If we determine that the specified block ends 354/// in an undefined jump, decide which block is best to revector to. 355/// 356/// Since we can pick an arbitrary destination, we pick the successor with the 357/// fewest predecessors. This should reduce the in-degree of the others. 358/// 359static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) { 360 TerminatorInst *BBTerm = BB->getTerminator(); 361 unsigned MinSucc = 0; 362 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc); 363 // Compute the successor with the minimum number of predecessors. 364 unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); 365 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) { 366 TestBB = BBTerm->getSuccessor(i); 367 unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB)); 368 if (NumPreds < MinNumPreds) 369 MinSucc = i; 370 } 371 372 return MinSucc; 373} 374 375/// ProcessBlock - If there are any predecessors whose control can be threaded 376/// through to a successor, transform them now. 377bool JumpThreading::ProcessBlock(BasicBlock *BB) { 378 // If this block has a single predecessor, and if that pred has a single 379 // successor, merge the blocks. This encourages recursive jump threading 380 // because now the condition in this block can be threaded through 381 // predecessors of our predecessor block. 382 if (BasicBlock *SinglePred = BB->getSinglePredecessor()) { 383 if (SinglePred->getTerminator()->getNumSuccessors() == 1 && 384 SinglePred != BB) { 385 // If SinglePred was a loop header, BB becomes one. 386 if (LoopHeaders.erase(SinglePred)) 387 LoopHeaders.insert(BB); 388 389 // Remember if SinglePred was the entry block of the function. If so, we 390 // will need to move BB back to the entry position. 391 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); 392 MergeBasicBlockIntoOnlyPred(BB); 393 394 if (isEntry && BB != &BB->getParent()->getEntryBlock()) 395 BB->moveBefore(&BB->getParent()->getEntryBlock()); 396 return true; 397 } 398 } 399 400 // Look to see if the terminator is a branch of switch, if not we can't thread 401 // it. 402 Value *Condition; 403 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 404 // Can't thread an unconditional jump. 405 if (BI->isUnconditional()) return false; 406 Condition = BI->getCondition(); 407 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) 408 Condition = SI->getCondition(); 409 else 410 return false; // Must be an invoke. 411 412 // If the terminator of this block is branching on a constant, simplify the 413 // terminator to an unconditional branch. This can occur due to threading in 414 // other blocks. 415 if (isa<ConstantInt>(Condition)) { 416 DEBUG(errs() << " In block '" << BB->getName() 417 << "' folding terminator: " << *BB->getTerminator() << '\n'); 418 ++NumFolds; 419 ConstantFoldTerminator(BB); 420 return true; 421 } 422 423 // If the terminator is branching on an undef, we can pick any of the 424 // successors to branch to. Let GetBestDestForJumpOnUndef decide. 425 if (isa<UndefValue>(Condition)) { 426 unsigned BestSucc = GetBestDestForJumpOnUndef(BB); 427 428 // Fold the branch/switch. 429 TerminatorInst *BBTerm = BB->getTerminator(); 430 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) { 431 if (i == BestSucc) continue; 432 RemovePredecessorAndSimplify(BBTerm->getSuccessor(i), BB, TD); 433 } 434 435 DEBUG(errs() << " In block '" << BB->getName() 436 << "' folding undef terminator: " << *BBTerm << '\n'); 437 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm); 438 BBTerm->eraseFromParent(); 439 return true; 440 } 441 442 Instruction *CondInst = dyn_cast<Instruction>(Condition); 443 444 // If the condition is an instruction defined in another block, see if a 445 // predecessor has the same condition: 446 // br COND, BBX, BBY 447 // BBX: 448 // br COND, BBZ, BBW 449 if (!Condition->hasOneUse() && // Multiple uses. 450 (CondInst == 0 || CondInst->getParent() != BB)) { // Non-local definition. 451 pred_iterator PI = pred_begin(BB), E = pred_end(BB); 452 if (isa<BranchInst>(BB->getTerminator())) { 453 for (; PI != E; ++PI) 454 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 455 if (PBI->isConditional() && PBI->getCondition() == Condition && 456 ProcessBranchOnDuplicateCond(*PI, BB)) 457 return true; 458 } else { 459 assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator"); 460 for (; PI != E; ++PI) 461 if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator())) 462 if (PSI->getCondition() == Condition && 463 ProcessSwitchOnDuplicateCond(*PI, BB)) 464 return true; 465 } 466 } 467 468 // All the rest of our checks depend on the condition being an instruction. 469 if (CondInst == 0) 470 return false; 471 472 // See if this is a phi node in the current block. 473 if (PHINode *PN = dyn_cast<PHINode>(CondInst)) 474 if (PN->getParent() == BB) 475 return ProcessJumpOnPHI(PN); 476 477 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) { 478 if (!isa<PHINode>(CondCmp->getOperand(0)) || 479 cast<PHINode>(CondCmp->getOperand(0))->getParent() != BB) { 480 // If we have a comparison, loop over the predecessors to see if there is 481 // a condition with a lexically identical value. 482 pred_iterator PI = pred_begin(BB), E = pred_end(BB); 483 for (; PI != E; ++PI) 484 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 485 if (PBI->isConditional() && *PI != BB) { 486 if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) { 487 if (CI->getOperand(0) == CondCmp->getOperand(0) && 488 CI->getOperand(1) == CondCmp->getOperand(1) && 489 CI->getPredicate() == CondCmp->getPredicate()) { 490 // TODO: Could handle things like (x != 4) --> (x == 17) 491 if (ProcessBranchOnDuplicateCond(*PI, BB)) 492 return true; 493 } 494 } 495 } 496 } 497 } 498 499 // Check for some cases that are worth simplifying. Right now we want to look 500 // for loads that are used by a switch or by the condition for the branch. If 501 // we see one, check to see if it's partially redundant. If so, insert a PHI 502 // which can then be used to thread the values. 503 // 504 // This is particularly important because reg2mem inserts loads and stores all 505 // over the place, and this blocks jump threading if we don't zap them. 506 Value *SimplifyValue = CondInst; 507 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue)) 508 if (isa<Constant>(CondCmp->getOperand(1))) 509 SimplifyValue = CondCmp->getOperand(0); 510 511 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue)) 512 if (SimplifyPartiallyRedundantLoad(LI)) 513 return true; 514 515 516 // Handle a variety of cases where we are branching on something derived from 517 // a PHI node in the current block. If we can prove that any predecessors 518 // compute a predictable value based on a PHI node, thread those predecessors. 519 // 520 // We only bother doing this if the current block has a PHI node and if the 521 // conditional instruction lives in the current block. If either condition 522 // fails, this won't be a computable value anyway. 523 if (CondInst->getParent() == BB && isa<PHINode>(BB->front())) 524 if (ProcessThreadableEdges(CondInst, BB)) 525 return true; 526 527 528 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know 529 // "(X == 4)" thread through this block. 530 531 return false; 532} 533 534/// ProcessBranchOnDuplicateCond - We found a block and a predecessor of that 535/// block that jump on exactly the same condition. This means that we almost 536/// always know the direction of the edge in the DESTBB: 537/// PREDBB: 538/// br COND, DESTBB, BBY 539/// DESTBB: 540/// br COND, BBZ, BBW 541/// 542/// If DESTBB has multiple predecessors, we can't just constant fold the branch 543/// in DESTBB, we have to thread over it. 544bool JumpThreading::ProcessBranchOnDuplicateCond(BasicBlock *PredBB, 545 BasicBlock *BB) { 546 BranchInst *PredBI = cast<BranchInst>(PredBB->getTerminator()); 547 548 // If both successors of PredBB go to DESTBB, we don't know anything. We can 549 // fold the branch to an unconditional one, which allows other recursive 550 // simplifications. 551 bool BranchDir; 552 if (PredBI->getSuccessor(1) != BB) 553 BranchDir = true; 554 else if (PredBI->getSuccessor(0) != BB) 555 BranchDir = false; 556 else { 557 DEBUG(errs() << " In block '" << PredBB->getName() 558 << "' folding terminator: " << *PredBB->getTerminator() << '\n'); 559 ++NumFolds; 560 ConstantFoldTerminator(PredBB); 561 return true; 562 } 563 564 BranchInst *DestBI = cast<BranchInst>(BB->getTerminator()); 565 566 // If the dest block has one predecessor, just fix the branch condition to a 567 // constant and fold it. 568 if (BB->getSinglePredecessor()) { 569 DEBUG(errs() << " In block '" << BB->getName() 570 << "' folding condition to '" << BranchDir << "': " 571 << *BB->getTerminator() << '\n'); 572 ++NumFolds; 573 Value *OldCond = DestBI->getCondition(); 574 DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()), 575 BranchDir)); 576 ConstantFoldTerminator(BB); 577 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 578 return true; 579 } 580 581 582 // Next, figure out which successor we are threading to. 583 BasicBlock *SuccBB = DestBI->getSuccessor(!BranchDir); 584 585 SmallVector<BasicBlock*, 2> Preds; 586 Preds.push_back(PredBB); 587 588 // Ok, try to thread it! 589 return ThreadEdge(BB, Preds, SuccBB); 590} 591 592/// ProcessSwitchOnDuplicateCond - We found a block and a predecessor of that 593/// block that switch on exactly the same condition. This means that we almost 594/// always know the direction of the edge in the DESTBB: 595/// PREDBB: 596/// switch COND [... DESTBB, BBY ... ] 597/// DESTBB: 598/// switch COND [... BBZ, BBW ] 599/// 600/// Optimizing switches like this is very important, because simplifycfg builds 601/// switches out of repeated 'if' conditions. 602bool JumpThreading::ProcessSwitchOnDuplicateCond(BasicBlock *PredBB, 603 BasicBlock *DestBB) { 604 // Can't thread edge to self. 605 if (PredBB == DestBB) 606 return false; 607 608 SwitchInst *PredSI = cast<SwitchInst>(PredBB->getTerminator()); 609 SwitchInst *DestSI = cast<SwitchInst>(DestBB->getTerminator()); 610 611 // There are a variety of optimizations that we can potentially do on these 612 // blocks: we order them from most to least preferable. 613 614 // If DESTBB *just* contains the switch, then we can forward edges from PREDBB 615 // directly to their destination. This does not introduce *any* code size 616 // growth. Skip debug info first. 617 BasicBlock::iterator BBI = DestBB->begin(); 618 while (isa<DbgInfoIntrinsic>(BBI)) 619 BBI++; 620 621 // FIXME: Thread if it just contains a PHI. 622 if (isa<SwitchInst>(BBI)) { 623 bool MadeChange = false; 624 // Ignore the default edge for now. 625 for (unsigned i = 1, e = DestSI->getNumSuccessors(); i != e; ++i) { 626 ConstantInt *DestVal = DestSI->getCaseValue(i); 627 BasicBlock *DestSucc = DestSI->getSuccessor(i); 628 629 // Okay, DestSI has a case for 'DestVal' that goes to 'DestSucc'. See if 630 // PredSI has an explicit case for it. If so, forward. If it is covered 631 // by the default case, we can't update PredSI. 632 unsigned PredCase = PredSI->findCaseValue(DestVal); 633 if (PredCase == 0) continue; 634 635 // If PredSI doesn't go to DestBB on this value, then it won't reach the 636 // case on this condition. 637 if (PredSI->getSuccessor(PredCase) != DestBB && 638 DestSI->getSuccessor(i) != DestBB) 639 continue; 640 641 // Otherwise, we're safe to make the change. Make sure that the edge from 642 // DestSI to DestSucc is not critical and has no PHI nodes. 643 DEBUG(errs() << "FORWARDING EDGE " << *DestVal << " FROM: " << *PredSI); 644 DEBUG(errs() << "THROUGH: " << *DestSI); 645 646 // If the destination has PHI nodes, just split the edge for updating 647 // simplicity. 648 if (isa<PHINode>(DestSucc->begin()) && !DestSucc->getSinglePredecessor()){ 649 SplitCriticalEdge(DestSI, i, this); 650 DestSucc = DestSI->getSuccessor(i); 651 } 652 FoldSingleEntryPHINodes(DestSucc); 653 PredSI->setSuccessor(PredCase, DestSucc); 654 MadeChange = true; 655 } 656 657 if (MadeChange) 658 return true; 659 } 660 661 return false; 662} 663 664 665/// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant 666/// load instruction, eliminate it by replacing it with a PHI node. This is an 667/// important optimization that encourages jump threading, and needs to be run 668/// interlaced with other jump threading tasks. 669bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) { 670 // Don't hack volatile loads. 671 if (LI->isVolatile()) return false; 672 673 // If the load is defined in a block with exactly one predecessor, it can't be 674 // partially redundant. 675 BasicBlock *LoadBB = LI->getParent(); 676 if (LoadBB->getSinglePredecessor()) 677 return false; 678 679 Value *LoadedPtr = LI->getOperand(0); 680 681 // If the loaded operand is defined in the LoadBB, it can't be available. 682 // FIXME: Could do PHI translation, that would be fun :) 683 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr)) 684 if (PtrOp->getParent() == LoadBB) 685 return false; 686 687 // Scan a few instructions up from the load, to see if it is obviously live at 688 // the entry to its block. 689 BasicBlock::iterator BBIt = LI; 690 691 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB, 692 BBIt, 6)) { 693 // If the value if the load is locally available within the block, just use 694 // it. This frequently occurs for reg2mem'd allocas. 695 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n"; 696 697 // If the returned value is the load itself, replace with an undef. This can 698 // only happen in dead loops. 699 if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType()); 700 LI->replaceAllUsesWith(AvailableVal); 701 LI->eraseFromParent(); 702 return true; 703 } 704 705 // Otherwise, if we scanned the whole block and got to the top of the block, 706 // we know the block is locally transparent to the load. If not, something 707 // might clobber its value. 708 if (BBIt != LoadBB->begin()) 709 return false; 710 711 712 SmallPtrSet<BasicBlock*, 8> PredsScanned; 713 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy; 714 AvailablePredsTy AvailablePreds; 715 BasicBlock *OneUnavailablePred = 0; 716 717 // If we got here, the loaded value is transparent through to the start of the 718 // block. Check to see if it is available in any of the predecessor blocks. 719 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB); 720 PI != PE; ++PI) { 721 BasicBlock *PredBB = *PI; 722 723 // If we already scanned this predecessor, skip it. 724 if (!PredsScanned.insert(PredBB)) 725 continue; 726 727 // Scan the predecessor to see if the value is available in the pred. 728 BBIt = PredBB->end(); 729 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6); 730 if (!PredAvailable) { 731 OneUnavailablePred = PredBB; 732 continue; 733 } 734 735 // If so, this load is partially redundant. Remember this info so that we 736 // can create a PHI node. 737 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable)); 738 } 739 740 // If the loaded value isn't available in any predecessor, it isn't partially 741 // redundant. 742 if (AvailablePreds.empty()) return false; 743 744 // Okay, the loaded value is available in at least one (and maybe all!) 745 // predecessors. If the value is unavailable in more than one unique 746 // predecessor, we want to insert a merge block for those common predecessors. 747 // This ensures that we only have to insert one reload, thus not increasing 748 // code size. 749 BasicBlock *UnavailablePred = 0; 750 751 // If there is exactly one predecessor where the value is unavailable, the 752 // already computed 'OneUnavailablePred' block is it. If it ends in an 753 // unconditional branch, we know that it isn't a critical edge. 754 if (PredsScanned.size() == AvailablePreds.size()+1 && 755 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) { 756 UnavailablePred = OneUnavailablePred; 757 } else if (PredsScanned.size() != AvailablePreds.size()) { 758 // Otherwise, we had multiple unavailable predecessors or we had a critical 759 // edge from the one. 760 SmallVector<BasicBlock*, 8> PredsToSplit; 761 SmallPtrSet<BasicBlock*, 8> AvailablePredSet; 762 763 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i) 764 AvailablePredSet.insert(AvailablePreds[i].first); 765 766 // Add all the unavailable predecessors to the PredsToSplit list. 767 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB); 768 PI != PE; ++PI) 769 if (!AvailablePredSet.count(*PI)) 770 PredsToSplit.push_back(*PI); 771 772 // Split them out to their own block. 773 UnavailablePred = 774 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(), 775 "thread-split", this); 776 } 777 778 // If the value isn't available in all predecessors, then there will be 779 // exactly one where it isn't available. Insert a load on that edge and add 780 // it to the AvailablePreds list. 781 if (UnavailablePred) { 782 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 && 783 "Can't handle critical edge here!"); 784 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", 785 UnavailablePred->getTerminator()); 786 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal)); 787 } 788 789 // Now we know that each predecessor of this block has a value in 790 // AvailablePreds, sort them for efficient access as we're walking the preds. 791 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end()); 792 793 // Create a PHI node at the start of the block for the PRE'd load value. 794 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin()); 795 PN->takeName(LI); 796 797 // Insert new entries into the PHI for each predecessor. A single block may 798 // have multiple entries here. 799 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E; 800 ++PI) { 801 AvailablePredsTy::iterator I = 802 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(), 803 std::make_pair(*PI, (Value*)0)); 804 805 assert(I != AvailablePreds.end() && I->first == *PI && 806 "Didn't find entry for predecessor!"); 807 808 PN->addIncoming(I->second, I->first); 809 } 810 811 //cerr << "PRE: " << *LI << *PN << "\n"; 812 813 LI->replaceAllUsesWith(PN); 814 LI->eraseFromParent(); 815 816 return true; 817} 818 819/// FindMostPopularDest - The specified list contains multiple possible 820/// threadable destinations. Pick the one that occurs the most frequently in 821/// the list. 822static BasicBlock * 823FindMostPopularDest(BasicBlock *BB, 824 const SmallVectorImpl<std::pair<BasicBlock*, 825 BasicBlock*> > &PredToDestList) { 826 assert(!PredToDestList.empty()); 827 828 // Determine popularity. If there are multiple possible destinations, we 829 // explicitly choose to ignore 'undef' destinations. We prefer to thread 830 // blocks with known and real destinations to threading undef. We'll handle 831 // them later if interesting. 832 DenseMap<BasicBlock*, unsigned> DestPopularity; 833 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i) 834 if (PredToDestList[i].second) 835 DestPopularity[PredToDestList[i].second]++; 836 837 // Find the most popular dest. 838 DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin(); 839 BasicBlock *MostPopularDest = DPI->first; 840 unsigned Popularity = DPI->second; 841 SmallVector<BasicBlock*, 4> SamePopularity; 842 843 for (++DPI; DPI != DestPopularity.end(); ++DPI) { 844 // If the popularity of this entry isn't higher than the popularity we've 845 // seen so far, ignore it. 846 if (DPI->second < Popularity) 847 ; // ignore. 848 else if (DPI->second == Popularity) { 849 // If it is the same as what we've seen so far, keep track of it. 850 SamePopularity.push_back(DPI->first); 851 } else { 852 // If it is more popular, remember it. 853 SamePopularity.clear(); 854 MostPopularDest = DPI->first; 855 Popularity = DPI->second; 856 } 857 } 858 859 // Okay, now we know the most popular destination. If there is more than 860 // destination, we need to determine one. This is arbitrary, but we need 861 // to make a deterministic decision. Pick the first one that appears in the 862 // successor list. 863 if (!SamePopularity.empty()) { 864 SamePopularity.push_back(MostPopularDest); 865 TerminatorInst *TI = BB->getTerminator(); 866 for (unsigned i = 0; ; ++i) { 867 assert(i != TI->getNumSuccessors() && "Didn't find any successor!"); 868 869 if (std::find(SamePopularity.begin(), SamePopularity.end(), 870 TI->getSuccessor(i)) == SamePopularity.end()) 871 continue; 872 873 MostPopularDest = TI->getSuccessor(i); 874 break; 875 } 876 } 877 878 // Okay, we have finally picked the most popular destination. 879 return MostPopularDest; 880} 881 882bool JumpThreading::ProcessThreadableEdges(Instruction *CondInst, 883 BasicBlock *BB) { 884 // If threading this would thread across a loop header, don't even try to 885 // thread the edge. 886 if (LoopHeaders.count(BB)) 887 return false; 888 889 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> PredValues; 890 if (!ComputeValueKnownInPredecessors(CondInst, BB, PredValues)) 891 return false; 892 assert(!PredValues.empty() && 893 "ComputeValueKnownInPredecessors returned true with no values"); 894 895 DEBUG(errs() << "IN BB: " << *BB; 896 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) { 897 errs() << " BB '" << BB->getName() << "': FOUND condition = "; 898 if (PredValues[i].first) 899 errs() << *PredValues[i].first; 900 else 901 errs() << "UNDEF"; 902 errs() << " for pred '" << PredValues[i].second->getName() 903 << "'.\n"; 904 }); 905 906 // Decide what we want to thread through. Convert our list of known values to 907 // a list of known destinations for each pred. This also discards duplicate 908 // predecessors and keeps track of the undefined inputs (which are represented 909 // as a null dest in the PredToDestList). 910 SmallPtrSet<BasicBlock*, 16> SeenPreds; 911 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList; 912 913 BasicBlock *OnlyDest = 0; 914 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL; 915 916 for (unsigned i = 0, e = PredValues.size(); i != e; ++i) { 917 BasicBlock *Pred = PredValues[i].second; 918 if (!SeenPreds.insert(Pred)) 919 continue; // Duplicate predecessor entry. 920 921 // If the predecessor ends with an indirect goto, we can't change its 922 // destination. 923 if (isa<IndirectBrInst>(Pred->getTerminator())) 924 continue; 925 926 ConstantInt *Val = PredValues[i].first; 927 928 BasicBlock *DestBB; 929 if (Val == 0) // Undef. 930 DestBB = 0; 931 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) 932 DestBB = BI->getSuccessor(Val->isZero()); 933 else { 934 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator()); 935 DestBB = SI->getSuccessor(SI->findCaseValue(Val)); 936 } 937 938 // If we have exactly one destination, remember it for efficiency below. 939 if (i == 0) 940 OnlyDest = DestBB; 941 else if (OnlyDest != DestBB) 942 OnlyDest = MultipleDestSentinel; 943 944 PredToDestList.push_back(std::make_pair(Pred, DestBB)); 945 } 946 947 // If all edges were unthreadable, we fail. 948 if (PredToDestList.empty()) 949 return false; 950 951 // Determine which is the most common successor. If we have many inputs and 952 // this block is a switch, we want to start by threading the batch that goes 953 // to the most popular destination first. If we only know about one 954 // threadable destination (the common case) we can avoid this. 955 BasicBlock *MostPopularDest = OnlyDest; 956 957 if (MostPopularDest == MultipleDestSentinel) 958 MostPopularDest = FindMostPopularDest(BB, PredToDestList); 959 960 // Now that we know what the most popular destination is, factor all 961 // predecessors that will jump to it into a single predecessor. 962 SmallVector<BasicBlock*, 16> PredsToFactor; 963 for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i) 964 if (PredToDestList[i].second == MostPopularDest) { 965 BasicBlock *Pred = PredToDestList[i].first; 966 967 // This predecessor may be a switch or something else that has multiple 968 // edges to the block. Factor each of these edges by listing them 969 // according to # occurrences in PredsToFactor. 970 TerminatorInst *PredTI = Pred->getTerminator(); 971 for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i) 972 if (PredTI->getSuccessor(i) == BB) 973 PredsToFactor.push_back(Pred); 974 } 975 976 // If the threadable edges are branching on an undefined value, we get to pick 977 // the destination that these predecessors should get to. 978 if (MostPopularDest == 0) 979 MostPopularDest = BB->getTerminator()-> 980 getSuccessor(GetBestDestForJumpOnUndef(BB)); 981 982 // Ok, try to thread it! 983 return ThreadEdge(BB, PredsToFactor, MostPopularDest); 984} 985 986/// ProcessJumpOnPHI - We have a conditional branch or switch on a PHI node in 987/// the current block. See if there are any simplifications we can do based on 988/// inputs to the phi node. 989/// 990bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) { 991 BasicBlock *BB = PN->getParent(); 992 993 // If any of the predecessor blocks end in an unconditional branch, we can 994 // *duplicate* the jump into that block in order to further encourage jump 995 // threading and to eliminate cases where we have branch on a phi of an icmp 996 // (branch on icmp is much better). 997 998 // We don't want to do this tranformation for switches, because we don't 999 // really want to duplicate a switch. 1000 if (isa<SwitchInst>(BB->getTerminator())) 1001 return false; 1002 1003 // Look for unconditional branch predecessors. 1004 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1005 BasicBlock *PredBB = PN->getIncomingBlock(i); 1006 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator())) 1007 if (PredBr->isUnconditional() && 1008 // Try to duplicate BB into PredBB. 1009 DuplicateCondBranchOnPHIIntoPred(BB, PredBB)) 1010 return true; 1011 } 1012 1013 return false; 1014} 1015 1016 1017/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new 1018/// predecessor to the PHIBB block. If it has PHI nodes, add entries for 1019/// NewPred using the entries from OldPred (suitably mapped). 1020static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, 1021 BasicBlock *OldPred, 1022 BasicBlock *NewPred, 1023 DenseMap<Instruction*, Value*> &ValueMap) { 1024 for (BasicBlock::iterator PNI = PHIBB->begin(); 1025 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) { 1026 // Ok, we have a PHI node. Figure out what the incoming value was for the 1027 // DestBlock. 1028 Value *IV = PN->getIncomingValueForBlock(OldPred); 1029 1030 // Remap the value if necessary. 1031 if (Instruction *Inst = dyn_cast<Instruction>(IV)) { 1032 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst); 1033 if (I != ValueMap.end()) 1034 IV = I->second; 1035 } 1036 1037 PN->addIncoming(IV, NewPred); 1038 } 1039} 1040 1041/// ThreadEdge - We have decided that it is safe and profitable to factor the 1042/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB 1043/// across BB. Transform the IR to reflect this change. 1044bool JumpThreading::ThreadEdge(BasicBlock *BB, 1045 const SmallVectorImpl<BasicBlock*> &PredBBs, 1046 BasicBlock *SuccBB) { 1047 // If threading to the same block as we come from, we would infinite loop. 1048 if (SuccBB == BB) { 1049 DEBUG(errs() << " Not threading across BB '" << BB->getName() 1050 << "' - would thread to self!\n"); 1051 return false; 1052 } 1053 1054 // If threading this would thread across a loop header, don't thread the edge. 1055 // See the comments above FindLoopHeaders for justifications and caveats. 1056 if (LoopHeaders.count(BB)) { 1057 DEBUG(errs() << " Not threading across loop header BB '" << BB->getName() 1058 << "' to dest BB '" << SuccBB->getName() 1059 << "' - it might create an irreducible loop!\n"); 1060 return false; 1061 } 1062 1063 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB); 1064 if (JumpThreadCost > Threshold) { 1065 DEBUG(errs() << " Not threading BB '" << BB->getName() 1066 << "' - Cost is too high: " << JumpThreadCost << "\n"); 1067 return false; 1068 } 1069 1070 // And finally, do it! Start by factoring the predecessors is needed. 1071 BasicBlock *PredBB; 1072 if (PredBBs.size() == 1) 1073 PredBB = PredBBs[0]; 1074 else { 1075 DEBUG(errs() << " Factoring out " << PredBBs.size() 1076 << " common predecessors.\n"); 1077 PredBB = SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(), 1078 ".thr_comm", this); 1079 } 1080 1081 // And finally, do it! 1082 DEBUG(errs() << " Threading edge from '" << PredBB->getName() << "' to '" 1083 << SuccBB->getName() << "' with cost: " << JumpThreadCost 1084 << ", across block:\n " 1085 << *BB << "\n"); 1086 1087 // We are going to have to map operands from the original BB block to the new 1088 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to 1089 // account for entry from PredBB. 1090 DenseMap<Instruction*, Value*> ValueMapping; 1091 1092 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), 1093 BB->getName()+".thread", 1094 BB->getParent(), BB); 1095 NewBB->moveAfter(PredBB); 1096 1097 BasicBlock::iterator BI = BB->begin(); 1098 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 1099 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 1100 1101 // Clone the non-phi instructions of BB into NewBB, keeping track of the 1102 // mapping and using it to remap operands in the cloned instructions. 1103 for (; !isa<TerminatorInst>(BI); ++BI) { 1104 Instruction *New = BI->clone(); 1105 New->setName(BI->getName()); 1106 NewBB->getInstList().push_back(New); 1107 ValueMapping[BI] = New; 1108 1109 // Remap operands to patch up intra-block references. 1110 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 1111 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 1112 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 1113 if (I != ValueMapping.end()) 1114 New->setOperand(i, I->second); 1115 } 1116 } 1117 1118 // We didn't copy the terminator from BB over to NewBB, because there is now 1119 // an unconditional jump to SuccBB. Insert the unconditional jump. 1120 BranchInst::Create(SuccBB, NewBB); 1121 1122 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the 1123 // PHI nodes for NewBB now. 1124 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping); 1125 1126 // If there were values defined in BB that are used outside the block, then we 1127 // now have to update all uses of the value to use either the original value, 1128 // the cloned value, or some PHI derived value. This can require arbitrary 1129 // PHI insertion, of which we are prepared to do, clean these up now. 1130 SSAUpdater SSAUpdate; 1131 SmallVector<Use*, 16> UsesToRename; 1132 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) { 1133 // Scan all uses of this instruction to see if it is used outside of its 1134 // block, and if so, record them in UsesToRename. 1135 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; 1136 ++UI) { 1137 Instruction *User = cast<Instruction>(*UI); 1138 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 1139 if (UserPN->getIncomingBlock(UI) == BB) 1140 continue; 1141 } else if (User->getParent() == BB) 1142 continue; 1143 1144 UsesToRename.push_back(&UI.getUse()); 1145 } 1146 1147 // If there are no uses outside the block, we're done with this instruction. 1148 if (UsesToRename.empty()) 1149 continue; 1150 1151 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n"); 1152 1153 // We found a use of I outside of BB. Rename all uses of I that are outside 1154 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 1155 // with the two values we know. 1156 SSAUpdate.Initialize(I); 1157 SSAUpdate.AddAvailableValue(BB, I); 1158 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]); 1159 1160 while (!UsesToRename.empty()) 1161 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 1162 DEBUG(errs() << "\n"); 1163 } 1164 1165 1166 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to 1167 // NewBB instead of BB. This eliminates predecessors from BB, which requires 1168 // us to simplify any PHI nodes in BB. 1169 TerminatorInst *PredTerm = PredBB->getTerminator(); 1170 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) 1171 if (PredTerm->getSuccessor(i) == BB) { 1172 RemovePredecessorAndSimplify(BB, PredBB, TD); 1173 PredTerm->setSuccessor(i, NewBB); 1174 } 1175 1176 // At this point, the IR is fully up to date and consistent. Do a quick scan 1177 // over the new instructions and zap any that are constants or dead. This 1178 // frequently happens because of phi translation. 1179 BI = NewBB->begin(); 1180 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) { 1181 Instruction *Inst = BI++; 1182 1183 if (Value *V = SimplifyInstruction(Inst, TD)) { 1184 WeakVH BIHandle(BI); 1185 ReplaceAndSimplifyAllUses(Inst, V, TD); 1186 if (BIHandle == 0) 1187 BI = NewBB->begin(); 1188 continue; 1189 } 1190 1191 RecursivelyDeleteTriviallyDeadInstructions(Inst); 1192 } 1193 1194 // Threaded an edge! 1195 ++NumThreads; 1196 return true; 1197} 1198 1199/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch 1200/// to BB which contains an i1 PHI node and a conditional branch on that PHI. 1201/// If we can duplicate the contents of BB up into PredBB do so now, this 1202/// improves the odds that the branch will be on an analyzable instruction like 1203/// a compare. 1204bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB, 1205 BasicBlock *PredBB) { 1206 // If BB is a loop header, then duplicating this block outside the loop would 1207 // cause us to transform this into an irreducible loop, don't do this. 1208 // See the comments above FindLoopHeaders for justifications and caveats. 1209 if (LoopHeaders.count(BB)) { 1210 DEBUG(errs() << " Not duplicating loop header '" << BB->getName() 1211 << "' into predecessor block '" << PredBB->getName() 1212 << "' - it might create an irreducible loop!\n"); 1213 return false; 1214 } 1215 1216 unsigned DuplicationCost = getJumpThreadDuplicationCost(BB); 1217 if (DuplicationCost > Threshold) { 1218 DEBUG(errs() << " Not duplicating BB '" << BB->getName() 1219 << "' - Cost is too high: " << DuplicationCost << "\n"); 1220 return false; 1221 } 1222 1223 // Okay, we decided to do this! Clone all the instructions in BB onto the end 1224 // of PredBB. 1225 DEBUG(errs() << " Duplicating block '" << BB->getName() << "' into end of '" 1226 << PredBB->getName() << "' to eliminate branch on phi. Cost: " 1227 << DuplicationCost << " block is:" << *BB << "\n"); 1228 1229 // We are going to have to map operands from the original BB block into the 1230 // PredBB block. Evaluate PHI nodes in BB. 1231 DenseMap<Instruction*, Value*> ValueMapping; 1232 1233 BasicBlock::iterator BI = BB->begin(); 1234 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 1235 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB); 1236 1237 BranchInst *OldPredBranch = cast<BranchInst>(PredBB->getTerminator()); 1238 1239 // Clone the non-phi instructions of BB into PredBB, keeping track of the 1240 // mapping and using it to remap operands in the cloned instructions. 1241 for (; BI != BB->end(); ++BI) { 1242 Instruction *New = BI->clone(); 1243 New->setName(BI->getName()); 1244 PredBB->getInstList().insert(OldPredBranch, New); 1245 ValueMapping[BI] = New; 1246 1247 // Remap operands to patch up intra-block references. 1248 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i) 1249 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) { 1250 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst); 1251 if (I != ValueMapping.end()) 1252 New->setOperand(i, I->second); 1253 } 1254 } 1255 1256 // Check to see if the targets of the branch had PHI nodes. If so, we need to 1257 // add entries to the PHI nodes for branch from PredBB now. 1258 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator()); 1259 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB, 1260 ValueMapping); 1261 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB, 1262 ValueMapping); 1263 1264 // If there were values defined in BB that are used outside the block, then we 1265 // now have to update all uses of the value to use either the original value, 1266 // the cloned value, or some PHI derived value. This can require arbitrary 1267 // PHI insertion, of which we are prepared to do, clean these up now. 1268 SSAUpdater SSAUpdate; 1269 SmallVector<Use*, 16> UsesToRename; 1270 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) { 1271 // Scan all uses of this instruction to see if it is used outside of its 1272 // block, and if so, record them in UsesToRename. 1273 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; 1274 ++UI) { 1275 Instruction *User = cast<Instruction>(*UI); 1276 if (PHINode *UserPN = dyn_cast<PHINode>(User)) { 1277 if (UserPN->getIncomingBlock(UI) == BB) 1278 continue; 1279 } else if (User->getParent() == BB) 1280 continue; 1281 1282 UsesToRename.push_back(&UI.getUse()); 1283 } 1284 1285 // If there are no uses outside the block, we're done with this instruction. 1286 if (UsesToRename.empty()) 1287 continue; 1288 1289 DEBUG(errs() << "JT: Renaming non-local uses of: " << *I << "\n"); 1290 1291 // We found a use of I outside of BB. Rename all uses of I that are outside 1292 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks 1293 // with the two values we know. 1294 SSAUpdate.Initialize(I); 1295 SSAUpdate.AddAvailableValue(BB, I); 1296 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]); 1297 1298 while (!UsesToRename.empty()) 1299 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val()); 1300 DEBUG(errs() << "\n"); 1301 } 1302 1303 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge 1304 // that we nuked. 1305 RemovePredecessorAndSimplify(BB, PredBB, TD); 1306 1307 // Remove the unconditional branch at the end of the PredBB block. 1308 OldPredBranch->eraseFromParent(); 1309 1310 ++NumDupes; 1311 return true; 1312} 1313 1314 1315