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