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