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