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