1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==// 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 family of functions perform manipulations on basic blocks, and 11 // instructions contained within basic blocks. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 16 #include "llvm/Analysis/AliasAnalysis.h" 17 #include "llvm/Analysis/CFG.h" 18 #include "llvm/Analysis/LoopInfo.h" 19 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 20 #include "llvm/IR/Constant.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/Dominators.h" 23 #include "llvm/IR/Function.h" 24 #include "llvm/IR/Instructions.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/IR/Type.h" 27 #include "llvm/IR/ValueHandle.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include "llvm/Transforms/Scalar.h" 30 #include "llvm/Transforms/Utils/Local.h" 31 #include <algorithm> 32 using namespace llvm; 33 34 /// DeleteDeadBlock - Delete the specified block, which must have no 35 /// predecessors. 36 void llvm::DeleteDeadBlock(BasicBlock *BB) { 37 assert((pred_begin(BB) == pred_end(BB) || 38 // Can delete self loop. 39 BB->getSinglePredecessor() == BB) && "Block is not dead!"); 40 TerminatorInst *BBTerm = BB->getTerminator(); 41 42 // Loop through all of our successors and make sure they know that one 43 // of their predecessors is going away. 44 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) 45 BBTerm->getSuccessor(i)->removePredecessor(BB); 46 47 // Zap all the instructions in the block. 48 while (!BB->empty()) { 49 Instruction &I = BB->back(); 50 // If this instruction is used, replace uses with an arbitrary value. 51 // Because control flow can't get here, we don't care what we replace the 52 // value with. Note that since this block is unreachable, and all values 53 // contained within it must dominate their uses, that all uses will 54 // eventually be removed (they are themselves dead). 55 if (!I.use_empty()) 56 I.replaceAllUsesWith(UndefValue::get(I.getType())); 57 BB->getInstList().pop_back(); 58 } 59 60 // Zap the block! 61 BB->eraseFromParent(); 62 } 63 64 /// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are 65 /// any single-entry PHI nodes in it, fold them away. This handles the case 66 /// when all entries to the PHI nodes in a block are guaranteed equal, such as 67 /// when the block has exactly one predecessor. 68 void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, AliasAnalysis *AA, 69 MemoryDependenceAnalysis *MemDep) { 70 if (!isa<PHINode>(BB->begin())) return; 71 72 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 73 if (PN->getIncomingValue(0) != PN) 74 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 75 else 76 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 77 78 if (MemDep) 79 MemDep->removeInstruction(PN); // Memdep updates AA itself. 80 else if (AA && isa<PointerType>(PN->getType())) 81 AA->deleteValue(PN); 82 83 PN->eraseFromParent(); 84 } 85 } 86 87 88 /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it 89 /// is dead. Also recursively delete any operands that become dead as 90 /// a result. This includes tracing the def-use list from the PHI to see if 91 /// it is ultimately unused or if it reaches an unused cycle. 92 bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) { 93 // Recursively deleting a PHI may cause multiple PHIs to be deleted 94 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete. 95 SmallVector<WeakVH, 8> PHIs; 96 for (BasicBlock::iterator I = BB->begin(); 97 PHINode *PN = dyn_cast<PHINode>(I); ++I) 98 PHIs.push_back(PN); 99 100 bool Changed = false; 101 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 102 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*())) 103 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI); 104 105 return Changed; 106 } 107 108 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor, 109 /// if possible. The return value indicates success or failure. 110 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT, 111 LoopInfo *LI, AliasAnalysis *AA, 112 MemoryDependenceAnalysis *MemDep) { 113 // Don't merge away blocks who have their address taken. 114 if (BB->hasAddressTaken()) return false; 115 116 // Can't merge if there are multiple predecessors, or no predecessors. 117 BasicBlock *PredBB = BB->getUniquePredecessor(); 118 if (!PredBB) return false; 119 120 // Don't break self-loops. 121 if (PredBB == BB) return false; 122 // Don't break invokes. 123 if (isa<InvokeInst>(PredBB->getTerminator())) return false; 124 125 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB)); 126 BasicBlock *OnlySucc = BB; 127 for (; SI != SE; ++SI) 128 if (*SI != OnlySucc) { 129 OnlySucc = nullptr; // There are multiple distinct successors! 130 break; 131 } 132 133 // Can't merge if there are multiple successors. 134 if (!OnlySucc) return false; 135 136 // Can't merge if there is PHI loop. 137 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) { 138 if (PHINode *PN = dyn_cast<PHINode>(BI)) { 139 for (Value *IncValue : PN->incoming_values()) 140 if (IncValue == PN) 141 return false; 142 } else 143 break; 144 } 145 146 // Begin by getting rid of unneeded PHIs. 147 if (isa<PHINode>(BB->front())) 148 FoldSingleEntryPHINodes(BB, AA, MemDep); 149 150 // Delete the unconditional branch from the predecessor... 151 PredBB->getInstList().pop_back(); 152 153 // Make all PHI nodes that referred to BB now refer to Pred as their 154 // source... 155 BB->replaceAllUsesWith(PredBB); 156 157 // Move all definitions in the successor to the predecessor... 158 PredBB->getInstList().splice(PredBB->end(), BB->getInstList()); 159 160 // Inherit predecessors name if it exists. 161 if (!PredBB->hasName()) 162 PredBB->takeName(BB); 163 164 // Finally, erase the old block and update dominator info. 165 if (DT) 166 if (DomTreeNode *DTN = DT->getNode(BB)) { 167 DomTreeNode *PredDTN = DT->getNode(PredBB); 168 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end()); 169 for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(), 170 DE = Children.end(); 171 DI != DE; ++DI) 172 DT->changeImmediateDominator(*DI, PredDTN); 173 174 DT->eraseNode(BB); 175 } 176 177 if (LI) 178 LI->removeBlock(BB); 179 180 if (MemDep) 181 MemDep->invalidateCachedPredecessors(); 182 183 BB->eraseFromParent(); 184 return true; 185 } 186 187 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI) 188 /// with a value, then remove and delete the original instruction. 189 /// 190 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL, 191 BasicBlock::iterator &BI, Value *V) { 192 Instruction &I = *BI; 193 // Replaces all of the uses of the instruction with uses of the value 194 I.replaceAllUsesWith(V); 195 196 // Make sure to propagate a name if there is one already. 197 if (I.hasName() && !V->hasName()) 198 V->takeName(&I); 199 200 // Delete the unnecessary instruction now... 201 BI = BIL.erase(BI); 202 } 203 204 205 /// ReplaceInstWithInst - Replace the instruction specified by BI with the 206 /// instruction specified by I. The original instruction is deleted and BI is 207 /// updated to point to the new instruction. 208 /// 209 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL, 210 BasicBlock::iterator &BI, Instruction *I) { 211 assert(I->getParent() == nullptr && 212 "ReplaceInstWithInst: Instruction already inserted into basic block!"); 213 214 // Copy debug location to newly added instruction, if it wasn't already set 215 // by the caller. 216 if (!I->getDebugLoc()) 217 I->setDebugLoc(BI->getDebugLoc()); 218 219 // Insert the new instruction into the basic block... 220 BasicBlock::iterator New = BIL.insert(BI, I); 221 222 // Replace all uses of the old instruction, and delete it. 223 ReplaceInstWithValue(BIL, BI, I); 224 225 // Move BI back to point to the newly inserted instruction 226 BI = New; 227 } 228 229 /// ReplaceInstWithInst - Replace the instruction specified by From with the 230 /// instruction specified by To. 231 /// 232 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) { 233 BasicBlock::iterator BI(From); 234 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To); 235 } 236 237 /// SplitEdge - Split the edge connecting specified block. Pass P must 238 /// not be NULL. 239 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT, 240 LoopInfo *LI) { 241 unsigned SuccNum = GetSuccessorNumber(BB, Succ); 242 243 // If this is a critical edge, let SplitCriticalEdge do it. 244 TerminatorInst *LatchTerm = BB->getTerminator(); 245 if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI) 246 .setPreserveLCSSA())) 247 return LatchTerm->getSuccessor(SuccNum); 248 249 // If the edge isn't critical, then BB has a single successor or Succ has a 250 // single pred. Split the block. 251 if (BasicBlock *SP = Succ->getSinglePredecessor()) { 252 // If the successor only has a single pred, split the top of the successor 253 // block. 254 assert(SP == BB && "CFG broken"); 255 SP = nullptr; 256 return SplitBlock(Succ, Succ->begin(), DT, LI); 257 } 258 259 // Otherwise, if BB has a single successor, split it at the bottom of the 260 // block. 261 assert(BB->getTerminator()->getNumSuccessors() == 1 && 262 "Should have a single succ!"); 263 return SplitBlock(BB, BB->getTerminator(), DT, LI); 264 } 265 266 unsigned 267 llvm::SplitAllCriticalEdges(Function &F, 268 const CriticalEdgeSplittingOptions &Options) { 269 unsigned NumBroken = 0; 270 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { 271 TerminatorInst *TI = I->getTerminator(); 272 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI)) 273 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 274 if (SplitCriticalEdge(TI, i, Options)) 275 ++NumBroken; 276 } 277 return NumBroken; 278 } 279 280 /// SplitBlock - Split the specified block at the specified instruction - every 281 /// thing before SplitPt stays in Old and everything starting with SplitPt moves 282 /// to a new block. The two blocks are joined by an unconditional branch and 283 /// the loop info is updated. 284 /// 285 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, 286 DominatorTree *DT, LoopInfo *LI) { 287 BasicBlock::iterator SplitIt = SplitPt; 288 while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt)) 289 ++SplitIt; 290 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split"); 291 292 // The new block lives in whichever loop the old one did. This preserves 293 // LCSSA as well, because we force the split point to be after any PHI nodes. 294 if (LI) 295 if (Loop *L = LI->getLoopFor(Old)) 296 L->addBasicBlockToLoop(New, *LI); 297 298 if (DT) 299 // Old dominates New. New node dominates all other nodes dominated by Old. 300 if (DomTreeNode *OldNode = DT->getNode(Old)) { 301 std::vector<DomTreeNode *> Children; 302 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end(); 303 I != E; ++I) 304 Children.push_back(*I); 305 306 DomTreeNode *NewNode = DT->addNewBlock(New, Old); 307 for (std::vector<DomTreeNode *>::iterator I = Children.begin(), 308 E = Children.end(); I != E; ++I) 309 DT->changeImmediateDominator(*I, NewNode); 310 } 311 312 return New; 313 } 314 315 /// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA 316 /// analysis information. 317 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, 318 ArrayRef<BasicBlock *> Preds, 319 DominatorTree *DT, LoopInfo *LI, 320 bool PreserveLCSSA, bool &HasLoopExit) { 321 // Update dominator tree if available. 322 if (DT) 323 DT->splitBlock(NewBB); 324 325 // The rest of the logic is only relevant for updating the loop structures. 326 if (!LI) 327 return; 328 329 Loop *L = LI->getLoopFor(OldBB); 330 331 // If we need to preserve loop analyses, collect some information about how 332 // this split will affect loops. 333 bool IsLoopEntry = !!L; 334 bool SplitMakesNewLoopHeader = false; 335 for (ArrayRef<BasicBlock *>::iterator i = Preds.begin(), e = Preds.end(); 336 i != e; ++i) { 337 BasicBlock *Pred = *i; 338 339 // If we need to preserve LCSSA, determine if any of the preds is a loop 340 // exit. 341 if (PreserveLCSSA) 342 if (Loop *PL = LI->getLoopFor(Pred)) 343 if (!PL->contains(OldBB)) 344 HasLoopExit = true; 345 346 // If we need to preserve LoopInfo, note whether any of the preds crosses 347 // an interesting loop boundary. 348 if (!L) 349 continue; 350 if (L->contains(Pred)) 351 IsLoopEntry = false; 352 else 353 SplitMakesNewLoopHeader = true; 354 } 355 356 // Unless we have a loop for OldBB, nothing else to do here. 357 if (!L) 358 return; 359 360 if (IsLoopEntry) { 361 // Add the new block to the nearest enclosing loop (and not an adjacent 362 // loop). To find this, examine each of the predecessors and determine which 363 // loops enclose them, and select the most-nested loop which contains the 364 // loop containing the block being split. 365 Loop *InnermostPredLoop = nullptr; 366 for (ArrayRef<BasicBlock*>::iterator 367 i = Preds.begin(), e = Preds.end(); i != e; ++i) { 368 BasicBlock *Pred = *i; 369 if (Loop *PredLoop = LI->getLoopFor(Pred)) { 370 // Seek a loop which actually contains the block being split (to avoid 371 // adjacent loops). 372 while (PredLoop && !PredLoop->contains(OldBB)) 373 PredLoop = PredLoop->getParentLoop(); 374 375 // Select the most-nested of these loops which contains the block. 376 if (PredLoop && PredLoop->contains(OldBB) && 377 (!InnermostPredLoop || 378 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth())) 379 InnermostPredLoop = PredLoop; 380 } 381 } 382 383 if (InnermostPredLoop) 384 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI); 385 } else { 386 L->addBasicBlockToLoop(NewBB, *LI); 387 if (SplitMakesNewLoopHeader) 388 L->moveToHeader(NewBB); 389 } 390 } 391 392 /// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming 393 /// from NewBB. This also updates AliasAnalysis, if available. 394 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, 395 ArrayRef<BasicBlock *> Preds, BranchInst *BI, 396 AliasAnalysis *AA, bool HasLoopExit) { 397 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB. 398 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end()); 399 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) { 400 PHINode *PN = cast<PHINode>(I++); 401 402 // Check to see if all of the values coming in are the same. If so, we 403 // don't need to create a new PHI node, unless it's needed for LCSSA. 404 Value *InVal = nullptr; 405 if (!HasLoopExit) { 406 InVal = PN->getIncomingValueForBlock(Preds[0]); 407 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 408 if (!PredSet.count(PN->getIncomingBlock(i))) 409 continue; 410 if (!InVal) 411 InVal = PN->getIncomingValue(i); 412 else if (InVal != PN->getIncomingValue(i)) { 413 InVal = nullptr; 414 break; 415 } 416 } 417 } 418 419 if (InVal) { 420 // If all incoming values for the new PHI would be the same, just don't 421 // make a new PHI. Instead, just remove the incoming values from the old 422 // PHI. 423 424 // NOTE! This loop walks backwards for a reason! First off, this minimizes 425 // the cost of removal if we end up removing a large number of values, and 426 // second off, this ensures that the indices for the incoming values 427 // aren't invalidated when we remove one. 428 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) 429 if (PredSet.count(PN->getIncomingBlock(i))) 430 PN->removeIncomingValue(i, false); 431 432 // Add an incoming value to the PHI node in the loop for the preheader 433 // edge. 434 PN->addIncoming(InVal, NewBB); 435 continue; 436 } 437 438 // If the values coming into the block are not the same, we need a new 439 // PHI. 440 // Create the new PHI node, insert it into NewBB at the end of the block 441 PHINode *NewPHI = 442 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI); 443 if (AA) 444 AA->copyValue(PN, NewPHI); 445 446 // NOTE! This loop walks backwards for a reason! First off, this minimizes 447 // the cost of removal if we end up removing a large number of values, and 448 // second off, this ensures that the indices for the incoming values aren't 449 // invalidated when we remove one. 450 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) { 451 BasicBlock *IncomingBB = PN->getIncomingBlock(i); 452 if (PredSet.count(IncomingBB)) { 453 Value *V = PN->removeIncomingValue(i, false); 454 NewPHI->addIncoming(V, IncomingBB); 455 } 456 } 457 458 PN->addIncoming(NewPHI, NewBB); 459 } 460 } 461 462 /// SplitBlockPredecessors - This method introduces at least one new basic block 463 /// into the function and moves some of the predecessors of BB to be 464 /// predecessors of the new block. The new predecessors are indicated by the 465 /// Preds array. The new block is given a suffix of 'Suffix'. Returns new basic 466 /// block to which predecessors from Preds are now pointing. 467 /// 468 /// If BB is a landingpad block then additional basicblock might be introduced. 469 /// It will have suffix of 'Suffix'+".split_lp". 470 /// See SplitLandingPadPredecessors for more details on this case. 471 /// 472 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree, 473 /// LoopInfo, and LCCSA but no other analyses. In particular, it does not 474 /// preserve LoopSimplify (because it's complicated to handle the case where one 475 /// of the edges being split is an exit of a loop with other exits). 476 /// 477 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 478 ArrayRef<BasicBlock *> Preds, 479 const char *Suffix, AliasAnalysis *AA, 480 DominatorTree *DT, LoopInfo *LI, 481 bool PreserveLCSSA) { 482 // For the landingpads we need to act a bit differently. 483 // Delegate this work to the SplitLandingPadPredecessors. 484 if (BB->isLandingPad()) { 485 SmallVector<BasicBlock*, 2> NewBBs; 486 std::string NewName = std::string(Suffix) + ".split-lp"; 487 488 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), 489 NewBBs, AA, DT, LI, PreserveLCSSA); 490 return NewBBs[0]; 491 } 492 493 // Create new basic block, insert right before the original block. 494 BasicBlock *NewBB = BasicBlock::Create( 495 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB); 496 497 // The new block unconditionally branches to the old block. 498 BranchInst *BI = BranchInst::Create(BB, NewBB); 499 BI->setDebugLoc(BB->getFirstNonPHI()->getDebugLoc()); 500 501 // Move the edges from Preds to point to NewBB instead of BB. 502 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 503 // This is slightly more strict than necessary; the minimum requirement 504 // is that there be no more than one indirectbr branching to BB. And 505 // all BlockAddress uses would need to be updated. 506 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 507 "Cannot split an edge from an IndirectBrInst"); 508 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB); 509 } 510 511 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI 512 // node becomes an incoming value for BB's phi node. However, if the Preds 513 // list is empty, we need to insert dummy entries into the PHI nodes in BB to 514 // account for the newly created predecessor. 515 if (Preds.size() == 0) { 516 // Insert dummy values as the incoming value. 517 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) 518 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB); 519 return NewBB; 520 } 521 522 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 523 bool HasLoopExit = false; 524 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA, 525 HasLoopExit); 526 527 // Update the PHI nodes in BB with the values coming from NewBB. 528 UpdatePHINodes(BB, NewBB, Preds, BI, AA, HasLoopExit); 529 return NewBB; 530 } 531 532 /// SplitLandingPadPredecessors - This method transforms the landing pad, 533 /// OrigBB, by introducing two new basic blocks into the function. One of those 534 /// new basic blocks gets the predecessors listed in Preds. The other basic 535 /// block gets the remaining predecessors of OrigBB. The landingpad instruction 536 /// OrigBB is clone into both of the new basic blocks. The new blocks are given 537 /// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector. 538 /// 539 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree, 540 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular, 541 /// it does not preserve LoopSimplify (because it's complicated to handle the 542 /// case where one of the edges being split is an exit of a loop with other 543 /// exits). 544 /// 545 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB, 546 ArrayRef<BasicBlock *> Preds, 547 const char *Suffix1, const char *Suffix2, 548 SmallVectorImpl<BasicBlock *> &NewBBs, 549 AliasAnalysis *AA, DominatorTree *DT, 550 LoopInfo *LI, bool PreserveLCSSA) { 551 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!"); 552 553 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert 554 // it right before the original block. 555 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(), 556 OrigBB->getName() + Suffix1, 557 OrigBB->getParent(), OrigBB); 558 NewBBs.push_back(NewBB1); 559 560 // The new block unconditionally branches to the old block. 561 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1); 562 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 563 564 // Move the edges from Preds to point to NewBB1 instead of OrigBB. 565 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 566 // This is slightly more strict than necessary; the minimum requirement 567 // is that there be no more than one indirectbr branching to BB. And 568 // all BlockAddress uses would need to be updated. 569 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 570 "Cannot split an edge from an IndirectBrInst"); 571 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1); 572 } 573 574 bool HasLoopExit = false; 575 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA, 576 HasLoopExit); 577 578 // Update the PHI nodes in OrigBB with the values coming from NewBB1. 579 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, AA, HasLoopExit); 580 581 // Move the remaining edges from OrigBB to point to NewBB2. 582 SmallVector<BasicBlock*, 8> NewBB2Preds; 583 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB); 584 i != e; ) { 585 BasicBlock *Pred = *i++; 586 if (Pred == NewBB1) continue; 587 assert(!isa<IndirectBrInst>(Pred->getTerminator()) && 588 "Cannot split an edge from an IndirectBrInst"); 589 NewBB2Preds.push_back(Pred); 590 e = pred_end(OrigBB); 591 } 592 593 BasicBlock *NewBB2 = nullptr; 594 if (!NewBB2Preds.empty()) { 595 // Create another basic block for the rest of OrigBB's predecessors. 596 NewBB2 = BasicBlock::Create(OrigBB->getContext(), 597 OrigBB->getName() + Suffix2, 598 OrigBB->getParent(), OrigBB); 599 NewBBs.push_back(NewBB2); 600 601 // The new block unconditionally branches to the old block. 602 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2); 603 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 604 605 // Move the remaining edges from OrigBB to point to NewBB2. 606 for (SmallVectorImpl<BasicBlock*>::iterator 607 i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i) 608 (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2); 609 610 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 611 HasLoopExit = false; 612 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, 613 PreserveLCSSA, HasLoopExit); 614 615 // Update the PHI nodes in OrigBB with the values coming from NewBB2. 616 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, AA, HasLoopExit); 617 } 618 619 LandingPadInst *LPad = OrigBB->getLandingPadInst(); 620 Instruction *Clone1 = LPad->clone(); 621 Clone1->setName(Twine("lpad") + Suffix1); 622 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1); 623 624 if (NewBB2) { 625 Instruction *Clone2 = LPad->clone(); 626 Clone2->setName(Twine("lpad") + Suffix2); 627 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2); 628 629 // Create a PHI node for the two cloned landingpad instructions. 630 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad); 631 PN->addIncoming(Clone1, NewBB1); 632 PN->addIncoming(Clone2, NewBB2); 633 LPad->replaceAllUsesWith(PN); 634 LPad->eraseFromParent(); 635 } else { 636 // There is no second clone. Just replace the landing pad with the first 637 // clone. 638 LPad->replaceAllUsesWith(Clone1); 639 LPad->eraseFromParent(); 640 } 641 } 642 643 /// FoldReturnIntoUncondBranch - This method duplicates the specified return 644 /// instruction into a predecessor which ends in an unconditional branch. If 645 /// the return instruction returns a value defined by a PHI, propagate the 646 /// right value into the return. It returns the new return instruction in the 647 /// predecessor. 648 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, 649 BasicBlock *Pred) { 650 Instruction *UncondBranch = Pred->getTerminator(); 651 // Clone the return and add it to the end of the predecessor. 652 Instruction *NewRet = RI->clone(); 653 Pred->getInstList().push_back(NewRet); 654 655 // If the return instruction returns a value, and if the value was a 656 // PHI node in "BB", propagate the right value into the return. 657 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end(); 658 i != e; ++i) { 659 Value *V = *i; 660 Instruction *NewBC = nullptr; 661 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) { 662 // Return value might be bitcasted. Clone and insert it before the 663 // return instruction. 664 V = BCI->getOperand(0); 665 NewBC = BCI->clone(); 666 Pred->getInstList().insert(NewRet, NewBC); 667 *i = NewBC; 668 } 669 if (PHINode *PN = dyn_cast<PHINode>(V)) { 670 if (PN->getParent() == BB) { 671 if (NewBC) 672 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred)); 673 else 674 *i = PN->getIncomingValueForBlock(Pred); 675 } 676 } 677 } 678 679 // Update any PHI nodes in the returning block to realize that we no 680 // longer branch to them. 681 BB->removePredecessor(Pred); 682 UncondBranch->eraseFromParent(); 683 return cast<ReturnInst>(NewRet); 684 } 685 686 /// SplitBlockAndInsertIfThen - Split the containing block at the 687 /// specified instruction - everything before and including SplitBefore stays 688 /// in the old basic block, and everything after SplitBefore is moved to a 689 /// new block. The two blocks are connected by a conditional branch 690 /// (with value of Cmp being the condition). 691 /// Before: 692 /// Head 693 /// SplitBefore 694 /// Tail 695 /// After: 696 /// Head 697 /// if (Cond) 698 /// ThenBlock 699 /// SplitBefore 700 /// Tail 701 /// 702 /// If Unreachable is true, then ThenBlock ends with 703 /// UnreachableInst, otherwise it branches to Tail. 704 /// Returns the NewBasicBlock's terminator. 705 706 TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond, 707 Instruction *SplitBefore, 708 bool Unreachable, 709 MDNode *BranchWeights, 710 DominatorTree *DT) { 711 BasicBlock *Head = SplitBefore->getParent(); 712 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore); 713 TerminatorInst *HeadOldTerm = Head->getTerminator(); 714 LLVMContext &C = Head->getContext(); 715 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 716 TerminatorInst *CheckTerm; 717 if (Unreachable) 718 CheckTerm = new UnreachableInst(C, ThenBlock); 719 else 720 CheckTerm = BranchInst::Create(Tail, ThenBlock); 721 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc()); 722 BranchInst *HeadNewTerm = 723 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond); 724 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 725 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 726 727 if (DT) { 728 if (DomTreeNode *OldNode = DT->getNode(Head)) { 729 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 730 731 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head); 732 for (auto Child : Children) 733 DT->changeImmediateDominator(Child, NewNode); 734 735 // Head dominates ThenBlock. 736 DT->addNewBlock(ThenBlock, Head); 737 } 738 } 739 740 return CheckTerm; 741 } 742 743 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, 744 /// but also creates the ElseBlock. 745 /// Before: 746 /// Head 747 /// SplitBefore 748 /// Tail 749 /// After: 750 /// Head 751 /// if (Cond) 752 /// ThenBlock 753 /// else 754 /// ElseBlock 755 /// SplitBefore 756 /// Tail 757 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, 758 TerminatorInst **ThenTerm, 759 TerminatorInst **ElseTerm, 760 MDNode *BranchWeights) { 761 BasicBlock *Head = SplitBefore->getParent(); 762 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore); 763 TerminatorInst *HeadOldTerm = Head->getTerminator(); 764 LLVMContext &C = Head->getContext(); 765 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 766 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 767 *ThenTerm = BranchInst::Create(Tail, ThenBlock); 768 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 769 *ElseTerm = BranchInst::Create(Tail, ElseBlock); 770 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 771 BranchInst *HeadNewTerm = 772 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond); 773 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 774 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 775 } 776 777 778 /// GetIfCondition - Given a basic block (BB) with two predecessors, 779 /// check to see if the merge at this block is due 780 /// to an "if condition". If so, return the boolean condition that determines 781 /// which entry into BB will be taken. Also, return by references the block 782 /// that will be entered from if the condition is true, and the block that will 783 /// be entered if the condition is false. 784 /// 785 /// This does no checking to see if the true/false blocks have large or unsavory 786 /// instructions in them. 787 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, 788 BasicBlock *&IfFalse) { 789 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin()); 790 BasicBlock *Pred1 = nullptr; 791 BasicBlock *Pred2 = nullptr; 792 793 if (SomePHI) { 794 if (SomePHI->getNumIncomingValues() != 2) 795 return nullptr; 796 Pred1 = SomePHI->getIncomingBlock(0); 797 Pred2 = SomePHI->getIncomingBlock(1); 798 } else { 799 pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 800 if (PI == PE) // No predecessor 801 return nullptr; 802 Pred1 = *PI++; 803 if (PI == PE) // Only one predecessor 804 return nullptr; 805 Pred2 = *PI++; 806 if (PI != PE) // More than two predecessors 807 return nullptr; 808 } 809 810 // We can only handle branches. Other control flow will be lowered to 811 // branches if possible anyway. 812 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator()); 813 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator()); 814 if (!Pred1Br || !Pred2Br) 815 return nullptr; 816 817 // Eliminate code duplication by ensuring that Pred1Br is conditional if 818 // either are. 819 if (Pred2Br->isConditional()) { 820 // If both branches are conditional, we don't have an "if statement". In 821 // reality, we could transform this case, but since the condition will be 822 // required anyway, we stand no chance of eliminating it, so the xform is 823 // probably not profitable. 824 if (Pred1Br->isConditional()) 825 return nullptr; 826 827 std::swap(Pred1, Pred2); 828 std::swap(Pred1Br, Pred2Br); 829 } 830 831 if (Pred1Br->isConditional()) { 832 // The only thing we have to watch out for here is to make sure that Pred2 833 // doesn't have incoming edges from other blocks. If it does, the condition 834 // doesn't dominate BB. 835 if (!Pred2->getSinglePredecessor()) 836 return nullptr; 837 838 // If we found a conditional branch predecessor, make sure that it branches 839 // to BB and Pred2Br. If it doesn't, this isn't an "if statement". 840 if (Pred1Br->getSuccessor(0) == BB && 841 Pred1Br->getSuccessor(1) == Pred2) { 842 IfTrue = Pred1; 843 IfFalse = Pred2; 844 } else if (Pred1Br->getSuccessor(0) == Pred2 && 845 Pred1Br->getSuccessor(1) == BB) { 846 IfTrue = Pred2; 847 IfFalse = Pred1; 848 } else { 849 // We know that one arm of the conditional goes to BB, so the other must 850 // go somewhere unrelated, and this must not be an "if statement". 851 return nullptr; 852 } 853 854 return Pred1Br->getCondition(); 855 } 856 857 // Ok, if we got here, both predecessors end with an unconditional branch to 858 // BB. Don't panic! If both blocks only have a single (identical) 859 // predecessor, and THAT is a conditional branch, then we're all ok! 860 BasicBlock *CommonPred = Pred1->getSinglePredecessor(); 861 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor()) 862 return nullptr; 863 864 // Otherwise, if this is a conditional branch, then we can use it! 865 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator()); 866 if (!BI) return nullptr; 867 868 assert(BI->isConditional() && "Two successors but not conditional?"); 869 if (BI->getSuccessor(0) == Pred1) { 870 IfTrue = Pred1; 871 IfFalse = Pred2; 872 } else { 873 IfTrue = Pred2; 874 IfFalse = Pred1; 875 } 876 return BI->getCondition(); 877 } 878