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