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