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