1 //===- TailDuplicator.cpp - Duplicate blocks into predecessors' tails -----===// 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 utility class duplicates basic blocks ending in unconditional branches 10 // into the tails of their predecessors. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/TailDuplicator.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/DenseSet.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/ProfileSummaryInfo.h" 23 #include "llvm/CodeGen/MachineBasicBlock.h" 24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/MachineInstr.h" 28 #include "llvm/CodeGen/MachineInstrBuilder.h" 29 #include "llvm/CodeGen/MachineOperand.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/CodeGen/MachineSizeOpts.h" 32 #include "llvm/CodeGen/MachineSSAUpdater.h" 33 #include "llvm/CodeGen/TargetInstrInfo.h" 34 #include "llvm/CodeGen/TargetRegisterInfo.h" 35 #include "llvm/CodeGen/TargetSubtargetInfo.h" 36 #include "llvm/IR/DebugLoc.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/Support/CommandLine.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/ErrorHandling.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include "llvm/Target/TargetMachine.h" 43 #include <algorithm> 44 #include <cassert> 45 #include <iterator> 46 #include <utility> 47 48 using namespace llvm; 49 50 #define DEBUG_TYPE "tailduplication" 51 52 STATISTIC(NumTails, "Number of tails duplicated"); 53 STATISTIC(NumTailDups, "Number of tail duplicated blocks"); 54 STATISTIC(NumTailDupAdded, 55 "Number of instructions added due to tail duplication"); 56 STATISTIC(NumTailDupRemoved, 57 "Number of instructions removed due to tail duplication"); 58 STATISTIC(NumDeadBlocks, "Number of dead blocks removed"); 59 STATISTIC(NumAddedPHIs, "Number of phis added"); 60 61 // Heuristic for tail duplication. 62 static cl::opt<unsigned> TailDuplicateSize( 63 "tail-dup-size", 64 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2), 65 cl::Hidden); 66 67 static cl::opt<unsigned> TailDupIndirectBranchSize( 68 "tail-dup-indirect-size", 69 cl::desc("Maximum instructions to consider tail duplicating blocks that " 70 "end with indirect branches."), cl::init(20), 71 cl::Hidden); 72 73 static cl::opt<unsigned> TailDupJmpTableLoopSize( 74 "tail-dup-jmptable-loop-size", 75 cl::desc("Maximum loop latches to consider tail duplication that are " 76 "successors of loop header."), 77 cl::init(128), cl::Hidden); 78 79 static cl::opt<bool> 80 TailDupVerify("tail-dup-verify", 81 cl::desc("Verify sanity of PHI instructions during taildup"), 82 cl::init(false), cl::Hidden); 83 84 static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U), 85 cl::Hidden); 86 87 void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc, 88 const MachineBranchProbabilityInfo *MBPIin, 89 MBFIWrapper *MBFIin, 90 ProfileSummaryInfo *PSIin, 91 bool LayoutModeIn, unsigned TailDupSizeIn) { 92 MF = &MFin; 93 TII = MF->getSubtarget().getInstrInfo(); 94 TRI = MF->getSubtarget().getRegisterInfo(); 95 MRI = &MF->getRegInfo(); 96 MMI = &MF->getMMI(); 97 MBPI = MBPIin; 98 MBFI = MBFIin; 99 PSI = PSIin; 100 TailDupSize = TailDupSizeIn; 101 102 assert(MBPI != nullptr && "Machine Branch Probability Info required"); 103 104 LayoutMode = LayoutModeIn; 105 this->PreRegAlloc = PreRegAlloc; 106 } 107 108 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) { 109 for (MachineBasicBlock &MBB : llvm::drop_begin(MF)) { 110 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB.pred_begin(), 111 MBB.pred_end()); 112 MachineBasicBlock::iterator MI = MBB.begin(); 113 while (MI != MBB.end()) { 114 if (!MI->isPHI()) 115 break; 116 for (MachineBasicBlock *PredBB : Preds) { 117 bool Found = false; 118 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) { 119 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB(); 120 if (PHIBB == PredBB) { 121 Found = true; 122 break; 123 } 124 } 125 if (!Found) { 126 dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": " 127 << *MI; 128 dbgs() << " missing input from predecessor " 129 << printMBBReference(*PredBB) << '\n'; 130 llvm_unreachable(nullptr); 131 } 132 } 133 134 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) { 135 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB(); 136 if (CheckExtra && !Preds.count(PHIBB)) { 137 dbgs() << "Warning: malformed PHI in " << printMBBReference(MBB) 138 << ": " << *MI; 139 dbgs() << " extra input from predecessor " 140 << printMBBReference(*PHIBB) << '\n'; 141 llvm_unreachable(nullptr); 142 } 143 if (PHIBB->getNumber() < 0) { 144 dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": " 145 << *MI; 146 dbgs() << " non-existing " << printMBBReference(*PHIBB) << '\n'; 147 llvm_unreachable(nullptr); 148 } 149 } 150 ++MI; 151 } 152 } 153 } 154 155 /// Tail duplicate the block and cleanup. 156 /// \p IsSimple - return value of isSimpleBB 157 /// \p MBB - block to be duplicated 158 /// \p ForcedLayoutPred - If non-null, treat this block as the layout 159 /// predecessor, instead of using the ordering in MF 160 /// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of 161 /// all Preds that received a copy of \p MBB. 162 /// \p RemovalCallback - if non-null, called just before MBB is deleted. 163 bool TailDuplicator::tailDuplicateAndUpdate( 164 bool IsSimple, MachineBasicBlock *MBB, 165 MachineBasicBlock *ForcedLayoutPred, 166 SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds, 167 function_ref<void(MachineBasicBlock *)> *RemovalCallback, 168 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) { 169 // Save the successors list. 170 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(), 171 MBB->succ_end()); 172 173 SmallVector<MachineBasicBlock *, 8> TDBBs; 174 SmallVector<MachineInstr *, 16> Copies; 175 if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred, 176 TDBBs, Copies, CandidatePtr)) 177 return false; 178 179 ++NumTails; 180 181 SmallVector<MachineInstr *, 8> NewPHIs; 182 MachineSSAUpdater SSAUpdate(*MF, &NewPHIs); 183 184 // TailBB's immediate successors are now successors of those predecessors 185 // which duplicated TailBB. Add the predecessors as sources to the PHI 186 // instructions. 187 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken(); 188 if (PreRegAlloc) 189 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs); 190 191 // If it is dead, remove it. 192 if (isDead) { 193 NumTailDupRemoved += MBB->size(); 194 removeDeadBlock(MBB, RemovalCallback); 195 ++NumDeadBlocks; 196 } 197 198 // Update SSA form. 199 if (!SSAUpdateVRs.empty()) { 200 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) { 201 unsigned VReg = SSAUpdateVRs[i]; 202 SSAUpdate.Initialize(VReg); 203 204 // If the original definition is still around, add it as an available 205 // value. 206 MachineInstr *DefMI = MRI->getVRegDef(VReg); 207 MachineBasicBlock *DefBB = nullptr; 208 if (DefMI) { 209 DefBB = DefMI->getParent(); 210 SSAUpdate.AddAvailableValue(DefBB, VReg); 211 } 212 213 // Add the new vregs as available values. 214 DenseMap<Register, AvailableValsTy>::iterator LI = 215 SSAUpdateVals.find(VReg); 216 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) { 217 MachineBasicBlock *SrcBB = LI->second[j].first; 218 Register SrcReg = LI->second[j].second; 219 SSAUpdate.AddAvailableValue(SrcBB, SrcReg); 220 } 221 222 // Rewrite uses that are outside of the original def's block. 223 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg); 224 // Only remove instructions after loop, as DBG_VALUE_LISTs with multiple 225 // uses of VReg may invalidate the use iterator when erased. 226 SmallPtrSet<MachineInstr *, 4> InstrsToRemove; 227 while (UI != MRI->use_end()) { 228 MachineOperand &UseMO = *UI; 229 MachineInstr *UseMI = UseMO.getParent(); 230 ++UI; 231 if (UseMI->isDebugValue()) { 232 // SSAUpdate can replace the use with an undef. That creates 233 // a debug instruction that is a kill. 234 // FIXME: Should it SSAUpdate job to delete debug instructions 235 // instead of replacing the use with undef? 236 InstrsToRemove.insert(UseMI); 237 continue; 238 } 239 if (UseMI->getParent() == DefBB && !UseMI->isPHI()) 240 continue; 241 SSAUpdate.RewriteUse(UseMO); 242 } 243 for (auto *MI : InstrsToRemove) 244 MI->eraseFromParent(); 245 } 246 247 SSAUpdateVRs.clear(); 248 SSAUpdateVals.clear(); 249 } 250 251 // Eliminate some of the copies inserted by tail duplication to maintain 252 // SSA form. 253 for (unsigned i = 0, e = Copies.size(); i != e; ++i) { 254 MachineInstr *Copy = Copies[i]; 255 if (!Copy->isCopy()) 256 continue; 257 Register Dst = Copy->getOperand(0).getReg(); 258 Register Src = Copy->getOperand(1).getReg(); 259 if (MRI->hasOneNonDBGUse(Src) && 260 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) { 261 // Copy is the only use. Do trivial copy propagation here. 262 MRI->replaceRegWith(Dst, Src); 263 Copy->eraseFromParent(); 264 } 265 } 266 267 if (NewPHIs.size()) 268 NumAddedPHIs += NewPHIs.size(); 269 270 if (DuplicatedPreds) 271 *DuplicatedPreds = std::move(TDBBs); 272 273 return true; 274 } 275 276 /// Look for small blocks that are unconditionally branched to and do not fall 277 /// through. Tail-duplicate their instructions into their predecessors to 278 /// eliminate (dynamic) branches. 279 bool TailDuplicator::tailDuplicateBlocks() { 280 bool MadeChange = false; 281 282 if (PreRegAlloc && TailDupVerify) { 283 LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n"); 284 VerifyPHIs(*MF, true); 285 } 286 287 for (MachineBasicBlock &MBB : 288 llvm::make_early_inc_range(llvm::drop_begin(*MF))) { 289 if (NumTails == TailDupLimit) 290 break; 291 292 bool IsSimple = isSimpleBB(&MBB); 293 294 if (!shouldTailDuplicate(IsSimple, MBB)) 295 continue; 296 297 MadeChange |= tailDuplicateAndUpdate(IsSimple, &MBB, nullptr); 298 } 299 300 if (PreRegAlloc && TailDupVerify) 301 VerifyPHIs(*MF, false); 302 303 return MadeChange; 304 } 305 306 static bool isDefLiveOut(Register Reg, MachineBasicBlock *BB, 307 const MachineRegisterInfo *MRI) { 308 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) { 309 if (UseMI.isDebugValue()) 310 continue; 311 if (UseMI.getParent() != BB) 312 return true; 313 } 314 return false; 315 } 316 317 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) { 318 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) 319 if (MI->getOperand(i + 1).getMBB() == SrcBB) 320 return i; 321 return 0; 322 } 323 324 // Remember which registers are used by phis in this block. This is 325 // used to determine which registers are liveout while modifying the 326 // block (which is why we need to copy the information). 327 static void getRegsUsedByPHIs(const MachineBasicBlock &BB, 328 DenseSet<Register> *UsedByPhi) { 329 for (const auto &MI : BB) { 330 if (!MI.isPHI()) 331 break; 332 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) { 333 Register SrcReg = MI.getOperand(i).getReg(); 334 UsedByPhi->insert(SrcReg); 335 } 336 } 337 } 338 339 /// Add a definition and source virtual registers pair for SSA update. 340 void TailDuplicator::addSSAUpdateEntry(Register OrigReg, Register NewReg, 341 MachineBasicBlock *BB) { 342 DenseMap<Register, AvailableValsTy>::iterator LI = 343 SSAUpdateVals.find(OrigReg); 344 if (LI != SSAUpdateVals.end()) 345 LI->second.push_back(std::make_pair(BB, NewReg)); 346 else { 347 AvailableValsTy Vals; 348 Vals.push_back(std::make_pair(BB, NewReg)); 349 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals)); 350 SSAUpdateVRs.push_back(OrigReg); 351 } 352 } 353 354 /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the 355 /// source register that's contributed by PredBB and update SSA update map. 356 void TailDuplicator::processPHI( 357 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB, 358 DenseMap<Register, RegSubRegPair> &LocalVRMap, 359 SmallVectorImpl<std::pair<Register, RegSubRegPair>> &Copies, 360 const DenseSet<Register> &RegsUsedByPhi, bool Remove) { 361 Register DefReg = MI->getOperand(0).getReg(); 362 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB); 363 assert(SrcOpIdx && "Unable to find matching PHI source?"); 364 Register SrcReg = MI->getOperand(SrcOpIdx).getReg(); 365 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg(); 366 const TargetRegisterClass *RC = MRI->getRegClass(DefReg); 367 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg))); 368 369 // Insert a copy from source to the end of the block. The def register is the 370 // available value liveout of the block. 371 Register NewDef = MRI->createVirtualRegister(RC); 372 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg))); 373 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg)) 374 addSSAUpdateEntry(DefReg, NewDef, PredBB); 375 376 if (!Remove) 377 return; 378 379 // Remove PredBB from the PHI node. 380 MI->RemoveOperand(SrcOpIdx + 1); 381 MI->RemoveOperand(SrcOpIdx); 382 if (MI->getNumOperands() == 1) 383 MI->eraseFromParent(); 384 } 385 386 /// Duplicate a TailBB instruction to PredBB and update 387 /// the source operands due to earlier PHI translation. 388 void TailDuplicator::duplicateInstruction( 389 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB, 390 DenseMap<Register, RegSubRegPair> &LocalVRMap, 391 const DenseSet<Register> &UsedByPhi) { 392 // Allow duplication of CFI instructions. 393 if (MI->isCFIInstruction()) { 394 BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()), 395 TII->get(TargetOpcode::CFI_INSTRUCTION)).addCFIIndex( 396 MI->getOperand(0).getCFIIndex()); 397 return; 398 } 399 MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI); 400 if (PreRegAlloc) { 401 for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) { 402 MachineOperand &MO = NewMI.getOperand(i); 403 if (!MO.isReg()) 404 continue; 405 Register Reg = MO.getReg(); 406 if (!Register::isVirtualRegister(Reg)) 407 continue; 408 if (MO.isDef()) { 409 const TargetRegisterClass *RC = MRI->getRegClass(Reg); 410 Register NewReg = MRI->createVirtualRegister(RC); 411 MO.setReg(NewReg); 412 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0))); 413 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg)) 414 addSSAUpdateEntry(Reg, NewReg, PredBB); 415 } else { 416 auto VI = LocalVRMap.find(Reg); 417 if (VI != LocalVRMap.end()) { 418 // Need to make sure that the register class of the mapped register 419 // will satisfy the constraints of the class of the register being 420 // replaced. 421 auto *OrigRC = MRI->getRegClass(Reg); 422 auto *MappedRC = MRI->getRegClass(VI->second.Reg); 423 const TargetRegisterClass *ConstrRC; 424 if (VI->second.SubReg != 0) { 425 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC, 426 VI->second.SubReg); 427 if (ConstrRC) { 428 // The actual constraining (as in "find appropriate new class") 429 // is done by getMatchingSuperRegClass, so now we only need to 430 // change the class of the mapped register. 431 MRI->setRegClass(VI->second.Reg, ConstrRC); 432 } 433 } else { 434 // For mapped registers that do not have sub-registers, simply 435 // restrict their class to match the original one. 436 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC); 437 } 438 439 if (ConstrRC) { 440 // If the class constraining succeeded, we can simply replace 441 // the old register with the mapped one. 442 MO.setReg(VI->second.Reg); 443 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a 444 // sub-register, we need to compose the sub-register indices. 445 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(), 446 VI->second.SubReg)); 447 } else { 448 // The direct replacement is not possible, due to failing register 449 // class constraints. An explicit COPY is necessary. Create one 450 // that can be reused 451 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI); 452 if (NewRC == nullptr) 453 NewRC = OrigRC; 454 Register NewReg = MRI->createVirtualRegister(NewRC); 455 BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(), 456 TII->get(TargetOpcode::COPY), NewReg) 457 .addReg(VI->second.Reg, 0, VI->second.SubReg); 458 LocalVRMap.erase(VI); 459 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0))); 460 MO.setReg(NewReg); 461 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which 462 // is equivalent to the whole register Reg. Hence, Reg:subreg 463 // is same as NewReg:subreg, so keep the sub-register index 464 // unchanged. 465 } 466 // Clear any kill flags from this operand. The new register could 467 // have uses after this one, so kills are not valid here. 468 MO.setIsKill(false); 469 } 470 } 471 } 472 } 473 } 474 475 /// After FromBB is tail duplicated into its predecessor blocks, the successors 476 /// have gained new predecessors. Update the PHI instructions in them 477 /// accordingly. 478 void TailDuplicator::updateSuccessorsPHIs( 479 MachineBasicBlock *FromBB, bool isDead, 480 SmallVectorImpl<MachineBasicBlock *> &TDBBs, 481 SmallSetVector<MachineBasicBlock *, 8> &Succs) { 482 for (MachineBasicBlock *SuccBB : Succs) { 483 for (MachineInstr &MI : *SuccBB) { 484 if (!MI.isPHI()) 485 break; 486 MachineInstrBuilder MIB(*FromBB->getParent(), MI); 487 unsigned Idx = 0; 488 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) { 489 MachineOperand &MO = MI.getOperand(i + 1); 490 if (MO.getMBB() == FromBB) { 491 Idx = i; 492 break; 493 } 494 } 495 496 assert(Idx != 0); 497 MachineOperand &MO0 = MI.getOperand(Idx); 498 Register Reg = MO0.getReg(); 499 if (isDead) { 500 // Folded into the previous BB. 501 // There could be duplicate phi source entries. FIXME: Should sdisel 502 // or earlier pass fixed this? 503 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) { 504 MachineOperand &MO = MI.getOperand(i + 1); 505 if (MO.getMBB() == FromBB) { 506 MI.RemoveOperand(i + 1); 507 MI.RemoveOperand(i); 508 } 509 } 510 } else 511 Idx = 0; 512 513 // If Idx is set, the operands at Idx and Idx+1 must be removed. 514 // We reuse the location to avoid expensive RemoveOperand calls. 515 516 DenseMap<Register, AvailableValsTy>::iterator LI = 517 SSAUpdateVals.find(Reg); 518 if (LI != SSAUpdateVals.end()) { 519 // This register is defined in the tail block. 520 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) { 521 MachineBasicBlock *SrcBB = LI->second[j].first; 522 // If we didn't duplicate a bb into a particular predecessor, we 523 // might still have added an entry to SSAUpdateVals to correcly 524 // recompute SSA. If that case, avoid adding a dummy extra argument 525 // this PHI. 526 if (!SrcBB->isSuccessor(SuccBB)) 527 continue; 528 529 Register SrcReg = LI->second[j].second; 530 if (Idx != 0) { 531 MI.getOperand(Idx).setReg(SrcReg); 532 MI.getOperand(Idx + 1).setMBB(SrcBB); 533 Idx = 0; 534 } else { 535 MIB.addReg(SrcReg).addMBB(SrcBB); 536 } 537 } 538 } else { 539 // Live in tail block, must also be live in predecessors. 540 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) { 541 MachineBasicBlock *SrcBB = TDBBs[j]; 542 if (Idx != 0) { 543 MI.getOperand(Idx).setReg(Reg); 544 MI.getOperand(Idx + 1).setMBB(SrcBB); 545 Idx = 0; 546 } else { 547 MIB.addReg(Reg).addMBB(SrcBB); 548 } 549 } 550 } 551 if (Idx != 0) { 552 MI.RemoveOperand(Idx + 1); 553 MI.RemoveOperand(Idx); 554 } 555 } 556 } 557 } 558 559 /// Determine if it is profitable to duplicate this block. 560 bool TailDuplicator::shouldTailDuplicate(bool IsSimple, 561 MachineBasicBlock &TailBB) { 562 // When doing tail-duplication during layout, the block ordering is in flux, 563 // so canFallThrough returns a result based on incorrect information and 564 // should just be ignored. 565 if (!LayoutMode && TailBB.canFallThrough()) 566 return false; 567 568 // Don't try to tail-duplicate single-block loops. 569 if (TailBB.isSuccessor(&TailBB)) 570 return false; 571 572 // When doing tail-duplication with jumptable loops like: 573 // 1 -> 2 <-> 3 | 574 // \ <-> 4 | 575 // \ <-> 5 | 576 // \ <-> ... | 577 // \---> rest | 578 // quadratic number of edges and much more loops are added to CFG. This 579 // may cause compile time regression when jumptable is quiet large. 580 // So set the limit on jumptable cases. 581 auto isLargeJumpTableLoop = [](const MachineBasicBlock &TailBB) { 582 const SmallPtrSet<const MachineBasicBlock *, 8> Preds(TailBB.pred_begin(), 583 TailBB.pred_end()); 584 // Check the basic block has large number of successors, all of them only 585 // have one successor which is the basic block itself. 586 return llvm::count_if( 587 TailBB.successors(), [&](const MachineBasicBlock *SuccBB) { 588 return Preds.count(SuccBB) && SuccBB->succ_size() == 1; 589 }) > TailDupJmpTableLoopSize; 590 }; 591 592 if (isLargeJumpTableLoop(TailBB)) 593 return false; 594 595 // Set the limit on the cost to duplicate. When optimizing for size, 596 // duplicate only one, because one branch instruction can be eliminated to 597 // compensate for the duplication. 598 unsigned MaxDuplicateCount; 599 bool OptForSize = MF->getFunction().hasOptSize() || 600 llvm::shouldOptimizeForSize(&TailBB, PSI, MBFI); 601 if (TailDupSize == 0) 602 MaxDuplicateCount = TailDuplicateSize; 603 else 604 MaxDuplicateCount = TailDupSize; 605 if (OptForSize) 606 MaxDuplicateCount = 1; 607 608 // If the block to be duplicated ends in an unanalyzable fallthrough, don't 609 // duplicate it. 610 // A similar check is necessary in MachineBlockPlacement to make sure pairs of 611 // blocks with unanalyzable fallthrough get layed out contiguously. 612 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 613 SmallVector<MachineOperand, 4> PredCond; 614 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) && 615 TailBB.canFallThrough()) 616 return false; 617 618 // If the target has hardware branch prediction that can handle indirect 619 // branches, duplicating them can often make them predictable when there 620 // are common paths through the code. The limit needs to be high enough 621 // to allow undoing the effects of tail merging and other optimizations 622 // that rearrange the predecessors of the indirect branch. 623 624 bool HasIndirectbr = false; 625 if (!TailBB.empty()) 626 HasIndirectbr = TailBB.back().isIndirectBranch(); 627 628 if (HasIndirectbr && PreRegAlloc) 629 MaxDuplicateCount = TailDupIndirectBranchSize; 630 631 // Check the instructions in the block to determine whether tail-duplication 632 // is invalid or unlikely to be profitable. 633 unsigned InstrCount = 0; 634 for (MachineInstr &MI : TailBB) { 635 // Non-duplicable things shouldn't be tail-duplicated. 636 // CFI instructions are marked as non-duplicable, because Darwin compact 637 // unwind info emission can't handle multiple prologue setups. In case of 638 // DWARF, allow them be duplicated, so that their existence doesn't prevent 639 // tail duplication of some basic blocks, that would be duplicated otherwise. 640 if (MI.isNotDuplicable() && 641 (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() || 642 !MI.isCFIInstruction())) 643 return false; 644 645 // Convergent instructions can be duplicated only if doing so doesn't add 646 // new control dependencies, which is what we're going to do here. 647 if (MI.isConvergent()) 648 return false; 649 650 // Do not duplicate 'return' instructions if this is a pre-regalloc run. 651 // A return may expand into a lot more instructions (e.g. reload of callee 652 // saved registers) after PEI. 653 if (PreRegAlloc && MI.isReturn()) 654 return false; 655 656 // Avoid duplicating calls before register allocation. Calls presents a 657 // barrier to register allocation so duplicating them may end up increasing 658 // spills. 659 if (PreRegAlloc && MI.isCall()) 660 return false; 661 662 // TailDuplicator::appendCopies will erroneously place COPYs after 663 // INLINEASM_BR instructions after 4b0aa5724fea, which demonstrates the same 664 // bug that was fixed in f7a53d82c090. 665 // FIXME: Use findPHICopyInsertPoint() to find the correct insertion point 666 // for the COPY when replacing PHIs. 667 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) 668 return false; 669 670 if (MI.isBundle()) 671 InstrCount += MI.getBundleSize(); 672 else if (!MI.isPHI() && !MI.isMetaInstruction()) 673 InstrCount += 1; 674 675 if (InstrCount > MaxDuplicateCount) 676 return false; 677 } 678 679 // Check if any of the successors of TailBB has a PHI node in which the 680 // value corresponding to TailBB uses a subregister. 681 // If a phi node uses a register paired with a subregister, the actual 682 // "value type" of the phi may differ from the type of the register without 683 // any subregisters. Due to a bug, tail duplication may add a new operand 684 // without a necessary subregister, producing an invalid code. This is 685 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll. 686 // Disable tail duplication for this case for now, until the problem is 687 // fixed. 688 for (auto SB : TailBB.successors()) { 689 for (auto &I : *SB) { 690 if (!I.isPHI()) 691 break; 692 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB); 693 assert(Idx != 0); 694 MachineOperand &PU = I.getOperand(Idx); 695 if (PU.getSubReg() != 0) 696 return false; 697 } 698 } 699 700 if (HasIndirectbr && PreRegAlloc) 701 return true; 702 703 if (IsSimple) 704 return true; 705 706 if (!PreRegAlloc) 707 return true; 708 709 return canCompletelyDuplicateBB(TailBB); 710 } 711 712 /// True if this BB has only one unconditional jump. 713 bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) { 714 if (TailBB->succ_size() != 1) 715 return false; 716 if (TailBB->pred_empty()) 717 return false; 718 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr(true); 719 if (I == TailBB->end()) 720 return true; 721 return I->isUnconditionalBranch(); 722 } 723 724 static bool bothUsedInPHI(const MachineBasicBlock &A, 725 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) { 726 for (MachineBasicBlock *BB : A.successors()) 727 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI()) 728 return true; 729 730 return false; 731 } 732 733 bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) { 734 for (MachineBasicBlock *PredBB : BB.predecessors()) { 735 if (PredBB->succ_size() > 1) 736 return false; 737 738 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 739 SmallVector<MachineOperand, 4> PredCond; 740 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond)) 741 return false; 742 743 if (!PredCond.empty()) 744 return false; 745 } 746 return true; 747 } 748 749 bool TailDuplicator::duplicateSimpleBB( 750 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs, 751 const DenseSet<Register> &UsedByPhi, 752 SmallVectorImpl<MachineInstr *> &Copies) { 753 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(), 754 TailBB->succ_end()); 755 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->predecessors()); 756 bool Changed = false; 757 for (MachineBasicBlock *PredBB : Preds) { 758 if (PredBB->hasEHPadSuccessor() || PredBB->mayHaveInlineAsmBr()) 759 continue; 760 761 if (bothUsedInPHI(*PredBB, Succs)) 762 continue; 763 764 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 765 SmallVector<MachineOperand, 4> PredCond; 766 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond)) 767 continue; 768 769 Changed = true; 770 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB 771 << "From simple Succ: " << *TailBB); 772 773 MachineBasicBlock *NewTarget = *TailBB->succ_begin(); 774 MachineBasicBlock *NextBB = PredBB->getNextNode(); 775 776 // Make PredFBB explicit. 777 if (PredCond.empty()) 778 PredFBB = PredTBB; 779 780 // Make fall through explicit. 781 if (!PredTBB) 782 PredTBB = NextBB; 783 if (!PredFBB) 784 PredFBB = NextBB; 785 786 // Redirect 787 if (PredFBB == TailBB) 788 PredFBB = NewTarget; 789 if (PredTBB == TailBB) 790 PredTBB = NewTarget; 791 792 // Make the branch unconditional if possible 793 if (PredTBB == PredFBB) { 794 PredCond.clear(); 795 PredFBB = nullptr; 796 } 797 798 // Avoid adding fall through branches. 799 if (PredFBB == NextBB) 800 PredFBB = nullptr; 801 if (PredTBB == NextBB && PredFBB == nullptr) 802 PredTBB = nullptr; 803 804 auto DL = PredBB->findBranchDebugLoc(); 805 TII->removeBranch(*PredBB); 806 807 if (!PredBB->isSuccessor(NewTarget)) 808 PredBB->replaceSuccessor(TailBB, NewTarget); 809 else { 810 PredBB->removeSuccessor(TailBB, true); 811 assert(PredBB->succ_size() <= 1); 812 } 813 814 if (PredTBB) 815 TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL); 816 817 TDBBs.push_back(PredBB); 818 } 819 return Changed; 820 } 821 822 bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB, 823 MachineBasicBlock *PredBB) { 824 // EH edges are ignored by analyzeBranch. 825 if (PredBB->succ_size() > 1) 826 return false; 827 828 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 829 SmallVector<MachineOperand, 4> PredCond; 830 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond)) 831 return false; 832 if (!PredCond.empty()) 833 return false; 834 return true; 835 } 836 837 /// If it is profitable, duplicate TailBB's contents in each 838 /// of its predecessors. 839 /// \p IsSimple result of isSimpleBB 840 /// \p TailBB Block to be duplicated. 841 /// \p ForcedLayoutPred When non-null, use this block as the layout predecessor 842 /// instead of the previous block in MF's order. 843 /// \p TDBBs A vector to keep track of all blocks tail-duplicated 844 /// into. 845 /// \p Copies A vector of copy instructions inserted. Used later to 846 /// walk all the inserted copies and remove redundant ones. 847 bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB, 848 MachineBasicBlock *ForcedLayoutPred, 849 SmallVectorImpl<MachineBasicBlock *> &TDBBs, 850 SmallVectorImpl<MachineInstr *> &Copies, 851 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) { 852 LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB) 853 << '\n'); 854 855 bool ShouldUpdateTerminators = TailBB->canFallThrough(); 856 857 DenseSet<Register> UsedByPhi; 858 getRegsUsedByPHIs(*TailBB, &UsedByPhi); 859 860 if (IsSimple) 861 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies); 862 863 // Iterate through all the unique predecessors and tail-duplicate this 864 // block into them, if possible. Copying the list ahead of time also 865 // avoids trouble with the predecessor list reallocating. 866 bool Changed = false; 867 SmallSetVector<MachineBasicBlock *, 8> Preds; 868 if (CandidatePtr) 869 Preds.insert(CandidatePtr->begin(), CandidatePtr->end()); 870 else 871 Preds.insert(TailBB->pred_begin(), TailBB->pred_end()); 872 873 for (MachineBasicBlock *PredBB : Preds) { 874 assert(TailBB != PredBB && 875 "Single-block loop should have been rejected earlier!"); 876 877 if (!canTailDuplicate(TailBB, PredBB)) 878 continue; 879 880 // Don't duplicate into a fall-through predecessor (at least for now). 881 // If profile is available, findDuplicateCandidates can choose better 882 // fall-through predecessor. 883 if (!(MF->getFunction().hasProfileData() && LayoutMode)) { 884 bool IsLayoutSuccessor = false; 885 if (ForcedLayoutPred) 886 IsLayoutSuccessor = (ForcedLayoutPred == PredBB); 887 else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough()) 888 IsLayoutSuccessor = true; 889 if (IsLayoutSuccessor) 890 continue; 891 } 892 893 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB 894 << "From Succ: " << *TailBB); 895 896 TDBBs.push_back(PredBB); 897 898 // Remove PredBB's unconditional branch. 899 TII->removeBranch(*PredBB); 900 901 // Clone the contents of TailBB into PredBB. 902 DenseMap<Register, RegSubRegPair> LocalVRMap; 903 SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos; 904 for (MachineInstr &MI : llvm::make_early_inc_range(*TailBB)) { 905 if (MI.isPHI()) { 906 // Replace the uses of the def of the PHI with the register coming 907 // from PredBB. 908 processPHI(&MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true); 909 } else { 910 // Replace def of virtual registers with new registers, and update 911 // uses with PHI source register or the new registers. 912 duplicateInstruction(&MI, TailBB, PredBB, LocalVRMap, UsedByPhi); 913 } 914 } 915 appendCopies(PredBB, CopyInfos, Copies); 916 917 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch 918 919 // Update the CFG. 920 PredBB->removeSuccessor(PredBB->succ_begin()); 921 assert(PredBB->succ_empty() && 922 "TailDuplicate called on block with multiple successors!"); 923 for (MachineBasicBlock *Succ : TailBB->successors()) 924 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ)); 925 926 // Update branches in pred to jump to tail's layout successor if needed. 927 if (ShouldUpdateTerminators) 928 PredBB->updateTerminator(TailBB->getNextNode()); 929 930 Changed = true; 931 ++NumTailDups; 932 } 933 934 // If TailBB was duplicated into all its predecessors except for the prior 935 // block, which falls through unconditionally, move the contents of this 936 // block into the prior block. 937 MachineBasicBlock *PrevBB = ForcedLayoutPred; 938 if (!PrevBB) 939 PrevBB = &*std::prev(TailBB->getIterator()); 940 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr; 941 SmallVector<MachineOperand, 4> PriorCond; 942 // This has to check PrevBB->succ_size() because EH edges are ignored by 943 // analyzeBranch. 944 if (PrevBB->succ_size() == 1 && 945 // Layout preds are not always CFG preds. Check. 946 *PrevBB->succ_begin() == TailBB && 947 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) && 948 PriorCond.empty() && 949 (!PriorTBB || PriorTBB == TailBB) && 950 TailBB->pred_size() == 1 && 951 !TailBB->hasAddressTaken()) { 952 LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB 953 << "From MBB: " << *TailBB); 954 // There may be a branch to the layout successor. This is unlikely but it 955 // happens. The correct thing to do is to remove the branch before 956 // duplicating the instructions in all cases. 957 bool RemovedBranches = TII->removeBranch(*PrevBB) != 0; 958 959 // If there are still tail instructions, abort the merge 960 if (PrevBB->getFirstTerminator() == PrevBB->end()) { 961 if (PreRegAlloc) { 962 DenseMap<Register, RegSubRegPair> LocalVRMap; 963 SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos; 964 MachineBasicBlock::iterator I = TailBB->begin(); 965 // Process PHI instructions first. 966 while (I != TailBB->end() && I->isPHI()) { 967 // Replace the uses of the def of the PHI with the register coming 968 // from PredBB. 969 MachineInstr *MI = &*I++; 970 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, 971 true); 972 } 973 974 // Now copy the non-PHI instructions. 975 while (I != TailBB->end()) { 976 // Replace def of virtual registers with new registers, and update 977 // uses with PHI source register or the new registers. 978 MachineInstr *MI = &*I++; 979 assert(!MI->isBundle() && "Not expecting bundles before regalloc!"); 980 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi); 981 MI->eraseFromParent(); 982 } 983 appendCopies(PrevBB, CopyInfos, Copies); 984 } else { 985 TII->removeBranch(*PrevBB); 986 // No PHIs to worry about, just splice the instructions over. 987 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end()); 988 } 989 PrevBB->removeSuccessor(PrevBB->succ_begin()); 990 assert(PrevBB->succ_empty()); 991 PrevBB->transferSuccessors(TailBB); 992 993 // Update branches in PrevBB based on Tail's layout successor. 994 if (ShouldUpdateTerminators) 995 PrevBB->updateTerminator(TailBB->getNextNode()); 996 997 TDBBs.push_back(PrevBB); 998 Changed = true; 999 } else { 1000 LLVM_DEBUG(dbgs() << "Abort merging blocks, the predecessor still " 1001 "contains terminator instructions"); 1002 // Return early if no changes were made 1003 if (!Changed) 1004 return RemovedBranches; 1005 } 1006 Changed |= RemovedBranches; 1007 } 1008 1009 // If this is after register allocation, there are no phis to fix. 1010 if (!PreRegAlloc) 1011 return Changed; 1012 1013 // If we made no changes so far, we are safe. 1014 if (!Changed) 1015 return Changed; 1016 1017 // Handle the nasty case in that we duplicated a block that is part of a loop 1018 // into some but not all of its predecessors. For example: 1019 // 1 -> 2 <-> 3 | 1020 // \ | 1021 // \---> rest | 1022 // if we duplicate 2 into 1 but not into 3, we end up with 1023 // 12 -> 3 <-> 2 -> rest | 1024 // \ / | 1025 // \----->-----/ | 1026 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced 1027 // with a phi in 3 (which now dominates 2). 1028 // What we do here is introduce a copy in 3 of the register defined by the 1029 // phi, just like when we are duplicating 2 into 3, but we don't copy any 1030 // real instructions or remove the 3 -> 2 edge from the phi in 2. 1031 for (MachineBasicBlock *PredBB : Preds) { 1032 if (is_contained(TDBBs, PredBB)) 1033 continue; 1034 1035 // EH edges 1036 if (PredBB->succ_size() != 1) 1037 continue; 1038 1039 DenseMap<Register, RegSubRegPair> LocalVRMap; 1040 SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos; 1041 MachineBasicBlock::iterator I = TailBB->begin(); 1042 // Process PHI instructions first. 1043 while (I != TailBB->end() && I->isPHI()) { 1044 // Replace the uses of the def of the PHI with the register coming 1045 // from PredBB. 1046 MachineInstr *MI = &*I++; 1047 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false); 1048 } 1049 appendCopies(PredBB, CopyInfos, Copies); 1050 } 1051 1052 return Changed; 1053 } 1054 1055 /// At the end of the block \p MBB generate COPY instructions between registers 1056 /// described by \p CopyInfos. Append resulting instructions to \p Copies. 1057 void TailDuplicator::appendCopies(MachineBasicBlock *MBB, 1058 SmallVectorImpl<std::pair<Register, RegSubRegPair>> &CopyInfos, 1059 SmallVectorImpl<MachineInstr*> &Copies) { 1060 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator(); 1061 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY); 1062 for (auto &CI : CopyInfos) { 1063 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first) 1064 .addReg(CI.second.Reg, 0, CI.second.SubReg); 1065 Copies.push_back(C); 1066 } 1067 } 1068 1069 /// Remove the specified dead machine basic block from the function, updating 1070 /// the CFG. 1071 void TailDuplicator::removeDeadBlock( 1072 MachineBasicBlock *MBB, 1073 function_ref<void(MachineBasicBlock *)> *RemovalCallback) { 1074 assert(MBB->pred_empty() && "MBB must be dead!"); 1075 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB); 1076 1077 MachineFunction *MF = MBB->getParent(); 1078 // Update the call site info. 1079 for (const MachineInstr &MI : *MBB) 1080 if (MI.shouldUpdateCallSiteInfo()) 1081 MF->eraseCallSiteInfo(&MI); 1082 1083 if (RemovalCallback) 1084 (*RemovalCallback)(MBB); 1085 1086 // Remove all successors. 1087 while (!MBB->succ_empty()) 1088 MBB->removeSuccessor(MBB->succ_end() - 1); 1089 1090 // Remove the block. 1091 MBB->eraseFromParent(); 1092 } 1093