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/Support/Debug.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include "llvm/Transforms/Utils/Local.h" 44 #include <cassert> 45 #include <cstdint> 46 #include <string> 47 #include <utility> 48 #include <vector> 49 50 using namespace llvm; 51 52 #define DEBUG_TYPE "basicblock-utils" 53 54 void llvm::DetatchDeadBlocks( 55 ArrayRef<BasicBlock *> BBs, 56 SmallVectorImpl<DominatorTree::UpdateType> *Updates, 57 bool KeepOneInputPHIs) { 58 for (auto *BB : BBs) { 59 // Loop through all of our successors and make sure they know that one 60 // of their predecessors is going away. 61 SmallPtrSet<BasicBlock *, 4> UniqueSuccessors; 62 for (BasicBlock *Succ : successors(BB)) { 63 Succ->removePredecessor(BB, KeepOneInputPHIs); 64 if (Updates && UniqueSuccessors.insert(Succ).second) 65 Updates->push_back({DominatorTree::Delete, BB, Succ}); 66 } 67 68 // Zap all the instructions in the block. 69 while (!BB->empty()) { 70 Instruction &I = BB->back(); 71 // If this instruction is used, replace uses with an arbitrary value. 72 // Because control flow can't get here, we don't care what we replace the 73 // value with. Note that since this block is unreachable, and all values 74 // contained within it must dominate their uses, that all uses will 75 // eventually be removed (they are themselves dead). 76 if (!I.use_empty()) 77 I.replaceAllUsesWith(UndefValue::get(I.getType())); 78 BB->getInstList().pop_back(); 79 } 80 new UnreachableInst(BB->getContext(), BB); 81 assert(BB->getInstList().size() == 1 && 82 isa<UnreachableInst>(BB->getTerminator()) && 83 "The successor list of BB isn't empty before " 84 "applying corresponding DTU updates."); 85 } 86 } 87 88 void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU, 89 bool KeepOneInputPHIs) { 90 DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs); 91 } 92 93 void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU, 94 bool KeepOneInputPHIs) { 95 #ifndef NDEBUG 96 // Make sure that all predecessors of each dead block is also dead. 97 SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end()); 98 assert(Dead.size() == BBs.size() && "Duplicating blocks?"); 99 for (auto *BB : Dead) 100 for (BasicBlock *Pred : predecessors(BB)) 101 assert(Dead.count(Pred) && "All predecessors must be dead!"); 102 #endif 103 104 SmallVector<DominatorTree::UpdateType, 4> Updates; 105 DetatchDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs); 106 107 if (DTU) 108 DTU->applyUpdates(Updates); 109 110 for (BasicBlock *BB : BBs) 111 if (DTU) 112 DTU->deleteBB(BB); 113 else 114 BB->eraseFromParent(); 115 } 116 117 bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU, 118 bool KeepOneInputPHIs) { 119 df_iterator_default_set<BasicBlock*> Reachable; 120 121 // Mark all reachable blocks. 122 for (BasicBlock *BB : depth_first_ext(&F, Reachable)) 123 (void)BB/* Mark all reachable blocks */; 124 125 // Collect all dead blocks. 126 std::vector<BasicBlock*> DeadBlocks; 127 for (BasicBlock &BB : F) 128 if (!Reachable.count(&BB)) 129 DeadBlocks.push_back(&BB); 130 131 // Delete the dead blocks. 132 DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs); 133 134 return !DeadBlocks.empty(); 135 } 136 137 bool llvm::FoldSingleEntryPHINodes(BasicBlock *BB, 138 MemoryDependenceResults *MemDep) { 139 if (!isa<PHINode>(BB->begin())) 140 return false; 141 142 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 143 if (PN->getIncomingValue(0) != PN) 144 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 145 else 146 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 147 148 if (MemDep) 149 MemDep->removeInstruction(PN); // Memdep updates AA itself. 150 151 PN->eraseFromParent(); 152 } 153 return true; 154 } 155 156 bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI, 157 MemorySSAUpdater *MSSAU) { 158 // Recursively deleting a PHI may cause multiple PHIs to be deleted 159 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete. 160 SmallVector<WeakTrackingVH, 8> PHIs; 161 for (PHINode &PN : BB->phis()) 162 PHIs.push_back(&PN); 163 164 bool Changed = false; 165 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 166 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*())) 167 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU); 168 169 return Changed; 170 } 171 172 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU, 173 LoopInfo *LI, MemorySSAUpdater *MSSAU, 174 MemoryDependenceResults *MemDep, 175 bool PredecessorWithTwoSuccessors) { 176 if (BB->hasAddressTaken()) 177 return false; 178 179 // Can't merge if there are multiple predecessors, or no predecessors. 180 BasicBlock *PredBB = BB->getUniquePredecessor(); 181 if (!PredBB) return false; 182 183 // Don't break self-loops. 184 if (PredBB == BB) return false; 185 // Don't break unwinding instructions. 186 if (PredBB->getTerminator()->isExceptionalTerminator()) 187 return false; 188 189 // Can't merge if there are multiple distinct successors. 190 if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB) 191 return false; 192 193 // Currently only allow PredBB to have two predecessors, one being BB. 194 // Update BI to branch to BB's only successor instead of BB. 195 BranchInst *PredBB_BI; 196 BasicBlock *NewSucc = nullptr; 197 unsigned FallThruPath; 198 if (PredecessorWithTwoSuccessors) { 199 if (!(PredBB_BI = dyn_cast<BranchInst>(PredBB->getTerminator()))) 200 return false; 201 BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator()); 202 if (!BB_JmpI || !BB_JmpI->isUnconditional()) 203 return false; 204 NewSucc = BB_JmpI->getSuccessor(0); 205 FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1; 206 } 207 208 // Can't merge if there is PHI loop. 209 for (PHINode &PN : BB->phis()) 210 if (llvm::is_contained(PN.incoming_values(), &PN)) 211 return false; 212 213 LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into " 214 << PredBB->getName() << "\n"); 215 216 // Begin by getting rid of unneeded PHIs. 217 SmallVector<AssertingVH<Value>, 4> IncomingValues; 218 if (isa<PHINode>(BB->front())) { 219 for (PHINode &PN : BB->phis()) 220 if (!isa<PHINode>(PN.getIncomingValue(0)) || 221 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB) 222 IncomingValues.push_back(PN.getIncomingValue(0)); 223 FoldSingleEntryPHINodes(BB, MemDep); 224 } 225 226 // DTU update: Collect all the edges that exit BB. 227 // These dominator edges will be redirected from Pred. 228 std::vector<DominatorTree::UpdateType> Updates; 229 if (DTU) { 230 SmallSetVector<BasicBlock *, 2> UniqueSuccessors(succ_begin(BB), 231 succ_end(BB)); 232 Updates.reserve(1 + (2 * UniqueSuccessors.size())); 233 // Add insert edges first. Experimentally, for the particular case of two 234 // blocks that can be merged, with a single successor and single predecessor 235 // respectively, it is beneficial to have all insert updates first. Deleting 236 // edges first may lead to unreachable blocks, followed by inserting edges 237 // making the blocks reachable again. Such DT updates lead to high compile 238 // times. We add inserts before deletes here to reduce compile time. 239 for (BasicBlock *UniqueSuccessor : UniqueSuccessors) 240 // This successor of BB may already have PredBB as a predecessor. 241 if (!llvm::is_contained(successors(PredBB), UniqueSuccessor)) 242 Updates.push_back({DominatorTree::Insert, PredBB, UniqueSuccessor}); 243 for (BasicBlock *UniqueSuccessor : UniqueSuccessors) 244 Updates.push_back({DominatorTree::Delete, BB, UniqueSuccessor}); 245 Updates.push_back({DominatorTree::Delete, PredBB, BB}); 246 } 247 248 Instruction *PTI = PredBB->getTerminator(); 249 Instruction *STI = BB->getTerminator(); 250 Instruction *Start = &*BB->begin(); 251 // If there's nothing to move, mark the starting instruction as the last 252 // instruction in the block. Terminator instruction is handled separately. 253 if (Start == STI) 254 Start = PTI; 255 256 // Move all definitions in the successor to the predecessor... 257 PredBB->getInstList().splice(PTI->getIterator(), BB->getInstList(), 258 BB->begin(), STI->getIterator()); 259 260 if (MSSAU) 261 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start); 262 263 // Make all PHI nodes that referred to BB now refer to Pred as their 264 // source... 265 BB->replaceAllUsesWith(PredBB); 266 267 if (PredecessorWithTwoSuccessors) { 268 // Delete the unconditional branch from BB. 269 BB->getInstList().pop_back(); 270 271 // Update branch in the predecessor. 272 PredBB_BI->setSuccessor(FallThruPath, NewSucc); 273 } else { 274 // Delete the unconditional branch from the predecessor. 275 PredBB->getInstList().pop_back(); 276 277 // Move terminator instruction. 278 PredBB->getInstList().splice(PredBB->end(), BB->getInstList()); 279 280 // Terminator may be a memory accessing instruction too. 281 if (MSSAU) 282 if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>( 283 MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator()))) 284 MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End); 285 } 286 // Add unreachable to now empty BB. 287 new UnreachableInst(BB->getContext(), BB); 288 289 // Inherit predecessors name if it exists. 290 if (!PredBB->hasName()) 291 PredBB->takeName(BB); 292 293 if (LI) 294 LI->removeBlock(BB); 295 296 if (MemDep) 297 MemDep->invalidateCachedPredecessors(); 298 299 // Finally, erase the old block and update dominator info. 300 if (DTU) { 301 assert(BB->getInstList().size() == 1 && 302 isa<UnreachableInst>(BB->getTerminator()) && 303 "The successor list of BB isn't empty before " 304 "applying corresponding DTU updates."); 305 DTU->applyUpdates(Updates); 306 DTU->deleteBB(BB); 307 } else { 308 BB->eraseFromParent(); // Nuke BB if DTU is nullptr. 309 } 310 311 return true; 312 } 313 314 bool llvm::MergeBlockSuccessorsIntoGivenBlocks( 315 SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L, DomTreeUpdater *DTU, 316 LoopInfo *LI) { 317 assert(!MergeBlocks.empty() && "MergeBlocks should not be empty"); 318 319 bool BlocksHaveBeenMerged = false; 320 while (!MergeBlocks.empty()) { 321 BasicBlock *BB = *MergeBlocks.begin(); 322 BasicBlock *Dest = BB->getSingleSuccessor(); 323 if (Dest && (!L || L->contains(Dest))) { 324 BasicBlock *Fold = Dest->getUniquePredecessor(); 325 (void)Fold; 326 if (MergeBlockIntoPredecessor(Dest, DTU, LI)) { 327 assert(Fold == BB && 328 "Expecting BB to be unique predecessor of the Dest block"); 329 MergeBlocks.erase(Dest); 330 BlocksHaveBeenMerged = true; 331 } else 332 MergeBlocks.erase(BB); 333 } else 334 MergeBlocks.erase(BB); 335 } 336 return BlocksHaveBeenMerged; 337 } 338 339 /// Remove redundant instructions within sequences of consecutive dbg.value 340 /// instructions. This is done using a backward scan to keep the last dbg.value 341 /// describing a specific variable/fragment. 342 /// 343 /// BackwardScan strategy: 344 /// ---------------------- 345 /// Given a sequence of consecutive DbgValueInst like this 346 /// 347 /// dbg.value ..., "x", FragmentX1 (*) 348 /// dbg.value ..., "y", FragmentY1 349 /// dbg.value ..., "x", FragmentX2 350 /// dbg.value ..., "x", FragmentX1 (**) 351 /// 352 /// then the instruction marked with (*) can be removed (it is guaranteed to be 353 /// obsoleted by the instruction marked with (**) as the latter instruction is 354 /// describing the same variable using the same fragment info). 355 /// 356 /// Possible improvements: 357 /// - Check fully overlapping fragments and not only identical fragments. 358 /// - Support dbg.addr, dbg.declare. dbg.label, and possibly other meta 359 /// instructions being part of the sequence of consecutive instructions. 360 static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) { 361 SmallVector<DbgValueInst *, 8> ToBeRemoved; 362 SmallDenseSet<DebugVariable> VariableSet; 363 for (auto &I : reverse(*BB)) { 364 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) { 365 DebugVariable Key(DVI->getVariable(), 366 DVI->getExpression(), 367 DVI->getDebugLoc()->getInlinedAt()); 368 auto R = VariableSet.insert(Key); 369 // If the same variable fragment is described more than once it is enough 370 // to keep the last one (i.e. the first found since we for reverse 371 // iteration). 372 if (!R.second) 373 ToBeRemoved.push_back(DVI); 374 continue; 375 } 376 // Sequence with consecutive dbg.value instrs ended. Clear the map to 377 // restart identifying redundant instructions if case we find another 378 // dbg.value sequence. 379 VariableSet.clear(); 380 } 381 382 for (auto &Instr : ToBeRemoved) 383 Instr->eraseFromParent(); 384 385 return !ToBeRemoved.empty(); 386 } 387 388 /// Remove redundant dbg.value instructions using a forward scan. This can 389 /// remove a dbg.value instruction that is redundant due to indicating that a 390 /// variable has the same value as already being indicated by an earlier 391 /// dbg.value. 392 /// 393 /// ForwardScan strategy: 394 /// --------------------- 395 /// Given two identical dbg.value instructions, separated by a block of 396 /// instructions that isn't describing the same variable, like this 397 /// 398 /// dbg.value X1, "x", FragmentX1 (**) 399 /// <block of instructions, none being "dbg.value ..., "x", ..."> 400 /// dbg.value X1, "x", FragmentX1 (*) 401 /// 402 /// then the instruction marked with (*) can be removed. Variable "x" is already 403 /// described as being mapped to the SSA value X1. 404 /// 405 /// Possible improvements: 406 /// - Keep track of non-overlapping fragments. 407 static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) { 408 SmallVector<DbgValueInst *, 8> ToBeRemoved; 409 DenseMap<DebugVariable, std::pair<Value *, DIExpression *> > VariableMap; 410 for (auto &I : *BB) { 411 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) { 412 DebugVariable Key(DVI->getVariable(), 413 NoneType(), 414 DVI->getDebugLoc()->getInlinedAt()); 415 auto VMI = VariableMap.find(Key); 416 // Update the map if we found a new value/expression describing the 417 // variable, or if the variable wasn't mapped already. 418 if (VMI == VariableMap.end() || 419 VMI->second.first != DVI->getValue() || 420 VMI->second.second != DVI->getExpression()) { 421 VariableMap[Key] = { DVI->getValue(), DVI->getExpression() }; 422 continue; 423 } 424 // Found an identical mapping. Remember the instruction for later removal. 425 ToBeRemoved.push_back(DVI); 426 } 427 } 428 429 for (auto &Instr : ToBeRemoved) 430 Instr->eraseFromParent(); 431 432 return !ToBeRemoved.empty(); 433 } 434 435 bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) { 436 bool MadeChanges = false; 437 // By using the "backward scan" strategy before the "forward scan" strategy we 438 // can remove both dbg.value (2) and (3) in a situation like this: 439 // 440 // (1) dbg.value V1, "x", DIExpression() 441 // ... 442 // (2) dbg.value V2, "x", DIExpression() 443 // (3) dbg.value V1, "x", DIExpression() 444 // 445 // The backward scan will remove (2), it is made obsolete by (3). After 446 // getting (2) out of the way, the foward scan will remove (3) since "x" 447 // already is described as having the value V1 at (1). 448 MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB); 449 MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB); 450 451 if (MadeChanges) 452 LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: " 453 << BB->getName() << "\n"); 454 return MadeChanges; 455 } 456 457 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL, 458 BasicBlock::iterator &BI, Value *V) { 459 Instruction &I = *BI; 460 // Replaces all of the uses of the instruction with uses of the value 461 I.replaceAllUsesWith(V); 462 463 // Make sure to propagate a name if there is one already. 464 if (I.hasName() && !V->hasName()) 465 V->takeName(&I); 466 467 // Delete the unnecessary instruction now... 468 BI = BIL.erase(BI); 469 } 470 471 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL, 472 BasicBlock::iterator &BI, Instruction *I) { 473 assert(I->getParent() == nullptr && 474 "ReplaceInstWithInst: Instruction already inserted into basic block!"); 475 476 // Copy debug location to newly added instruction, if it wasn't already set 477 // by the caller. 478 if (!I->getDebugLoc()) 479 I->setDebugLoc(BI->getDebugLoc()); 480 481 // Insert the new instruction into the basic block... 482 BasicBlock::iterator New = BIL.insert(BI, I); 483 484 // Replace all uses of the old instruction, and delete it. 485 ReplaceInstWithValue(BIL, BI, I); 486 487 // Move BI back to point to the newly inserted instruction 488 BI = New; 489 } 490 491 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) { 492 BasicBlock::iterator BI(From); 493 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To); 494 } 495 496 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT, 497 LoopInfo *LI, MemorySSAUpdater *MSSAU, 498 const Twine &BBName) { 499 unsigned SuccNum = GetSuccessorNumber(BB, Succ); 500 501 // If this is a critical edge, let SplitCriticalEdge do it. 502 Instruction *LatchTerm = BB->getTerminator(); 503 if (SplitCriticalEdge( 504 LatchTerm, SuccNum, 505 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA(), 506 BBName)) 507 return LatchTerm->getSuccessor(SuccNum); 508 509 // If the edge isn't critical, then BB has a single successor or Succ has a 510 // single pred. Split the block. 511 if (BasicBlock *SP = Succ->getSinglePredecessor()) { 512 // If the successor only has a single pred, split the top of the successor 513 // block. 514 assert(SP == BB && "CFG broken"); 515 SP = nullptr; 516 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName, 517 /*Before=*/true); 518 } 519 520 // Otherwise, if BB has a single successor, split it at the bottom of the 521 // block. 522 assert(BB->getTerminator()->getNumSuccessors() == 1 && 523 "Should have a single succ!"); 524 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName); 525 } 526 527 unsigned 528 llvm::SplitAllCriticalEdges(Function &F, 529 const CriticalEdgeSplittingOptions &Options) { 530 unsigned NumBroken = 0; 531 for (BasicBlock &BB : F) { 532 Instruction *TI = BB.getTerminator(); 533 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI) && 534 !isa<CallBrInst>(TI)) 535 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 536 if (SplitCriticalEdge(TI, i, Options)) 537 ++NumBroken; 538 } 539 return NumBroken; 540 } 541 542 static BasicBlock *SplitBlockImpl(BasicBlock *Old, Instruction *SplitPt, 543 DomTreeUpdater *DTU, DominatorTree *DT, 544 LoopInfo *LI, MemorySSAUpdater *MSSAU, 545 const Twine &BBName, bool Before) { 546 if (Before) { 547 DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 548 return splitBlockBefore(Old, SplitPt, 549 DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU, 550 BBName); 551 } 552 BasicBlock::iterator SplitIt = SplitPt->getIterator(); 553 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) 554 ++SplitIt; 555 std::string Name = BBName.str(); 556 BasicBlock *New = Old->splitBasicBlock( 557 SplitIt, Name.empty() ? Old->getName() + ".split" : Name); 558 559 // The new block lives in whichever loop the old one did. This preserves 560 // LCSSA as well, because we force the split point to be after any PHI nodes. 561 if (LI) 562 if (Loop *L = LI->getLoopFor(Old)) 563 L->addBasicBlockToLoop(New, *LI); 564 565 if (DTU) { 566 SmallVector<DominatorTree::UpdateType, 8> Updates; 567 // Old dominates New. New node dominates all other nodes dominated by Old. 568 SmallSetVector<BasicBlock *, 8> UniqueSuccessorsOfOld(succ_begin(New), 569 succ_end(New)); 570 Updates.push_back({DominatorTree::Insert, Old, New}); 571 Updates.reserve(Updates.size() + 2 * UniqueSuccessorsOfOld.size()); 572 for (BasicBlock *UniqueSuccessorOfOld : UniqueSuccessorsOfOld) { 573 Updates.push_back({DominatorTree::Insert, New, UniqueSuccessorOfOld}); 574 Updates.push_back({DominatorTree::Delete, Old, UniqueSuccessorOfOld}); 575 } 576 577 DTU->applyUpdates(Updates); 578 } else if (DT) 579 // Old dominates New. New node dominates all other nodes dominated by Old. 580 if (DomTreeNode *OldNode = DT->getNode(Old)) { 581 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 582 583 DomTreeNode *NewNode = DT->addNewBlock(New, Old); 584 for (DomTreeNode *I : Children) 585 DT->changeImmediateDominator(I, NewNode); 586 } 587 588 // Move MemoryAccesses still tracked in Old, but part of New now. 589 // Update accesses in successor blocks accordingly. 590 if (MSSAU) 591 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin())); 592 593 return New; 594 } 595 596 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, 597 DominatorTree *DT, LoopInfo *LI, 598 MemorySSAUpdater *MSSAU, const Twine &BBName, 599 bool Before) { 600 return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName, 601 Before); 602 } 603 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, 604 DomTreeUpdater *DTU, LoopInfo *LI, 605 MemorySSAUpdater *MSSAU, const Twine &BBName, 606 bool Before) { 607 return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName, 608 Before); 609 } 610 611 BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, Instruction *SplitPt, 612 DomTreeUpdater *DTU, LoopInfo *LI, 613 MemorySSAUpdater *MSSAU, 614 const Twine &BBName) { 615 616 BasicBlock::iterator SplitIt = SplitPt->getIterator(); 617 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) 618 ++SplitIt; 619 std::string Name = BBName.str(); 620 BasicBlock *New = Old->splitBasicBlock( 621 SplitIt, Name.empty() ? Old->getName() + ".split" : Name, 622 /* Before=*/true); 623 624 // The new block lives in whichever loop the old one did. This preserves 625 // LCSSA as well, because we force the split point to be after any PHI nodes. 626 if (LI) 627 if (Loop *L = LI->getLoopFor(Old)) 628 L->addBasicBlockToLoop(New, *LI); 629 630 if (DTU) { 631 SmallVector<DominatorTree::UpdateType, 8> DTUpdates; 632 // New dominates Old. The predecessor nodes of the Old node dominate 633 // New node. 634 SmallSetVector<BasicBlock *, 8> UniquePredecessorsOfOld(pred_begin(New), 635 pred_end(New)); 636 DTUpdates.push_back({DominatorTree::Insert, New, Old}); 637 DTUpdates.reserve(DTUpdates.size() + 2 * UniquePredecessorsOfOld.size()); 638 for (BasicBlock *UniquePredecessorOfOld : UniquePredecessorsOfOld) { 639 DTUpdates.push_back({DominatorTree::Insert, UniquePredecessorOfOld, New}); 640 DTUpdates.push_back({DominatorTree::Delete, UniquePredecessorOfOld, Old}); 641 } 642 643 DTU->applyUpdates(DTUpdates); 644 645 // Move MemoryAccesses still tracked in Old, but part of New now. 646 // Update accesses in successor blocks accordingly. 647 if (MSSAU) { 648 MSSAU->applyUpdates(DTUpdates, DTU->getDomTree()); 649 if (VerifyMemorySSA) 650 MSSAU->getMemorySSA()->verifyMemorySSA(); 651 } 652 } 653 return New; 654 } 655 656 /// Update DominatorTree, LoopInfo, and LCCSA analysis information. 657 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, 658 ArrayRef<BasicBlock *> Preds, 659 DomTreeUpdater *DTU, DominatorTree *DT, 660 LoopInfo *LI, MemorySSAUpdater *MSSAU, 661 bool PreserveLCSSA, bool &HasLoopExit) { 662 // Update dominator tree if available. 663 if (DTU) { 664 // Recalculation of DomTree is needed when updating a forward DomTree and 665 // the Entry BB is replaced. 666 if (NewBB == &NewBB->getParent()->getEntryBlock() && DTU->hasDomTree()) { 667 // The entry block was removed and there is no external interface for 668 // the dominator tree to be notified of this change. In this corner-case 669 // we recalculate the entire tree. 670 DTU->recalculate(*NewBB->getParent()); 671 } else { 672 // Split block expects NewBB to have a non-empty set of predecessors. 673 SmallVector<DominatorTree::UpdateType, 8> Updates; 674 SmallSetVector<BasicBlock *, 8> UniquePreds(Preds.begin(), Preds.end()); 675 Updates.push_back({DominatorTree::Insert, NewBB, OldBB}); 676 Updates.reserve(Updates.size() + 2 * UniquePreds.size()); 677 for (auto *UniquePred : UniquePreds) { 678 Updates.push_back({DominatorTree::Insert, UniquePred, NewBB}); 679 Updates.push_back({DominatorTree::Delete, UniquePred, OldBB}); 680 } 681 DTU->applyUpdates(Updates); 682 } 683 } else if (DT) { 684 if (OldBB == DT->getRootNode()->getBlock()) { 685 assert(NewBB == &NewBB->getParent()->getEntryBlock()); 686 DT->setNewRoot(NewBB); 687 } else { 688 // Split block expects NewBB to have a non-empty set of predecessors. 689 DT->splitBlock(NewBB); 690 } 691 } 692 693 // Update MemoryPhis after split if MemorySSA is available 694 if (MSSAU) 695 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds); 696 697 // The rest of the logic is only relevant for updating the loop structures. 698 if (!LI) 699 return; 700 701 if (DTU && DTU->hasDomTree()) 702 DT = &DTU->getDomTree(); 703 assert(DT && "DT should be available to update LoopInfo!"); 704 Loop *L = LI->getLoopFor(OldBB); 705 706 // If we need to preserve loop analyses, collect some information about how 707 // this split will affect loops. 708 bool IsLoopEntry = !!L; 709 bool SplitMakesNewLoopHeader = false; 710 for (BasicBlock *Pred : Preds) { 711 // Preds that are not reachable from entry should not be used to identify if 712 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks 713 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader 714 // as true and make the NewBB the header of some loop. This breaks LI. 715 if (!DT->isReachableFromEntry(Pred)) 716 continue; 717 // If we need to preserve LCSSA, determine if any of the preds is a loop 718 // exit. 719 if (PreserveLCSSA) 720 if (Loop *PL = LI->getLoopFor(Pred)) 721 if (!PL->contains(OldBB)) 722 HasLoopExit = true; 723 724 // If we need to preserve LoopInfo, note whether any of the preds crosses 725 // an interesting loop boundary. 726 if (!L) 727 continue; 728 if (L->contains(Pred)) 729 IsLoopEntry = false; 730 else 731 SplitMakesNewLoopHeader = true; 732 } 733 734 // Unless we have a loop for OldBB, nothing else to do here. 735 if (!L) 736 return; 737 738 if (IsLoopEntry) { 739 // Add the new block to the nearest enclosing loop (and not an adjacent 740 // loop). To find this, examine each of the predecessors and determine which 741 // loops enclose them, and select the most-nested loop which contains the 742 // loop containing the block being split. 743 Loop *InnermostPredLoop = nullptr; 744 for (BasicBlock *Pred : Preds) { 745 if (Loop *PredLoop = LI->getLoopFor(Pred)) { 746 // Seek a loop which actually contains the block being split (to avoid 747 // adjacent loops). 748 while (PredLoop && !PredLoop->contains(OldBB)) 749 PredLoop = PredLoop->getParentLoop(); 750 751 // Select the most-nested of these loops which contains the block. 752 if (PredLoop && PredLoop->contains(OldBB) && 753 (!InnermostPredLoop || 754 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth())) 755 InnermostPredLoop = PredLoop; 756 } 757 } 758 759 if (InnermostPredLoop) 760 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI); 761 } else { 762 L->addBasicBlockToLoop(NewBB, *LI); 763 if (SplitMakesNewLoopHeader) 764 L->moveToHeader(NewBB); 765 } 766 } 767 768 /// Update the PHI nodes in OrigBB to include the values coming from NewBB. 769 /// This also updates AliasAnalysis, if available. 770 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, 771 ArrayRef<BasicBlock *> Preds, BranchInst *BI, 772 bool HasLoopExit) { 773 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB. 774 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end()); 775 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) { 776 PHINode *PN = cast<PHINode>(I++); 777 778 // Check to see if all of the values coming in are the same. If so, we 779 // don't need to create a new PHI node, unless it's needed for LCSSA. 780 Value *InVal = nullptr; 781 if (!HasLoopExit) { 782 InVal = PN->getIncomingValueForBlock(Preds[0]); 783 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 784 if (!PredSet.count(PN->getIncomingBlock(i))) 785 continue; 786 if (!InVal) 787 InVal = PN->getIncomingValue(i); 788 else if (InVal != PN->getIncomingValue(i)) { 789 InVal = nullptr; 790 break; 791 } 792 } 793 } 794 795 if (InVal) { 796 // If all incoming values for the new PHI would be the same, just don't 797 // make a new PHI. Instead, just remove the incoming values from the old 798 // PHI. 799 800 // NOTE! This loop walks backwards for a reason! First off, this minimizes 801 // the cost of removal if we end up removing a large number of values, and 802 // second off, this ensures that the indices for the incoming values 803 // aren't invalidated when we remove one. 804 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) 805 if (PredSet.count(PN->getIncomingBlock(i))) 806 PN->removeIncomingValue(i, false); 807 808 // Add an incoming value to the PHI node in the loop for the preheader 809 // edge. 810 PN->addIncoming(InVal, NewBB); 811 continue; 812 } 813 814 // If the values coming into the block are not the same, we need a new 815 // PHI. 816 // Create the new PHI node, insert it into NewBB at the end of the block 817 PHINode *NewPHI = 818 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI); 819 820 // NOTE! This loop walks backwards for a reason! First off, this minimizes 821 // the cost of removal if we end up removing a large number of values, and 822 // second off, this ensures that the indices for the incoming values aren't 823 // invalidated when we remove one. 824 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) { 825 BasicBlock *IncomingBB = PN->getIncomingBlock(i); 826 if (PredSet.count(IncomingBB)) { 827 Value *V = PN->removeIncomingValue(i, false); 828 NewPHI->addIncoming(V, IncomingBB); 829 } 830 } 831 832 PN->addIncoming(NewPHI, NewBB); 833 } 834 } 835 836 static void SplitLandingPadPredecessorsImpl( 837 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1, 838 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs, 839 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, 840 MemorySSAUpdater *MSSAU, bool PreserveLCSSA); 841 842 static BasicBlock * 843 SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds, 844 const char *Suffix, DomTreeUpdater *DTU, 845 DominatorTree *DT, LoopInfo *LI, 846 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) { 847 // Do not attempt to split that which cannot be split. 848 if (!BB->canSplitPredecessors()) 849 return nullptr; 850 851 // For the landingpads we need to act a bit differently. 852 // Delegate this work to the SplitLandingPadPredecessors. 853 if (BB->isLandingPad()) { 854 SmallVector<BasicBlock*, 2> NewBBs; 855 std::string NewName = std::string(Suffix) + ".split-lp"; 856 857 SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs, 858 DTU, DT, LI, MSSAU, PreserveLCSSA); 859 return NewBBs[0]; 860 } 861 862 // Create new basic block, insert right before the original block. 863 BasicBlock *NewBB = BasicBlock::Create( 864 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB); 865 866 // The new block unconditionally branches to the old block. 867 BranchInst *BI = BranchInst::Create(BB, NewBB); 868 869 Loop *L = nullptr; 870 BasicBlock *OldLatch = nullptr; 871 // Splitting the predecessors of a loop header creates a preheader block. 872 if (LI && LI->isLoopHeader(BB)) { 873 L = LI->getLoopFor(BB); 874 // Using the loop start line number prevents debuggers stepping into the 875 // loop body for this instruction. 876 BI->setDebugLoc(L->getStartLoc()); 877 878 // If BB is the header of the Loop, it is possible that the loop is 879 // modified, such that the current latch does not remain the latch of the 880 // loop. If that is the case, the loop metadata from the current latch needs 881 // to be applied to the new latch. 882 OldLatch = L->getLoopLatch(); 883 } else 884 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc()); 885 886 // Move the edges from Preds to point to NewBB instead of BB. 887 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 888 // This is slightly more strict than necessary; the minimum requirement 889 // is that there be no more than one indirectbr branching to BB. And 890 // all BlockAddress uses would need to be updated. 891 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 892 "Cannot split an edge from an IndirectBrInst"); 893 assert(!isa<CallBrInst>(Preds[i]->getTerminator()) && 894 "Cannot split an edge from a CallBrInst"); 895 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB); 896 } 897 898 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI 899 // node becomes an incoming value for BB's phi node. However, if the Preds 900 // list is empty, we need to insert dummy entries into the PHI nodes in BB to 901 // account for the newly created predecessor. 902 if (Preds.empty()) { 903 // Insert dummy values as the incoming value. 904 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) 905 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB); 906 } 907 908 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 909 bool HasLoopExit = false; 910 UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA, 911 HasLoopExit); 912 913 if (!Preds.empty()) { 914 // Update the PHI nodes in BB with the values coming from NewBB. 915 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit); 916 } 917 918 if (OldLatch) { 919 BasicBlock *NewLatch = L->getLoopLatch(); 920 if (NewLatch != OldLatch) { 921 MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop"); 922 NewLatch->getTerminator()->setMetadata("llvm.loop", MD); 923 OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr); 924 } 925 } 926 927 return NewBB; 928 } 929 930 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 931 ArrayRef<BasicBlock *> Preds, 932 const char *Suffix, DominatorTree *DT, 933 LoopInfo *LI, MemorySSAUpdater *MSSAU, 934 bool PreserveLCSSA) { 935 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI, 936 MSSAU, PreserveLCSSA); 937 } 938 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 939 ArrayRef<BasicBlock *> Preds, 940 const char *Suffix, 941 DomTreeUpdater *DTU, LoopInfo *LI, 942 MemorySSAUpdater *MSSAU, 943 bool PreserveLCSSA) { 944 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU, 945 /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA); 946 } 947 948 static void SplitLandingPadPredecessorsImpl( 949 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1, 950 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs, 951 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, 952 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) { 953 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!"); 954 955 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert 956 // it right before the original block. 957 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(), 958 OrigBB->getName() + Suffix1, 959 OrigBB->getParent(), OrigBB); 960 NewBBs.push_back(NewBB1); 961 962 // The new block unconditionally branches to the old block. 963 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1); 964 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 965 966 // Move the edges from Preds to point to NewBB1 instead of OrigBB. 967 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 968 // This is slightly more strict than necessary; the minimum requirement 969 // is that there be no more than one indirectbr branching to BB. And 970 // all BlockAddress uses would need to be updated. 971 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 972 "Cannot split an edge from an IndirectBrInst"); 973 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1); 974 } 975 976 bool HasLoopExit = false; 977 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU, 978 PreserveLCSSA, HasLoopExit); 979 980 // Update the PHI nodes in OrigBB with the values coming from NewBB1. 981 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit); 982 983 // Move the remaining edges from OrigBB to point to NewBB2. 984 SmallVector<BasicBlock*, 8> NewBB2Preds; 985 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB); 986 i != e; ) { 987 BasicBlock *Pred = *i++; 988 if (Pred == NewBB1) continue; 989 assert(!isa<IndirectBrInst>(Pred->getTerminator()) && 990 "Cannot split an edge from an IndirectBrInst"); 991 NewBB2Preds.push_back(Pred); 992 e = pred_end(OrigBB); 993 } 994 995 BasicBlock *NewBB2 = nullptr; 996 if (!NewBB2Preds.empty()) { 997 // Create another basic block for the rest of OrigBB's predecessors. 998 NewBB2 = BasicBlock::Create(OrigBB->getContext(), 999 OrigBB->getName() + Suffix2, 1000 OrigBB->getParent(), OrigBB); 1001 NewBBs.push_back(NewBB2); 1002 1003 // The new block unconditionally branches to the old block. 1004 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2); 1005 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 1006 1007 // Move the remaining edges from OrigBB to point to NewBB2. 1008 for (BasicBlock *NewBB2Pred : NewBB2Preds) 1009 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2); 1010 1011 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 1012 HasLoopExit = false; 1013 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU, 1014 PreserveLCSSA, HasLoopExit); 1015 1016 // Update the PHI nodes in OrigBB with the values coming from NewBB2. 1017 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit); 1018 } 1019 1020 LandingPadInst *LPad = OrigBB->getLandingPadInst(); 1021 Instruction *Clone1 = LPad->clone(); 1022 Clone1->setName(Twine("lpad") + Suffix1); 1023 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1); 1024 1025 if (NewBB2) { 1026 Instruction *Clone2 = LPad->clone(); 1027 Clone2->setName(Twine("lpad") + Suffix2); 1028 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2); 1029 1030 // Create a PHI node for the two cloned landingpad instructions only 1031 // if the original landingpad instruction has some uses. 1032 if (!LPad->use_empty()) { 1033 assert(!LPad->getType()->isTokenTy() && 1034 "Split cannot be applied if LPad is token type. Otherwise an " 1035 "invalid PHINode of token type would be created."); 1036 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad); 1037 PN->addIncoming(Clone1, NewBB1); 1038 PN->addIncoming(Clone2, NewBB2); 1039 LPad->replaceAllUsesWith(PN); 1040 } 1041 LPad->eraseFromParent(); 1042 } else { 1043 // There is no second clone. Just replace the landing pad with the first 1044 // clone. 1045 LPad->replaceAllUsesWith(Clone1); 1046 LPad->eraseFromParent(); 1047 } 1048 } 1049 1050 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB, 1051 ArrayRef<BasicBlock *> Preds, 1052 const char *Suffix1, const char *Suffix2, 1053 SmallVectorImpl<BasicBlock *> &NewBBs, 1054 DominatorTree *DT, LoopInfo *LI, 1055 MemorySSAUpdater *MSSAU, 1056 bool PreserveLCSSA) { 1057 return SplitLandingPadPredecessorsImpl( 1058 OrigBB, Preds, Suffix1, Suffix2, NewBBs, 1059 /*DTU=*/nullptr, DT, LI, MSSAU, PreserveLCSSA); 1060 } 1061 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB, 1062 ArrayRef<BasicBlock *> Preds, 1063 const char *Suffix1, const char *Suffix2, 1064 SmallVectorImpl<BasicBlock *> &NewBBs, 1065 DomTreeUpdater *DTU, LoopInfo *LI, 1066 MemorySSAUpdater *MSSAU, 1067 bool PreserveLCSSA) { 1068 return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2, 1069 NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU, 1070 PreserveLCSSA); 1071 } 1072 1073 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, 1074 BasicBlock *Pred, 1075 DomTreeUpdater *DTU) { 1076 Instruction *UncondBranch = Pred->getTerminator(); 1077 // Clone the return and add it to the end of the predecessor. 1078 Instruction *NewRet = RI->clone(); 1079 Pred->getInstList().push_back(NewRet); 1080 1081 // If the return instruction returns a value, and if the value was a 1082 // PHI node in "BB", propagate the right value into the return. 1083 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end(); 1084 i != e; ++i) { 1085 Value *V = *i; 1086 Instruction *NewBC = nullptr; 1087 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) { 1088 // Return value might be bitcasted. Clone and insert it before the 1089 // return instruction. 1090 V = BCI->getOperand(0); 1091 NewBC = BCI->clone(); 1092 Pred->getInstList().insert(NewRet->getIterator(), NewBC); 1093 *i = NewBC; 1094 } 1095 1096 Instruction *NewEV = nullptr; 1097 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) { 1098 V = EVI->getOperand(0); 1099 NewEV = EVI->clone(); 1100 if (NewBC) { 1101 NewBC->setOperand(0, NewEV); 1102 Pred->getInstList().insert(NewBC->getIterator(), NewEV); 1103 } else { 1104 Pred->getInstList().insert(NewRet->getIterator(), NewEV); 1105 *i = NewEV; 1106 } 1107 } 1108 1109 if (PHINode *PN = dyn_cast<PHINode>(V)) { 1110 if (PN->getParent() == BB) { 1111 if (NewEV) { 1112 NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred)); 1113 } else if (NewBC) 1114 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred)); 1115 else 1116 *i = PN->getIncomingValueForBlock(Pred); 1117 } 1118 } 1119 } 1120 1121 // Update any PHI nodes in the returning block to realize that we no 1122 // longer branch to them. 1123 BB->removePredecessor(Pred); 1124 UncondBranch->eraseFromParent(); 1125 1126 if (DTU) 1127 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}}); 1128 1129 return cast<ReturnInst>(NewRet); 1130 } 1131 1132 static Instruction * 1133 SplitBlockAndInsertIfThenImpl(Value *Cond, Instruction *SplitBefore, 1134 bool Unreachable, MDNode *BranchWeights, 1135 DomTreeUpdater *DTU, DominatorTree *DT, 1136 LoopInfo *LI, BasicBlock *ThenBlock) { 1137 SmallVector<DominatorTree::UpdateType, 8> Updates; 1138 BasicBlock *Head = SplitBefore->getParent(); 1139 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 1140 if (DTU) { 1141 SmallSetVector<BasicBlock *, 8> UniqueSuccessorsOfHead(succ_begin(Tail), 1142 succ_end(Tail)); 1143 Updates.push_back({DominatorTree::Insert, Head, Tail}); 1144 Updates.reserve(Updates.size() + 2 * UniqueSuccessorsOfHead.size()); 1145 for (BasicBlock *UniqueSuccessorOfHead : UniqueSuccessorsOfHead) { 1146 Updates.push_back({DominatorTree::Insert, Tail, UniqueSuccessorOfHead}); 1147 Updates.push_back({DominatorTree::Delete, Head, UniqueSuccessorOfHead}); 1148 } 1149 } 1150 Instruction *HeadOldTerm = Head->getTerminator(); 1151 LLVMContext &C = Head->getContext(); 1152 Instruction *CheckTerm; 1153 bool CreateThenBlock = (ThenBlock == nullptr); 1154 if (CreateThenBlock) { 1155 ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1156 if (Unreachable) 1157 CheckTerm = new UnreachableInst(C, ThenBlock); 1158 else { 1159 CheckTerm = BranchInst::Create(Tail, ThenBlock); 1160 if (DTU) 1161 Updates.push_back({DominatorTree::Insert, ThenBlock, Tail}); 1162 } 1163 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc()); 1164 } else 1165 CheckTerm = ThenBlock->getTerminator(); 1166 BranchInst *HeadNewTerm = 1167 BranchInst::Create(/*ifTrue*/ ThenBlock, /*ifFalse*/ Tail, Cond); 1168 if (DTU) 1169 Updates.push_back({DominatorTree::Insert, Head, ThenBlock}); 1170 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 1171 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 1172 1173 if (DTU) 1174 DTU->applyUpdates(Updates); 1175 else if (DT) { 1176 if (DomTreeNode *OldNode = DT->getNode(Head)) { 1177 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 1178 1179 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head); 1180 for (DomTreeNode *Child : Children) 1181 DT->changeImmediateDominator(Child, NewNode); 1182 1183 // Head dominates ThenBlock. 1184 if (CreateThenBlock) 1185 DT->addNewBlock(ThenBlock, Head); 1186 else 1187 DT->changeImmediateDominator(ThenBlock, Head); 1188 } 1189 } 1190 1191 if (LI) { 1192 if (Loop *L = LI->getLoopFor(Head)) { 1193 L->addBasicBlockToLoop(ThenBlock, *LI); 1194 L->addBasicBlockToLoop(Tail, *LI); 1195 } 1196 } 1197 1198 return CheckTerm; 1199 } 1200 1201 Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond, 1202 Instruction *SplitBefore, 1203 bool Unreachable, 1204 MDNode *BranchWeights, 1205 DominatorTree *DT, LoopInfo *LI, 1206 BasicBlock *ThenBlock) { 1207 return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable, 1208 BranchWeights, 1209 /*DTU=*/nullptr, DT, LI, ThenBlock); 1210 } 1211 Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond, 1212 Instruction *SplitBefore, 1213 bool Unreachable, 1214 MDNode *BranchWeights, 1215 DomTreeUpdater *DTU, LoopInfo *LI, 1216 BasicBlock *ThenBlock) { 1217 return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable, 1218 BranchWeights, DTU, /*DT=*/nullptr, LI, 1219 ThenBlock); 1220 } 1221 1222 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, 1223 Instruction **ThenTerm, 1224 Instruction **ElseTerm, 1225 MDNode *BranchWeights) { 1226 BasicBlock *Head = SplitBefore->getParent(); 1227 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 1228 Instruction *HeadOldTerm = Head->getTerminator(); 1229 LLVMContext &C = Head->getContext(); 1230 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1231 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1232 *ThenTerm = BranchInst::Create(Tail, ThenBlock); 1233 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 1234 *ElseTerm = BranchInst::Create(Tail, ElseBlock); 1235 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 1236 BranchInst *HeadNewTerm = 1237 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond); 1238 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 1239 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 1240 } 1241 1242 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, 1243 BasicBlock *&IfFalse) { 1244 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin()); 1245 BasicBlock *Pred1 = nullptr; 1246 BasicBlock *Pred2 = nullptr; 1247 1248 if (SomePHI) { 1249 if (SomePHI->getNumIncomingValues() != 2) 1250 return nullptr; 1251 Pred1 = SomePHI->getIncomingBlock(0); 1252 Pred2 = SomePHI->getIncomingBlock(1); 1253 } else { 1254 pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 1255 if (PI == PE) // No predecessor 1256 return nullptr; 1257 Pred1 = *PI++; 1258 if (PI == PE) // Only one predecessor 1259 return nullptr; 1260 Pred2 = *PI++; 1261 if (PI != PE) // More than two predecessors 1262 return nullptr; 1263 } 1264 1265 // We can only handle branches. Other control flow will be lowered to 1266 // branches if possible anyway. 1267 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator()); 1268 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator()); 1269 if (!Pred1Br || !Pred2Br) 1270 return nullptr; 1271 1272 // Eliminate code duplication by ensuring that Pred1Br is conditional if 1273 // either are. 1274 if (Pred2Br->isConditional()) { 1275 // If both branches are conditional, we don't have an "if statement". In 1276 // reality, we could transform this case, but since the condition will be 1277 // required anyway, we stand no chance of eliminating it, so the xform is 1278 // probably not profitable. 1279 if (Pred1Br->isConditional()) 1280 return nullptr; 1281 1282 std::swap(Pred1, Pred2); 1283 std::swap(Pred1Br, Pred2Br); 1284 } 1285 1286 if (Pred1Br->isConditional()) { 1287 // The only thing we have to watch out for here is to make sure that Pred2 1288 // doesn't have incoming edges from other blocks. If it does, the condition 1289 // doesn't dominate BB. 1290 if (!Pred2->getSinglePredecessor()) 1291 return nullptr; 1292 1293 // If we found a conditional branch predecessor, make sure that it branches 1294 // to BB and Pred2Br. If it doesn't, this isn't an "if statement". 1295 if (Pred1Br->getSuccessor(0) == BB && 1296 Pred1Br->getSuccessor(1) == Pred2) { 1297 IfTrue = Pred1; 1298 IfFalse = Pred2; 1299 } else if (Pred1Br->getSuccessor(0) == Pred2 && 1300 Pred1Br->getSuccessor(1) == BB) { 1301 IfTrue = Pred2; 1302 IfFalse = Pred1; 1303 } else { 1304 // We know that one arm of the conditional goes to BB, so the other must 1305 // go somewhere unrelated, and this must not be an "if statement". 1306 return nullptr; 1307 } 1308 1309 return Pred1Br->getCondition(); 1310 } 1311 1312 // Ok, if we got here, both predecessors end with an unconditional branch to 1313 // BB. Don't panic! If both blocks only have a single (identical) 1314 // predecessor, and THAT is a conditional branch, then we're all ok! 1315 BasicBlock *CommonPred = Pred1->getSinglePredecessor(); 1316 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor()) 1317 return nullptr; 1318 1319 // Otherwise, if this is a conditional branch, then we can use it! 1320 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator()); 1321 if (!BI) return nullptr; 1322 1323 assert(BI->isConditional() && "Two successors but not conditional?"); 1324 if (BI->getSuccessor(0) == Pred1) { 1325 IfTrue = Pred1; 1326 IfFalse = Pred2; 1327 } else { 1328 IfTrue = Pred2; 1329 IfFalse = Pred1; 1330 } 1331 return BI->getCondition(); 1332 } 1333 1334 // After creating a control flow hub, the operands of PHINodes in an outgoing 1335 // block Out no longer match the predecessors of that block. Predecessors of Out 1336 // that are incoming blocks to the hub are now replaced by just one edge from 1337 // the hub. To match this new control flow, the corresponding values from each 1338 // PHINode must now be moved a new PHINode in the first guard block of the hub. 1339 // 1340 // This operation cannot be performed with SSAUpdater, because it involves one 1341 // new use: If the block Out is in the list of Incoming blocks, then the newly 1342 // created PHI in the Hub will use itself along that edge from Out to Hub. 1343 static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock, 1344 const SetVector<BasicBlock *> &Incoming, 1345 BasicBlock *FirstGuardBlock) { 1346 auto I = Out->begin(); 1347 while (I != Out->end() && isa<PHINode>(I)) { 1348 auto Phi = cast<PHINode>(I); 1349 auto NewPhi = 1350 PHINode::Create(Phi->getType(), Incoming.size(), 1351 Phi->getName() + ".moved", &FirstGuardBlock->back()); 1352 for (auto In : Incoming) { 1353 Value *V = UndefValue::get(Phi->getType()); 1354 if (In == Out) { 1355 V = NewPhi; 1356 } else if (Phi->getBasicBlockIndex(In) != -1) { 1357 V = Phi->removeIncomingValue(In, false); 1358 } 1359 NewPhi->addIncoming(V, In); 1360 } 1361 assert(NewPhi->getNumIncomingValues() == Incoming.size()); 1362 if (Phi->getNumOperands() == 0) { 1363 Phi->replaceAllUsesWith(NewPhi); 1364 I = Phi->eraseFromParent(); 1365 continue; 1366 } 1367 Phi->addIncoming(NewPhi, GuardBlock); 1368 ++I; 1369 } 1370 } 1371 1372 using BBPredicates = DenseMap<BasicBlock *, PHINode *>; 1373 using BBSetVector = SetVector<BasicBlock *>; 1374 1375 // Redirects the terminator of the incoming block to the first guard 1376 // block in the hub. The condition of the original terminator (if it 1377 // was conditional) and its original successors are returned as a 1378 // tuple <condition, succ0, succ1>. The function additionally filters 1379 // out successors that are not in the set of outgoing blocks. 1380 // 1381 // - condition is non-null iff the branch is conditional. 1382 // - Succ1 is non-null iff the sole/taken target is an outgoing block. 1383 // - Succ2 is non-null iff condition is non-null and the fallthrough 1384 // target is an outgoing block. 1385 static std::tuple<Value *, BasicBlock *, BasicBlock *> 1386 redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock, 1387 const BBSetVector &Outgoing) { 1388 auto Branch = cast<BranchInst>(BB->getTerminator()); 1389 auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr; 1390 1391 BasicBlock *Succ0 = Branch->getSuccessor(0); 1392 BasicBlock *Succ1 = nullptr; 1393 Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr; 1394 1395 if (Branch->isUnconditional()) { 1396 Branch->setSuccessor(0, FirstGuardBlock); 1397 assert(Succ0); 1398 } else { 1399 Succ1 = Branch->getSuccessor(1); 1400 Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr; 1401 assert(Succ0 || Succ1); 1402 if (Succ0 && !Succ1) { 1403 Branch->setSuccessor(0, FirstGuardBlock); 1404 } else if (Succ1 && !Succ0) { 1405 Branch->setSuccessor(1, FirstGuardBlock); 1406 } else { 1407 Branch->eraseFromParent(); 1408 BranchInst::Create(FirstGuardBlock, BB); 1409 } 1410 } 1411 1412 assert(Succ0 || Succ1); 1413 return std::make_tuple(Condition, Succ0, Succ1); 1414 } 1415 1416 // Capture the existing control flow as guard predicates, and redirect 1417 // control flow from every incoming block to the first guard block in 1418 // the hub. 1419 // 1420 // There is one guard predicate for each outgoing block OutBB. The 1421 // predicate is a PHINode with one input for each InBB which 1422 // represents whether the hub should transfer control flow to OutBB if 1423 // it arrived from InBB. These predicates are NOT ORTHOGONAL. The Hub 1424 // evaluates them in the same order as the Outgoing set-vector, and 1425 // control branches to the first outgoing block whose predicate 1426 // evaluates to true. 1427 static void convertToGuardPredicates( 1428 BasicBlock *FirstGuardBlock, BBPredicates &GuardPredicates, 1429 SmallVectorImpl<WeakVH> &DeletionCandidates, const BBSetVector &Incoming, 1430 const BBSetVector &Outgoing) { 1431 auto &Context = Incoming.front()->getContext(); 1432 auto BoolTrue = ConstantInt::getTrue(Context); 1433 auto BoolFalse = ConstantInt::getFalse(Context); 1434 1435 // The predicate for the last outgoing is trivially true, and so we 1436 // process only the first N-1 successors. 1437 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) { 1438 auto Out = Outgoing[i]; 1439 LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n"); 1440 auto Phi = 1441 PHINode::Create(Type::getInt1Ty(Context), Incoming.size(), 1442 StringRef("Guard.") + Out->getName(), FirstGuardBlock); 1443 GuardPredicates[Out] = Phi; 1444 } 1445 1446 for (auto In : Incoming) { 1447 Value *Condition; 1448 BasicBlock *Succ0; 1449 BasicBlock *Succ1; 1450 std::tie(Condition, Succ0, Succ1) = 1451 redirectToHub(In, FirstGuardBlock, Outgoing); 1452 1453 // Optimization: Consider an incoming block A with both successors 1454 // Succ0 and Succ1 in the set of outgoing blocks. The predicates 1455 // for Succ0 and Succ1 complement each other. If Succ0 is visited 1456 // first in the loop below, control will branch to Succ0 using the 1457 // corresponding predicate. But if that branch is not taken, then 1458 // control must reach Succ1, which means that the predicate for 1459 // Succ1 is always true. 1460 bool OneSuccessorDone = false; 1461 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) { 1462 auto Out = Outgoing[i]; 1463 auto Phi = GuardPredicates[Out]; 1464 if (Out != Succ0 && Out != Succ1) { 1465 Phi->addIncoming(BoolFalse, In); 1466 continue; 1467 } 1468 // Optimization: When only one successor is an outgoing block, 1469 // the predicate is always true. 1470 if (!Succ0 || !Succ1 || OneSuccessorDone) { 1471 Phi->addIncoming(BoolTrue, In); 1472 continue; 1473 } 1474 assert(Succ0 && Succ1); 1475 OneSuccessorDone = true; 1476 if (Out == Succ0) { 1477 Phi->addIncoming(Condition, In); 1478 continue; 1479 } 1480 auto Inverted = invertCondition(Condition); 1481 DeletionCandidates.push_back(Condition); 1482 Phi->addIncoming(Inverted, In); 1483 } 1484 } 1485 } 1486 1487 // For each outgoing block OutBB, create a guard block in the Hub. The 1488 // first guard block was already created outside, and available as the 1489 // first element in the vector of guard blocks. 1490 // 1491 // Each guard block terminates in a conditional branch that transfers 1492 // control to the corresponding outgoing block or the next guard 1493 // block. The last guard block has two outgoing blocks as successors 1494 // since the condition for the final outgoing block is trivially 1495 // true. So we create one less block (including the first guard block) 1496 // than the number of outgoing blocks. 1497 static void createGuardBlocks(SmallVectorImpl<BasicBlock *> &GuardBlocks, 1498 Function *F, const BBSetVector &Outgoing, 1499 BBPredicates &GuardPredicates, StringRef Prefix) { 1500 for (int i = 0, e = Outgoing.size() - 2; i != e; ++i) { 1501 GuardBlocks.push_back( 1502 BasicBlock::Create(F->getContext(), Prefix + ".guard", F)); 1503 } 1504 assert(GuardBlocks.size() == GuardPredicates.size()); 1505 1506 // To help keep the loop simple, temporarily append the last 1507 // outgoing block to the list of guard blocks. 1508 GuardBlocks.push_back(Outgoing.back()); 1509 1510 for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) { 1511 auto Out = Outgoing[i]; 1512 assert(GuardPredicates.count(Out)); 1513 BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out], 1514 GuardBlocks[i]); 1515 } 1516 1517 // Remove the last block from the guard list. 1518 GuardBlocks.pop_back(); 1519 } 1520 1521 BasicBlock *llvm::CreateControlFlowHub( 1522 DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks, 1523 const BBSetVector &Incoming, const BBSetVector &Outgoing, 1524 const StringRef Prefix) { 1525 auto F = Incoming.front()->getParent(); 1526 auto FirstGuardBlock = 1527 BasicBlock::Create(F->getContext(), Prefix + ".guard", F); 1528 1529 SmallVector<DominatorTree::UpdateType, 16> Updates; 1530 if (DTU) { 1531 for (auto In : Incoming) { 1532 Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock}); 1533 for (auto Succ : successors(In)) { 1534 if (Outgoing.count(Succ)) 1535 Updates.push_back({DominatorTree::Delete, In, Succ}); 1536 } 1537 } 1538 } 1539 1540 BBPredicates GuardPredicates; 1541 SmallVector<WeakVH, 8> DeletionCandidates; 1542 convertToGuardPredicates(FirstGuardBlock, GuardPredicates, DeletionCandidates, 1543 Incoming, Outgoing); 1544 1545 GuardBlocks.push_back(FirstGuardBlock); 1546 createGuardBlocks(GuardBlocks, F, Outgoing, GuardPredicates, Prefix); 1547 1548 // Update the PHINodes in each outgoing block to match the new control flow. 1549 for (int i = 0, e = GuardBlocks.size(); i != e; ++i) { 1550 reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock); 1551 } 1552 reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock); 1553 1554 if (DTU) { 1555 int NumGuards = GuardBlocks.size(); 1556 assert((int)Outgoing.size() == NumGuards + 1); 1557 for (int i = 0; i != NumGuards - 1; ++i) { 1558 Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]}); 1559 Updates.push_back( 1560 {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]}); 1561 } 1562 Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1], 1563 Outgoing[NumGuards - 1]}); 1564 Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1], 1565 Outgoing[NumGuards]}); 1566 DTU->applyUpdates(Updates); 1567 } 1568 1569 for (auto I : DeletionCandidates) { 1570 if (I->use_empty()) 1571 if (auto Inst = dyn_cast_or_null<Instruction>(I)) 1572 Inst->eraseFromParent(); 1573 } 1574 1575 return FirstGuardBlock; 1576 } 1577