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