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 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 return LatchTerm->getSuccessor(SuccNum); 507 508 // If the edge isn't critical, then BB has a single successor or Succ has a 509 // single pred. Split the block. 510 if (BasicBlock *SP = Succ->getSinglePredecessor()) { 511 // If the successor only has a single pred, split the top of the successor 512 // block. 513 assert(SP == BB && "CFG broken"); 514 SP = nullptr; 515 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, "", /*Before=*/true); 516 } 517 518 // Otherwise, if BB has a single successor, split it at the bottom of the 519 // block. 520 assert(BB->getTerminator()->getNumSuccessors() == 1 && 521 "Should have a single succ!"); 522 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU); 523 } 524 525 unsigned 526 llvm::SplitAllCriticalEdges(Function &F, 527 const CriticalEdgeSplittingOptions &Options) { 528 unsigned NumBroken = 0; 529 for (BasicBlock &BB : F) { 530 Instruction *TI = BB.getTerminator(); 531 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI) && 532 !isa<CallBrInst>(TI)) 533 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 534 if (SplitCriticalEdge(TI, i, Options)) 535 ++NumBroken; 536 } 537 return NumBroken; 538 } 539 540 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, 541 DominatorTree *DT, LoopInfo *LI, 542 MemorySSAUpdater *MSSAU, const Twine &BBName, 543 bool Before) { 544 if (Before) 545 return splitBlockBefore(Old, SplitPt, DT, LI, MSSAU, BBName); 546 BasicBlock::iterator SplitIt = SplitPt->getIterator(); 547 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) 548 ++SplitIt; 549 std::string Name = BBName.str(); 550 BasicBlock *New = Old->splitBasicBlock( 551 SplitIt, Name.empty() ? Old->getName() + ".split" : Name); 552 553 // The new block lives in whichever loop the old one did. This preserves 554 // LCSSA as well, because we force the split point to be after any PHI nodes. 555 if (LI) 556 if (Loop *L = LI->getLoopFor(Old)) 557 L->addBasicBlockToLoop(New, *LI); 558 559 if (DT) 560 // Old dominates New. New node dominates all other nodes dominated by Old. 561 if (DomTreeNode *OldNode = DT->getNode(Old)) { 562 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 563 564 DomTreeNode *NewNode = DT->addNewBlock(New, Old); 565 for (DomTreeNode *I : Children) 566 DT->changeImmediateDominator(I, NewNode); 567 } 568 569 // Move MemoryAccesses still tracked in Old, but part of New now. 570 // Update accesses in successor blocks accordingly. 571 if (MSSAU) 572 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin())); 573 574 return New; 575 } 576 577 BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, Instruction *SplitPt, 578 DominatorTree *DT, LoopInfo *LI, 579 MemorySSAUpdater *MSSAU, 580 const Twine &BBName) { 581 582 BasicBlock::iterator SplitIt = SplitPt->getIterator(); 583 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) 584 ++SplitIt; 585 std::string Name = BBName.str(); 586 BasicBlock *New = Old->splitBasicBlock( 587 SplitIt, Name.empty() ? Old->getName() + ".split" : Name, 588 /* Before=*/true); 589 590 // The new block lives in whichever loop the old one did. This preserves 591 // LCSSA as well, because we force the split point to be after any PHI nodes. 592 if (LI) 593 if (Loop *L = LI->getLoopFor(Old)) 594 L->addBasicBlockToLoop(New, *LI); 595 596 if (DT) { 597 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 598 SmallVector<DominatorTree::UpdateType, 8> DTUpdates; 599 // New dominates Old. The predecessor nodes of the Old node dominate 600 // New node. 601 DTUpdates.push_back({DominatorTree::Insert, New, Old}); 602 for (BasicBlock *Pred : predecessors(New)) 603 if (DT->getNode(Pred)) { 604 DTUpdates.push_back({DominatorTree::Insert, Pred, New}); 605 DTUpdates.push_back({DominatorTree::Delete, Pred, Old}); 606 } 607 608 DTU.applyUpdates(DTUpdates); 609 DTU.flush(); 610 611 // Move MemoryAccesses still tracked in Old, but part of New now. 612 // Update accesses in successor blocks accordingly. 613 if (MSSAU) { 614 MSSAU->applyUpdates(DTUpdates, *DT); 615 if (VerifyMemorySSA) 616 MSSAU->getMemorySSA()->verifyMemorySSA(); 617 } 618 } 619 return New; 620 } 621 622 /// Update DominatorTree, LoopInfo, and LCCSA analysis information. 623 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, 624 ArrayRef<BasicBlock *> Preds, 625 DominatorTree *DT, LoopInfo *LI, 626 MemorySSAUpdater *MSSAU, 627 bool PreserveLCSSA, bool &HasLoopExit) { 628 // Update dominator tree if available. 629 if (DT) { 630 if (OldBB == DT->getRootNode()->getBlock()) { 631 assert(NewBB == &NewBB->getParent()->getEntryBlock()); 632 DT->setNewRoot(NewBB); 633 } else { 634 // Split block expects NewBB to have a non-empty set of predecessors. 635 DT->splitBlock(NewBB); 636 } 637 } 638 639 // Update MemoryPhis after split if MemorySSA is available 640 if (MSSAU) 641 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds); 642 643 // The rest of the logic is only relevant for updating the loop structures. 644 if (!LI) 645 return; 646 647 assert(DT && "DT should be available to update LoopInfo!"); 648 Loop *L = LI->getLoopFor(OldBB); 649 650 // If we need to preserve loop analyses, collect some information about how 651 // this split will affect loops. 652 bool IsLoopEntry = !!L; 653 bool SplitMakesNewLoopHeader = false; 654 for (BasicBlock *Pred : Preds) { 655 // Preds that are not reachable from entry should not be used to identify if 656 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks 657 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader 658 // as true and make the NewBB the header of some loop. This breaks LI. 659 if (!DT->isReachableFromEntry(Pred)) 660 continue; 661 // If we need to preserve LCSSA, determine if any of the preds is a loop 662 // exit. 663 if (PreserveLCSSA) 664 if (Loop *PL = LI->getLoopFor(Pred)) 665 if (!PL->contains(OldBB)) 666 HasLoopExit = true; 667 668 // If we need to preserve LoopInfo, note whether any of the preds crosses 669 // an interesting loop boundary. 670 if (!L) 671 continue; 672 if (L->contains(Pred)) 673 IsLoopEntry = false; 674 else 675 SplitMakesNewLoopHeader = true; 676 } 677 678 // Unless we have a loop for OldBB, nothing else to do here. 679 if (!L) 680 return; 681 682 if (IsLoopEntry) { 683 // Add the new block to the nearest enclosing loop (and not an adjacent 684 // loop). To find this, examine each of the predecessors and determine which 685 // loops enclose them, and select the most-nested loop which contains the 686 // loop containing the block being split. 687 Loop *InnermostPredLoop = nullptr; 688 for (BasicBlock *Pred : Preds) { 689 if (Loop *PredLoop = LI->getLoopFor(Pred)) { 690 // Seek a loop which actually contains the block being split (to avoid 691 // adjacent loops). 692 while (PredLoop && !PredLoop->contains(OldBB)) 693 PredLoop = PredLoop->getParentLoop(); 694 695 // Select the most-nested of these loops which contains the block. 696 if (PredLoop && PredLoop->contains(OldBB) && 697 (!InnermostPredLoop || 698 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth())) 699 InnermostPredLoop = PredLoop; 700 } 701 } 702 703 if (InnermostPredLoop) 704 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI); 705 } else { 706 L->addBasicBlockToLoop(NewBB, *LI); 707 if (SplitMakesNewLoopHeader) 708 L->moveToHeader(NewBB); 709 } 710 } 711 712 /// Update the PHI nodes in OrigBB to include the values coming from NewBB. 713 /// This also updates AliasAnalysis, if available. 714 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, 715 ArrayRef<BasicBlock *> Preds, BranchInst *BI, 716 bool HasLoopExit) { 717 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB. 718 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end()); 719 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) { 720 PHINode *PN = cast<PHINode>(I++); 721 722 // Check to see if all of the values coming in are the same. If so, we 723 // don't need to create a new PHI node, unless it's needed for LCSSA. 724 Value *InVal = nullptr; 725 if (!HasLoopExit) { 726 InVal = PN->getIncomingValueForBlock(Preds[0]); 727 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 728 if (!PredSet.count(PN->getIncomingBlock(i))) 729 continue; 730 if (!InVal) 731 InVal = PN->getIncomingValue(i); 732 else if (InVal != PN->getIncomingValue(i)) { 733 InVal = nullptr; 734 break; 735 } 736 } 737 } 738 739 if (InVal) { 740 // If all incoming values for the new PHI would be the same, just don't 741 // make a new PHI. Instead, just remove the incoming values from the old 742 // PHI. 743 744 // NOTE! This loop walks backwards for a reason! First off, this minimizes 745 // the cost of removal if we end up removing a large number of values, and 746 // second off, this ensures that the indices for the incoming values 747 // aren't invalidated when we remove one. 748 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) 749 if (PredSet.count(PN->getIncomingBlock(i))) 750 PN->removeIncomingValue(i, false); 751 752 // Add an incoming value to the PHI node in the loop for the preheader 753 // edge. 754 PN->addIncoming(InVal, NewBB); 755 continue; 756 } 757 758 // If the values coming into the block are not the same, we need a new 759 // PHI. 760 // Create the new PHI node, insert it into NewBB at the end of the block 761 PHINode *NewPHI = 762 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI); 763 764 // NOTE! This loop walks backwards for a reason! First off, this minimizes 765 // the cost of removal if we end up removing a large number of values, and 766 // second off, this ensures that the indices for the incoming values aren't 767 // invalidated when we remove one. 768 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) { 769 BasicBlock *IncomingBB = PN->getIncomingBlock(i); 770 if (PredSet.count(IncomingBB)) { 771 Value *V = PN->removeIncomingValue(i, false); 772 NewPHI->addIncoming(V, IncomingBB); 773 } 774 } 775 776 PN->addIncoming(NewPHI, NewBB); 777 } 778 } 779 780 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 781 ArrayRef<BasicBlock *> Preds, 782 const char *Suffix, DominatorTree *DT, 783 LoopInfo *LI, MemorySSAUpdater *MSSAU, 784 bool PreserveLCSSA) { 785 // Do not attempt to split that which cannot be split. 786 if (!BB->canSplitPredecessors()) 787 return nullptr; 788 789 // For the landingpads we need to act a bit differently. 790 // Delegate this work to the SplitLandingPadPredecessors. 791 if (BB->isLandingPad()) { 792 SmallVector<BasicBlock*, 2> NewBBs; 793 std::string NewName = std::string(Suffix) + ".split-lp"; 794 795 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT, 796 LI, MSSAU, PreserveLCSSA); 797 return NewBBs[0]; 798 } 799 800 // Create new basic block, insert right before the original block. 801 BasicBlock *NewBB = BasicBlock::Create( 802 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB); 803 804 // The new block unconditionally branches to the old block. 805 BranchInst *BI = BranchInst::Create(BB, NewBB); 806 807 Loop *L = nullptr; 808 BasicBlock *OldLatch = nullptr; 809 // Splitting the predecessors of a loop header creates a preheader block. 810 if (LI && LI->isLoopHeader(BB)) { 811 L = LI->getLoopFor(BB); 812 // Using the loop start line number prevents debuggers stepping into the 813 // loop body for this instruction. 814 BI->setDebugLoc(L->getStartLoc()); 815 816 // If BB is the header of the Loop, it is possible that the loop is 817 // modified, such that the current latch does not remain the latch of the 818 // loop. If that is the case, the loop metadata from the current latch needs 819 // to be applied to the new latch. 820 OldLatch = L->getLoopLatch(); 821 } else 822 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc()); 823 824 // Move the edges from Preds to point to NewBB instead of BB. 825 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 826 // This is slightly more strict than necessary; the minimum requirement 827 // is that there be no more than one indirectbr branching to BB. And 828 // all BlockAddress uses would need to be updated. 829 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 830 "Cannot split an edge from an IndirectBrInst"); 831 assert(!isa<CallBrInst>(Preds[i]->getTerminator()) && 832 "Cannot split an edge from a CallBrInst"); 833 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB); 834 } 835 836 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI 837 // node becomes an incoming value for BB's phi node. However, if the Preds 838 // list is empty, we need to insert dummy entries into the PHI nodes in BB to 839 // account for the newly created predecessor. 840 if (Preds.empty()) { 841 // Insert dummy values as the incoming value. 842 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) 843 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB); 844 } 845 846 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 847 bool HasLoopExit = false; 848 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, MSSAU, PreserveLCSSA, 849 HasLoopExit); 850 851 if (!Preds.empty()) { 852 // Update the PHI nodes in BB with the values coming from NewBB. 853 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit); 854 } 855 856 if (OldLatch) { 857 BasicBlock *NewLatch = L->getLoopLatch(); 858 if (NewLatch != OldLatch) { 859 MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop"); 860 NewLatch->getTerminator()->setMetadata("llvm.loop", MD); 861 OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr); 862 } 863 } 864 865 return NewBB; 866 } 867 868 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB, 869 ArrayRef<BasicBlock *> Preds, 870 const char *Suffix1, const char *Suffix2, 871 SmallVectorImpl<BasicBlock *> &NewBBs, 872 DominatorTree *DT, LoopInfo *LI, 873 MemorySSAUpdater *MSSAU, 874 bool PreserveLCSSA) { 875 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!"); 876 877 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert 878 // it right before the original block. 879 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(), 880 OrigBB->getName() + Suffix1, 881 OrigBB->getParent(), OrigBB); 882 NewBBs.push_back(NewBB1); 883 884 // The new block unconditionally branches to the old block. 885 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1); 886 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 887 888 // Move the edges from Preds to point to NewBB1 instead of OrigBB. 889 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 890 // This is slightly more strict than necessary; the minimum requirement 891 // is that there be no more than one indirectbr branching to BB. And 892 // all BlockAddress uses would need to be updated. 893 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 894 "Cannot split an edge from an IndirectBrInst"); 895 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1); 896 } 897 898 bool HasLoopExit = false; 899 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, MSSAU, PreserveLCSSA, 900 HasLoopExit); 901 902 // Update the PHI nodes in OrigBB with the values coming from NewBB1. 903 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit); 904 905 // Move the remaining edges from OrigBB to point to NewBB2. 906 SmallVector<BasicBlock*, 8> NewBB2Preds; 907 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB); 908 i != e; ) { 909 BasicBlock *Pred = *i++; 910 if (Pred == NewBB1) continue; 911 assert(!isa<IndirectBrInst>(Pred->getTerminator()) && 912 "Cannot split an edge from an IndirectBrInst"); 913 NewBB2Preds.push_back(Pred); 914 e = pred_end(OrigBB); 915 } 916 917 BasicBlock *NewBB2 = nullptr; 918 if (!NewBB2Preds.empty()) { 919 // Create another basic block for the rest of OrigBB's predecessors. 920 NewBB2 = BasicBlock::Create(OrigBB->getContext(), 921 OrigBB->getName() + Suffix2, 922 OrigBB->getParent(), OrigBB); 923 NewBBs.push_back(NewBB2); 924 925 // The new block unconditionally branches to the old block. 926 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2); 927 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 928 929 // Move the remaining edges from OrigBB to point to NewBB2. 930 for (BasicBlock *NewBB2Pred : NewBB2Preds) 931 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2); 932 933 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 934 HasLoopExit = false; 935 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, MSSAU, 936 PreserveLCSSA, HasLoopExit); 937 938 // Update the PHI nodes in OrigBB with the values coming from NewBB2. 939 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit); 940 } 941 942 LandingPadInst *LPad = OrigBB->getLandingPadInst(); 943 Instruction *Clone1 = LPad->clone(); 944 Clone1->setName(Twine("lpad") + Suffix1); 945 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1); 946 947 if (NewBB2) { 948 Instruction *Clone2 = LPad->clone(); 949 Clone2->setName(Twine("lpad") + Suffix2); 950 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2); 951 952 // Create a PHI node for the two cloned landingpad instructions only 953 // if the original landingpad instruction has some uses. 954 if (!LPad->use_empty()) { 955 assert(!LPad->getType()->isTokenTy() && 956 "Split cannot be applied if LPad is token type. Otherwise an " 957 "invalid PHINode of token type would be created."); 958 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad); 959 PN->addIncoming(Clone1, NewBB1); 960 PN->addIncoming(Clone2, NewBB2); 961 LPad->replaceAllUsesWith(PN); 962 } 963 LPad->eraseFromParent(); 964 } else { 965 // There is no second clone. Just replace the landing pad with the first 966 // clone. 967 LPad->replaceAllUsesWith(Clone1); 968 LPad->eraseFromParent(); 969 } 970 } 971 972 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, 973 BasicBlock *Pred, 974 DomTreeUpdater *DTU) { 975 Instruction *UncondBranch = Pred->getTerminator(); 976 // Clone the return and add it to the end of the predecessor. 977 Instruction *NewRet = RI->clone(); 978 Pred->getInstList().push_back(NewRet); 979 980 // If the return instruction returns a value, and if the value was a 981 // PHI node in "BB", propagate the right value into the return. 982 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end(); 983 i != e; ++i) { 984 Value *V = *i; 985 Instruction *NewBC = nullptr; 986 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) { 987 // Return value might be bitcasted. Clone and insert it before the 988 // return instruction. 989 V = BCI->getOperand(0); 990 NewBC = BCI->clone(); 991 Pred->getInstList().insert(NewRet->getIterator(), NewBC); 992 *i = NewBC; 993 } 994 995 Instruction *NewEV = nullptr; 996 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) { 997 V = EVI->getOperand(0); 998 NewEV = EVI->clone(); 999 if (NewBC) { 1000 NewBC->setOperand(0, NewEV); 1001 Pred->getInstList().insert(NewBC->getIterator(), NewEV); 1002 } else { 1003 Pred->getInstList().insert(NewRet->getIterator(), NewEV); 1004 *i = NewEV; 1005 } 1006 } 1007 1008 if (PHINode *PN = dyn_cast<PHINode>(V)) { 1009 if (PN->getParent() == BB) { 1010 if (NewEV) { 1011 NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred)); 1012 } else if (NewBC) 1013 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred)); 1014 else 1015 *i = PN->getIncomingValueForBlock(Pred); 1016 } 1017 } 1018 } 1019 1020 // Update any PHI nodes in the returning block to realize that we no 1021 // longer branch to them. 1022 BB->removePredecessor(Pred); 1023 UncondBranch->eraseFromParent(); 1024 1025 if (DTU) 1026 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}}); 1027 1028 return cast<ReturnInst>(NewRet); 1029 } 1030 1031 Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond, 1032 Instruction *SplitBefore, 1033 bool Unreachable, 1034 MDNode *BranchWeights, 1035 DominatorTree *DT, LoopInfo *LI, 1036 BasicBlock *ThenBlock) { 1037 BasicBlock *Head = SplitBefore->getParent(); 1038 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 1039 Instruction *HeadOldTerm = Head->getTerminator(); 1040 LLVMContext &C = Head->getContext(); 1041 Instruction *CheckTerm; 1042 bool CreateThenBlock = (ThenBlock == nullptr); 1043 if (CreateThenBlock) { 1044 ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1045 if (Unreachable) 1046 CheckTerm = new UnreachableInst(C, ThenBlock); 1047 else 1048 CheckTerm = BranchInst::Create(Tail, ThenBlock); 1049 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc()); 1050 } else 1051 CheckTerm = ThenBlock->getTerminator(); 1052 BranchInst *HeadNewTerm = 1053 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond); 1054 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 1055 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 1056 1057 if (DT) { 1058 if (DomTreeNode *OldNode = DT->getNode(Head)) { 1059 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 1060 1061 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head); 1062 for (DomTreeNode *Child : Children) 1063 DT->changeImmediateDominator(Child, NewNode); 1064 1065 // Head dominates ThenBlock. 1066 if (CreateThenBlock) 1067 DT->addNewBlock(ThenBlock, Head); 1068 else 1069 DT->changeImmediateDominator(ThenBlock, Head); 1070 } 1071 } 1072 1073 if (LI) { 1074 if (Loop *L = LI->getLoopFor(Head)) { 1075 L->addBasicBlockToLoop(ThenBlock, *LI); 1076 L->addBasicBlockToLoop(Tail, *LI); 1077 } 1078 } 1079 1080 return CheckTerm; 1081 } 1082 1083 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, 1084 Instruction **ThenTerm, 1085 Instruction **ElseTerm, 1086 MDNode *BranchWeights) { 1087 BasicBlock *Head = SplitBefore->getParent(); 1088 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 1089 Instruction *HeadOldTerm = Head->getTerminator(); 1090 LLVMContext &C = Head->getContext(); 1091 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1092 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1093 *ThenTerm = BranchInst::Create(Tail, ThenBlock); 1094 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 1095 *ElseTerm = BranchInst::Create(Tail, ElseBlock); 1096 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 1097 BranchInst *HeadNewTerm = 1098 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond); 1099 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 1100 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 1101 } 1102 1103 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, 1104 BasicBlock *&IfFalse) { 1105 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin()); 1106 BasicBlock *Pred1 = nullptr; 1107 BasicBlock *Pred2 = nullptr; 1108 1109 if (SomePHI) { 1110 if (SomePHI->getNumIncomingValues() != 2) 1111 return nullptr; 1112 Pred1 = SomePHI->getIncomingBlock(0); 1113 Pred2 = SomePHI->getIncomingBlock(1); 1114 } else { 1115 pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 1116 if (PI == PE) // No predecessor 1117 return nullptr; 1118 Pred1 = *PI++; 1119 if (PI == PE) // Only one predecessor 1120 return nullptr; 1121 Pred2 = *PI++; 1122 if (PI != PE) // More than two predecessors 1123 return nullptr; 1124 } 1125 1126 // We can only handle branches. Other control flow will be lowered to 1127 // branches if possible anyway. 1128 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator()); 1129 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator()); 1130 if (!Pred1Br || !Pred2Br) 1131 return nullptr; 1132 1133 // Eliminate code duplication by ensuring that Pred1Br is conditional if 1134 // either are. 1135 if (Pred2Br->isConditional()) { 1136 // If both branches are conditional, we don't have an "if statement". In 1137 // reality, we could transform this case, but since the condition will be 1138 // required anyway, we stand no chance of eliminating it, so the xform is 1139 // probably not profitable. 1140 if (Pred1Br->isConditional()) 1141 return nullptr; 1142 1143 std::swap(Pred1, Pred2); 1144 std::swap(Pred1Br, Pred2Br); 1145 } 1146 1147 if (Pred1Br->isConditional()) { 1148 // The only thing we have to watch out for here is to make sure that Pred2 1149 // doesn't have incoming edges from other blocks. If it does, the condition 1150 // doesn't dominate BB. 1151 if (!Pred2->getSinglePredecessor()) 1152 return nullptr; 1153 1154 // If we found a conditional branch predecessor, make sure that it branches 1155 // to BB and Pred2Br. If it doesn't, this isn't an "if statement". 1156 if (Pred1Br->getSuccessor(0) == BB && 1157 Pred1Br->getSuccessor(1) == Pred2) { 1158 IfTrue = Pred1; 1159 IfFalse = Pred2; 1160 } else if (Pred1Br->getSuccessor(0) == Pred2 && 1161 Pred1Br->getSuccessor(1) == BB) { 1162 IfTrue = Pred2; 1163 IfFalse = Pred1; 1164 } else { 1165 // We know that one arm of the conditional goes to BB, so the other must 1166 // go somewhere unrelated, and this must not be an "if statement". 1167 return nullptr; 1168 } 1169 1170 return Pred1Br->getCondition(); 1171 } 1172 1173 // Ok, if we got here, both predecessors end with an unconditional branch to 1174 // BB. Don't panic! If both blocks only have a single (identical) 1175 // predecessor, and THAT is a conditional branch, then we're all ok! 1176 BasicBlock *CommonPred = Pred1->getSinglePredecessor(); 1177 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor()) 1178 return nullptr; 1179 1180 // Otherwise, if this is a conditional branch, then we can use it! 1181 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator()); 1182 if (!BI) return nullptr; 1183 1184 assert(BI->isConditional() && "Two successors but not conditional?"); 1185 if (BI->getSuccessor(0) == Pred1) { 1186 IfTrue = Pred1; 1187 IfFalse = Pred2; 1188 } else { 1189 IfTrue = Pred2; 1190 IfFalse = Pred1; 1191 } 1192 return BI->getCondition(); 1193 } 1194 1195 // After creating a control flow hub, the operands of PHINodes in an outgoing 1196 // block Out no longer match the predecessors of that block. Predecessors of Out 1197 // that are incoming blocks to the hub are now replaced by just one edge from 1198 // the hub. To match this new control flow, the corresponding values from each 1199 // PHINode must now be moved a new PHINode in the first guard block of the hub. 1200 // 1201 // This operation cannot be performed with SSAUpdater, because it involves one 1202 // new use: If the block Out is in the list of Incoming blocks, then the newly 1203 // created PHI in the Hub will use itself along that edge from Out to Hub. 1204 static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock, 1205 const SetVector<BasicBlock *> &Incoming, 1206 BasicBlock *FirstGuardBlock) { 1207 auto I = Out->begin(); 1208 while (I != Out->end() && isa<PHINode>(I)) { 1209 auto Phi = cast<PHINode>(I); 1210 auto NewPhi = 1211 PHINode::Create(Phi->getType(), Incoming.size(), 1212 Phi->getName() + ".moved", &FirstGuardBlock->back()); 1213 for (auto In : Incoming) { 1214 Value *V = UndefValue::get(Phi->getType()); 1215 if (In == Out) { 1216 V = NewPhi; 1217 } else if (Phi->getBasicBlockIndex(In) != -1) { 1218 V = Phi->removeIncomingValue(In, false); 1219 } 1220 NewPhi->addIncoming(V, In); 1221 } 1222 assert(NewPhi->getNumIncomingValues() == Incoming.size()); 1223 if (Phi->getNumOperands() == 0) { 1224 Phi->replaceAllUsesWith(NewPhi); 1225 I = Phi->eraseFromParent(); 1226 continue; 1227 } 1228 Phi->addIncoming(NewPhi, GuardBlock); 1229 ++I; 1230 } 1231 } 1232 1233 using BBPredicates = DenseMap<BasicBlock *, PHINode *>; 1234 using BBSetVector = SetVector<BasicBlock *>; 1235 1236 // Redirects the terminator of the incoming block to the first guard 1237 // block in the hub. The condition of the original terminator (if it 1238 // was conditional) and its original successors are returned as a 1239 // tuple <condition, succ0, succ1>. The function additionally filters 1240 // out successors that are not in the set of outgoing blocks. 1241 // 1242 // - condition is non-null iff the branch is conditional. 1243 // - Succ1 is non-null iff the sole/taken target is an outgoing block. 1244 // - Succ2 is non-null iff condition is non-null and the fallthrough 1245 // target is an outgoing block. 1246 static std::tuple<Value *, BasicBlock *, BasicBlock *> 1247 redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock, 1248 const BBSetVector &Outgoing) { 1249 auto Branch = cast<BranchInst>(BB->getTerminator()); 1250 auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr; 1251 1252 BasicBlock *Succ0 = Branch->getSuccessor(0); 1253 BasicBlock *Succ1 = nullptr; 1254 Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr; 1255 1256 if (Branch->isUnconditional()) { 1257 Branch->setSuccessor(0, FirstGuardBlock); 1258 assert(Succ0); 1259 } else { 1260 Succ1 = Branch->getSuccessor(1); 1261 Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr; 1262 assert(Succ0 || Succ1); 1263 if (Succ0 && !Succ1) { 1264 Branch->setSuccessor(0, FirstGuardBlock); 1265 } else if (Succ1 && !Succ0) { 1266 Branch->setSuccessor(1, FirstGuardBlock); 1267 } else { 1268 Branch->eraseFromParent(); 1269 BranchInst::Create(FirstGuardBlock, BB); 1270 } 1271 } 1272 1273 assert(Succ0 || Succ1); 1274 return std::make_tuple(Condition, Succ0, Succ1); 1275 } 1276 1277 // Capture the existing control flow as guard predicates, and redirect 1278 // control flow from every incoming block to the first guard block in 1279 // the hub. 1280 // 1281 // There is one guard predicate for each outgoing block OutBB. The 1282 // predicate is a PHINode with one input for each InBB which 1283 // represents whether the hub should transfer control flow to OutBB if 1284 // it arrived from InBB. These predicates are NOT ORTHOGONAL. The Hub 1285 // evaluates them in the same order as the Outgoing set-vector, and 1286 // control branches to the first outgoing block whose predicate 1287 // evaluates to true. 1288 static void convertToGuardPredicates( 1289 BasicBlock *FirstGuardBlock, BBPredicates &GuardPredicates, 1290 SmallVectorImpl<WeakVH> &DeletionCandidates, const BBSetVector &Incoming, 1291 const BBSetVector &Outgoing) { 1292 auto &Context = Incoming.front()->getContext(); 1293 auto BoolTrue = ConstantInt::getTrue(Context); 1294 auto BoolFalse = ConstantInt::getFalse(Context); 1295 1296 // The predicate for the last outgoing is trivially true, and so we 1297 // process only the first N-1 successors. 1298 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) { 1299 auto Out = Outgoing[i]; 1300 LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n"); 1301 auto Phi = 1302 PHINode::Create(Type::getInt1Ty(Context), Incoming.size(), 1303 StringRef("Guard.") + Out->getName(), FirstGuardBlock); 1304 GuardPredicates[Out] = Phi; 1305 } 1306 1307 for (auto In : Incoming) { 1308 Value *Condition; 1309 BasicBlock *Succ0; 1310 BasicBlock *Succ1; 1311 std::tie(Condition, Succ0, Succ1) = 1312 redirectToHub(In, FirstGuardBlock, Outgoing); 1313 1314 // Optimization: Consider an incoming block A with both successors 1315 // Succ0 and Succ1 in the set of outgoing blocks. The predicates 1316 // for Succ0 and Succ1 complement each other. If Succ0 is visited 1317 // first in the loop below, control will branch to Succ0 using the 1318 // corresponding predicate. But if that branch is not taken, then 1319 // control must reach Succ1, which means that the predicate for 1320 // Succ1 is always true. 1321 bool OneSuccessorDone = false; 1322 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) { 1323 auto Out = Outgoing[i]; 1324 auto Phi = GuardPredicates[Out]; 1325 if (Out != Succ0 && Out != Succ1) { 1326 Phi->addIncoming(BoolFalse, In); 1327 continue; 1328 } 1329 // Optimization: When only one successor is an outgoing block, 1330 // the predicate is always true. 1331 if (!Succ0 || !Succ1 || OneSuccessorDone) { 1332 Phi->addIncoming(BoolTrue, In); 1333 continue; 1334 } 1335 assert(Succ0 && Succ1); 1336 OneSuccessorDone = true; 1337 if (Out == Succ0) { 1338 Phi->addIncoming(Condition, In); 1339 continue; 1340 } 1341 auto Inverted = invertCondition(Condition); 1342 DeletionCandidates.push_back(Condition); 1343 Phi->addIncoming(Inverted, In); 1344 } 1345 } 1346 } 1347 1348 // For each outgoing block OutBB, create a guard block in the Hub. The 1349 // first guard block was already created outside, and available as the 1350 // first element in the vector of guard blocks. 1351 // 1352 // Each guard block terminates in a conditional branch that transfers 1353 // control to the corresponding outgoing block or the next guard 1354 // block. The last guard block has two outgoing blocks as successors 1355 // since the condition for the final outgoing block is trivially 1356 // true. So we create one less block (including the first guard block) 1357 // than the number of outgoing blocks. 1358 static void createGuardBlocks(SmallVectorImpl<BasicBlock *> &GuardBlocks, 1359 Function *F, const BBSetVector &Outgoing, 1360 BBPredicates &GuardPredicates, StringRef Prefix) { 1361 for (int i = 0, e = Outgoing.size() - 2; i != e; ++i) { 1362 GuardBlocks.push_back( 1363 BasicBlock::Create(F->getContext(), Prefix + ".guard", F)); 1364 } 1365 assert(GuardBlocks.size() == GuardPredicates.size()); 1366 1367 // To help keep the loop simple, temporarily append the last 1368 // outgoing block to the list of guard blocks. 1369 GuardBlocks.push_back(Outgoing.back()); 1370 1371 for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) { 1372 auto Out = Outgoing[i]; 1373 assert(GuardPredicates.count(Out)); 1374 BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out], 1375 GuardBlocks[i]); 1376 } 1377 1378 // Remove the last block from the guard list. 1379 GuardBlocks.pop_back(); 1380 } 1381 1382 BasicBlock *llvm::CreateControlFlowHub( 1383 DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks, 1384 const BBSetVector &Incoming, const BBSetVector &Outgoing, 1385 const StringRef Prefix) { 1386 auto F = Incoming.front()->getParent(); 1387 auto FirstGuardBlock = 1388 BasicBlock::Create(F->getContext(), Prefix + ".guard", F); 1389 1390 SmallVector<DominatorTree::UpdateType, 16> Updates; 1391 if (DTU) { 1392 for (auto In : Incoming) { 1393 for (auto Succ : successors(In)) { 1394 if (Outgoing.count(Succ)) 1395 Updates.push_back({DominatorTree::Delete, In, Succ}); 1396 } 1397 Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock}); 1398 } 1399 } 1400 1401 BBPredicates GuardPredicates; 1402 SmallVector<WeakVH, 8> DeletionCandidates; 1403 convertToGuardPredicates(FirstGuardBlock, GuardPredicates, DeletionCandidates, 1404 Incoming, Outgoing); 1405 1406 GuardBlocks.push_back(FirstGuardBlock); 1407 createGuardBlocks(GuardBlocks, F, Outgoing, GuardPredicates, Prefix); 1408 1409 // Update the PHINodes in each outgoing block to match the new control flow. 1410 for (int i = 0, e = GuardBlocks.size(); i != e; ++i) { 1411 reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock); 1412 } 1413 reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock); 1414 1415 if (DTU) { 1416 int NumGuards = GuardBlocks.size(); 1417 assert((int)Outgoing.size() == NumGuards + 1); 1418 for (int i = 0; i != NumGuards - 1; ++i) { 1419 Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]}); 1420 Updates.push_back( 1421 {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]}); 1422 } 1423 Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1], 1424 Outgoing[NumGuards - 1]}); 1425 Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1], 1426 Outgoing[NumGuards]}); 1427 DTU->applyUpdates(Updates); 1428 } 1429 1430 for (auto I : DeletionCandidates) { 1431 if (I->use_empty()) 1432 if (auto Inst = dyn_cast_or_null<Instruction>(I)) 1433 Inst->eraseFromParent(); 1434 } 1435 1436 return FirstGuardBlock; 1437 } 1438