1 //===- CriticalAntiDepBreaker.cpp - Anti-dep breaker ----------------------===// 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 file implements the CriticalAntiDepBreaker class, which 10 // implements register anti-dependence breaking along a blocks 11 // critical path during post-RA scheduler. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CriticalAntiDepBreaker.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/CodeGen/MachineBasicBlock.h" 20 #include "llvm/CodeGen/MachineFrameInfo.h" 21 #include "llvm/CodeGen/MachineFunction.h" 22 #include "llvm/CodeGen/MachineInstr.h" 23 #include "llvm/CodeGen/MachineOperand.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/RegisterClassInfo.h" 26 #include "llvm/CodeGen/ScheduleDAG.h" 27 #include "llvm/CodeGen/TargetInstrInfo.h" 28 #include "llvm/CodeGen/TargetRegisterInfo.h" 29 #include "llvm/CodeGen/TargetSubtargetInfo.h" 30 #include "llvm/MC/MCInstrDesc.h" 31 #include "llvm/MC/MCRegisterInfo.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include <cassert> 35 #include <utility> 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "post-RA-sched" 40 41 CriticalAntiDepBreaker::CriticalAntiDepBreaker(MachineFunction &MFi, 42 const RegisterClassInfo &RCI) 43 : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()), 44 TII(MF.getSubtarget().getInstrInfo()), 45 TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI), 46 Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0), 47 DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {} 48 49 CriticalAntiDepBreaker::~CriticalAntiDepBreaker() = default; 50 51 void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) { 52 const unsigned BBSize = BB->size(); 53 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) { 54 // Clear out the register class data. 55 Classes[i] = nullptr; 56 57 // Initialize the indices to indicate that no registers are live. 58 KillIndices[i] = ~0u; 59 DefIndices[i] = BBSize; 60 } 61 62 // Clear "do not change" set. 63 KeepRegs.reset(); 64 65 bool IsReturnBlock = BB->isReturnBlock(); 66 67 // Examine the live-in regs of all successors. 68 for (const MachineBasicBlock *Succ : BB->successors()) 69 for (const auto &LI : Succ->liveins()) { 70 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI) { 71 unsigned Reg = *AI; 72 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 73 KillIndices[Reg] = BBSize; 74 DefIndices[Reg] = ~0u; 75 } 76 } 77 78 // Mark live-out callee-saved registers. In a return block this is 79 // all callee-saved registers. In non-return this is any 80 // callee-saved register that is not saved in the prolog. 81 const MachineFrameInfo &MFI = MF.getFrameInfo(); 82 BitVector Pristine = MFI.getPristineRegs(MF); 83 for (const MCPhysReg *I = MF.getRegInfo().getCalleeSavedRegs(); *I; 84 ++I) { 85 unsigned Reg = *I; 86 if (!IsReturnBlock && !Pristine.test(Reg)) 87 continue; 88 for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) { 89 unsigned Reg = *AI; 90 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 91 KillIndices[Reg] = BBSize; 92 DefIndices[Reg] = ~0u; 93 } 94 } 95 } 96 97 void CriticalAntiDepBreaker::FinishBlock() { 98 RegRefs.clear(); 99 KeepRegs.reset(); 100 } 101 102 void CriticalAntiDepBreaker::Observe(MachineInstr &MI, unsigned Count, 103 unsigned InsertPosIndex) { 104 // Kill instructions can define registers but are really nops, and there might 105 // be a real definition earlier that needs to be paired with uses dominated by 106 // this kill. 107 108 // FIXME: It may be possible to remove the isKill() restriction once PR18663 109 // has been properly fixed. There can be value in processing kills as seen in 110 // the AggressiveAntiDepBreaker class. 111 if (MI.isDebugInstr() || MI.isKill()) 112 return; 113 assert(Count < InsertPosIndex && "Instruction index out of expected range!"); 114 115 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) { 116 if (KillIndices[Reg] != ~0u) { 117 // If Reg is currently live, then mark that it can't be renamed as 118 // we don't know the extent of its live-range anymore (now that it 119 // has been scheduled). 120 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 121 KillIndices[Reg] = Count; 122 } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) { 123 // Any register which was defined within the previous scheduling region 124 // may have been rescheduled and its lifetime may overlap with registers 125 // in ways not reflected in our current liveness state. For each such 126 // register, adjust the liveness state to be conservatively correct. 127 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 128 129 // Move the def index to the end of the previous region, to reflect 130 // that the def could theoretically have been scheduled at the end. 131 DefIndices[Reg] = InsertPosIndex; 132 } 133 } 134 135 PrescanInstruction(MI); 136 ScanInstruction(MI, Count); 137 } 138 139 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up 140 /// critical path. 141 static const SDep *CriticalPathStep(const SUnit *SU) { 142 const SDep *Next = nullptr; 143 unsigned NextDepth = 0; 144 // Find the predecessor edge with the greatest depth. 145 for (const SDep &P : SU->Preds) { 146 const SUnit *PredSU = P.getSUnit(); 147 unsigned PredLatency = P.getLatency(); 148 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency; 149 // In the case of a latency tie, prefer an anti-dependency edge over 150 // other types of edges. 151 if (NextDepth < PredTotalLatency || 152 (NextDepth == PredTotalLatency && P.getKind() == SDep::Anti)) { 153 NextDepth = PredTotalLatency; 154 Next = &P; 155 } 156 } 157 return Next; 158 } 159 160 void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr &MI) { 161 // It's not safe to change register allocation for source operands of 162 // instructions that have special allocation requirements. Also assume all 163 // registers used in a call must not be changed (ABI). 164 // FIXME: The issue with predicated instruction is more complex. We are being 165 // conservative here because the kill markers cannot be trusted after 166 // if-conversion: 167 // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14] 168 // ... 169 // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395] 170 // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12] 171 // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8) 172 // 173 // The first R6 kill is not really a kill since it's killed by a predicated 174 // instruction which may not be executed. The second R6 def may or may not 175 // re-define R6 so it's not safe to change it since the last R6 use cannot be 176 // changed. 177 bool Special = 178 MI.isCall() || MI.hasExtraSrcRegAllocReq() || TII->isPredicated(MI); 179 180 // Scan the register operands for this instruction and update 181 // Classes and RegRefs. 182 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 183 MachineOperand &MO = MI.getOperand(i); 184 if (!MO.isReg()) continue; 185 Register Reg = MO.getReg(); 186 if (Reg == 0) continue; 187 const TargetRegisterClass *NewRC = nullptr; 188 189 if (i < MI.getDesc().getNumOperands()) 190 NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF); 191 192 // For now, only allow the register to be changed if its register 193 // class is consistent across all uses. 194 if (!Classes[Reg] && NewRC) 195 Classes[Reg] = NewRC; 196 else if (!NewRC || Classes[Reg] != NewRC) 197 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 198 199 // Now check for aliases. 200 for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) { 201 // If an alias of the reg is used during the live range, give up. 202 // Note that this allows us to skip checking if AntiDepReg 203 // overlaps with any of the aliases, among other things. 204 unsigned AliasReg = *AI; 205 if (Classes[AliasReg]) { 206 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1); 207 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 208 } 209 } 210 211 // If we're still willing to consider this register, note the reference. 212 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1)) 213 RegRefs.insert(std::make_pair(Reg, &MO)); 214 215 if (MO.isUse() && Special) { 216 if (!KeepRegs.test(Reg)) { 217 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); 218 SubRegs.isValid(); ++SubRegs) 219 KeepRegs.set(*SubRegs); 220 } 221 } 222 } 223 224 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) { 225 const MachineOperand &MO = MI.getOperand(I); 226 if (!MO.isReg()) continue; 227 Register Reg = MO.getReg(); 228 if (!Reg.isValid()) 229 continue; 230 // If this reg is tied and live (Classes[Reg] is set to -1), we can't change 231 // it or any of its sub or super regs. We need to use KeepRegs to mark the 232 // reg because not all uses of the same reg within an instruction are 233 // necessarily tagged as tied. 234 // Example: an x86 "xor %eax, %eax" will have one source operand tied to the 235 // def register but not the second (see PR20020 for details). 236 // FIXME: can this check be relaxed to account for undef uses 237 // of a register? In the above 'xor' example, the uses of %eax are undef, so 238 // earlier instructions could still replace %eax even though the 'xor' 239 // itself can't be changed. 240 if (MI.isRegTiedToUseOperand(I) && 241 Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)) { 242 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); 243 SubRegs.isValid(); ++SubRegs) { 244 KeepRegs.set(*SubRegs); 245 } 246 for (MCSuperRegIterator SuperRegs(Reg, TRI); 247 SuperRegs.isValid(); ++SuperRegs) { 248 KeepRegs.set(*SuperRegs); 249 } 250 } 251 } 252 } 253 254 void CriticalAntiDepBreaker::ScanInstruction(MachineInstr &MI, unsigned Count) { 255 // Update liveness. 256 // Proceeding upwards, registers that are defed but not used in this 257 // instruction are now dead. 258 assert(!MI.isKill() && "Attempting to scan a kill instruction"); 259 260 if (!TII->isPredicated(MI)) { 261 // Predicated defs are modeled as read + write, i.e. similar to two 262 // address updates. 263 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 264 MachineOperand &MO = MI.getOperand(i); 265 266 if (MO.isRegMask()) { 267 auto ClobbersPhysRegAndSubRegs = [&](unsigned PhysReg) { 268 for (MCSubRegIterator SRI(PhysReg, TRI, true); SRI.isValid(); ++SRI) 269 if (!MO.clobbersPhysReg(*SRI)) 270 return false; 271 272 return true; 273 }; 274 275 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) { 276 if (ClobbersPhysRegAndSubRegs(i)) { 277 DefIndices[i] = Count; 278 KillIndices[i] = ~0u; 279 KeepRegs.reset(i); 280 Classes[i] = nullptr; 281 RegRefs.erase(i); 282 } 283 } 284 } 285 286 if (!MO.isReg()) continue; 287 Register Reg = MO.getReg(); 288 if (Reg == 0) continue; 289 if (!MO.isDef()) continue; 290 291 // Ignore two-addr defs. 292 if (MI.isRegTiedToUseOperand(i)) 293 continue; 294 295 // If we've already marked this reg as unchangeable, don't remove 296 // it or any of its subregs from KeepRegs. 297 bool Keep = KeepRegs.test(Reg); 298 299 // For the reg itself and all subregs: update the def to current; 300 // reset the kill state, any restrictions, and references. 301 for (MCSubRegIterator SRI(Reg, TRI, true); SRI.isValid(); ++SRI) { 302 unsigned SubregReg = *SRI; 303 DefIndices[SubregReg] = Count; 304 KillIndices[SubregReg] = ~0u; 305 Classes[SubregReg] = nullptr; 306 RegRefs.erase(SubregReg); 307 if (!Keep) 308 KeepRegs.reset(SubregReg); 309 } 310 // Conservatively mark super-registers as unusable. 311 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) 312 Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1); 313 } 314 } 315 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 316 MachineOperand &MO = MI.getOperand(i); 317 if (!MO.isReg()) continue; 318 Register Reg = MO.getReg(); 319 if (Reg == 0) continue; 320 if (!MO.isUse()) continue; 321 322 const TargetRegisterClass *NewRC = nullptr; 323 if (i < MI.getDesc().getNumOperands()) 324 NewRC = TII->getRegClass(MI.getDesc(), i, TRI, MF); 325 326 // For now, only allow the register to be changed if its register 327 // class is consistent across all uses. 328 if (!Classes[Reg] && NewRC) 329 Classes[Reg] = NewRC; 330 else if (!NewRC || Classes[Reg] != NewRC) 331 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1); 332 333 RegRefs.insert(std::make_pair(Reg, &MO)); 334 335 // It wasn't previously live but now it is, this is a kill. 336 // Repeat for all aliases. 337 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) { 338 unsigned AliasReg = *AI; 339 if (KillIndices[AliasReg] == ~0u) { 340 KillIndices[AliasReg] = Count; 341 DefIndices[AliasReg] = ~0u; 342 } 343 } 344 } 345 } 346 347 // Check all machine operands that reference the antidependent register and must 348 // be replaced by NewReg. Return true if any of their parent instructions may 349 // clobber the new register. 350 // 351 // Note: AntiDepReg may be referenced by a two-address instruction such that 352 // it's use operand is tied to a def operand. We guard against the case in which 353 // the two-address instruction also defines NewReg, as may happen with 354 // pre/postincrement loads. In this case, both the use and def operands are in 355 // RegRefs because the def is inserted by PrescanInstruction and not erased 356 // during ScanInstruction. So checking for an instruction with definitions of 357 // both NewReg and AntiDepReg covers it. 358 bool 359 CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin, 360 RegRefIter RegRefEnd, 361 unsigned NewReg) { 362 for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) { 363 MachineOperand *RefOper = I->second; 364 365 // Don't allow the instruction defining AntiDepReg to earlyclobber its 366 // operands, in case they may be assigned to NewReg. In this case antidep 367 // breaking must fail, but it's too rare to bother optimizing. 368 if (RefOper->isDef() && RefOper->isEarlyClobber()) 369 return true; 370 371 // Handle cases in which this instruction defines NewReg. 372 MachineInstr *MI = RefOper->getParent(); 373 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 374 const MachineOperand &CheckOper = MI->getOperand(i); 375 376 if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg)) 377 return true; 378 379 if (!CheckOper.isReg() || !CheckOper.isDef() || 380 CheckOper.getReg() != NewReg) 381 continue; 382 383 // Don't allow the instruction to define NewReg and AntiDepReg. 384 // When AntiDepReg is renamed it will be an illegal op. 385 if (RefOper->isDef()) 386 return true; 387 388 // Don't allow an instruction using AntiDepReg to be earlyclobbered by 389 // NewReg. 390 if (CheckOper.isEarlyClobber()) 391 return true; 392 393 // Don't allow inline asm to define NewReg at all. Who knows what it's 394 // doing with it. 395 if (MI->isInlineAsm()) 396 return true; 397 } 398 } 399 return false; 400 } 401 402 unsigned CriticalAntiDepBreaker:: 403 findSuitableFreeRegister(RegRefIter RegRefBegin, 404 RegRefIter RegRefEnd, 405 unsigned AntiDepReg, 406 unsigned LastNewReg, 407 const TargetRegisterClass *RC, 408 SmallVectorImpl<unsigned> &Forbid) { 409 ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC); 410 for (unsigned i = 0; i != Order.size(); ++i) { 411 unsigned NewReg = Order[i]; 412 // Don't replace a register with itself. 413 if (NewReg == AntiDepReg) continue; 414 // Don't replace a register with one that was recently used to repair 415 // an anti-dependence with this AntiDepReg, because that would 416 // re-introduce that anti-dependence. 417 if (NewReg == LastNewReg) continue; 418 // If any instructions that define AntiDepReg also define the NewReg, it's 419 // not suitable. For example, Instruction with multiple definitions can 420 // result in this condition. 421 if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue; 422 // If NewReg is dead and NewReg's most recent def is not before 423 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg. 424 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) 425 && "Kill and Def maps aren't consistent for AntiDepReg!"); 426 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) 427 && "Kill and Def maps aren't consistent for NewReg!"); 428 if (KillIndices[NewReg] != ~0u || 429 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) || 430 KillIndices[AntiDepReg] > DefIndices[NewReg]) 431 continue; 432 // If NewReg overlaps any of the forbidden registers, we can't use it. 433 bool Forbidden = false; 434 for (unsigned R : Forbid) 435 if (TRI->regsOverlap(NewReg, R)) { 436 Forbidden = true; 437 break; 438 } 439 if (Forbidden) continue; 440 return NewReg; 441 } 442 443 // No registers are free and available! 444 return 0; 445 } 446 447 unsigned CriticalAntiDepBreaker:: 448 BreakAntiDependencies(const std::vector<SUnit> &SUnits, 449 MachineBasicBlock::iterator Begin, 450 MachineBasicBlock::iterator End, 451 unsigned InsertPosIndex, 452 DbgValueVector &DbgValues) { 453 // The code below assumes that there is at least one instruction, 454 // so just duck out immediately if the block is empty. 455 if (SUnits.empty()) return 0; 456 457 // Keep a map of the MachineInstr*'s back to the SUnit representing them. 458 // This is used for updating debug information. 459 // 460 // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap 461 DenseMap<MachineInstr *, const SUnit *> MISUnitMap; 462 463 // Find the node at the bottom of the critical path. 464 const SUnit *Max = nullptr; 465 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) { 466 const SUnit *SU = &SUnits[i]; 467 MISUnitMap[SU->getInstr()] = SU; 468 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency) 469 Max = SU; 470 } 471 assert(Max && "Failed to find bottom of the critical path"); 472 473 #ifndef NDEBUG 474 { 475 LLVM_DEBUG(dbgs() << "Critical path has total latency " 476 << (Max->getDepth() + Max->Latency) << "\n"); 477 LLVM_DEBUG(dbgs() << "Available regs:"); 478 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) { 479 if (KillIndices[Reg] == ~0u) 480 LLVM_DEBUG(dbgs() << " " << printReg(Reg, TRI)); 481 } 482 LLVM_DEBUG(dbgs() << '\n'); 483 } 484 #endif 485 486 // Track progress along the critical path through the SUnit graph as we walk 487 // the instructions. 488 const SUnit *CriticalPathSU = Max; 489 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr(); 490 491 // Consider this pattern: 492 // A = ... 493 // ... = A 494 // A = ... 495 // ... = A 496 // A = ... 497 // ... = A 498 // A = ... 499 // ... = A 500 // There are three anti-dependencies here, and without special care, 501 // we'd break all of them using the same register: 502 // A = ... 503 // ... = A 504 // B = ... 505 // ... = B 506 // B = ... 507 // ... = B 508 // B = ... 509 // ... = B 510 // because at each anti-dependence, B is the first register that 511 // isn't A which is free. This re-introduces anti-dependencies 512 // at all but one of the original anti-dependencies that we were 513 // trying to break. To avoid this, keep track of the most recent 514 // register that each register was replaced with, avoid 515 // using it to repair an anti-dependence on the same register. 516 // This lets us produce this: 517 // A = ... 518 // ... = A 519 // B = ... 520 // ... = B 521 // C = ... 522 // ... = C 523 // B = ... 524 // ... = B 525 // This still has an anti-dependence on B, but at least it isn't on the 526 // original critical path. 527 // 528 // TODO: If we tracked more than one register here, we could potentially 529 // fix that remaining critical edge too. This is a little more involved, 530 // because unlike the most recent register, less recent registers should 531 // still be considered, though only if no other registers are available. 532 std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0); 533 534 // Attempt to break anti-dependence edges on the critical path. Walk the 535 // instructions from the bottom up, tracking information about liveness 536 // as we go to help determine which registers are available. 537 unsigned Broken = 0; 538 unsigned Count = InsertPosIndex - 1; 539 for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) { 540 MachineInstr &MI = *--I; 541 // Kill instructions can define registers but are really nops, and there 542 // might be a real definition earlier that needs to be paired with uses 543 // dominated by this kill. 544 545 // FIXME: It may be possible to remove the isKill() restriction once PR18663 546 // has been properly fixed. There can be value in processing kills as seen 547 // in the AggressiveAntiDepBreaker class. 548 if (MI.isDebugInstr() || MI.isKill()) 549 continue; 550 551 // Check if this instruction has a dependence on the critical path that 552 // is an anti-dependence that we may be able to break. If it is, set 553 // AntiDepReg to the non-zero register associated with the anti-dependence. 554 // 555 // We limit our attention to the critical path as a heuristic to avoid 556 // breaking anti-dependence edges that aren't going to significantly 557 // impact the overall schedule. There are a limited number of registers 558 // and we want to save them for the important edges. 559 // 560 // TODO: Instructions with multiple defs could have multiple 561 // anti-dependencies. The current code here only knows how to break one 562 // edge per instruction. Note that we'd have to be able to break all of 563 // the anti-dependencies in an instruction in order to be effective. 564 unsigned AntiDepReg = 0; 565 if (&MI == CriticalPathMI) { 566 if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) { 567 const SUnit *NextSU = Edge->getSUnit(); 568 569 // Only consider anti-dependence edges. 570 if (Edge->getKind() == SDep::Anti) { 571 AntiDepReg = Edge->getReg(); 572 assert(AntiDepReg != 0 && "Anti-dependence on reg0?"); 573 if (!MRI.isAllocatable(AntiDepReg)) 574 // Don't break anti-dependencies on non-allocatable registers. 575 AntiDepReg = 0; 576 else if (KeepRegs.test(AntiDepReg)) 577 // Don't break anti-dependencies if a use down below requires 578 // this exact register. 579 AntiDepReg = 0; 580 else { 581 // If the SUnit has other dependencies on the SUnit that it 582 // anti-depends on, don't bother breaking the anti-dependency 583 // since those edges would prevent such units from being 584 // scheduled past each other regardless. 585 // 586 // Also, if there are dependencies on other SUnits with the 587 // same register as the anti-dependency, don't attempt to 588 // break it. 589 for (const SDep &P : CriticalPathSU->Preds) 590 if (P.getSUnit() == NextSU 591 ? (P.getKind() != SDep::Anti || P.getReg() != AntiDepReg) 592 : (P.getKind() == SDep::Data && 593 P.getReg() == AntiDepReg)) { 594 AntiDepReg = 0; 595 break; 596 } 597 } 598 } 599 CriticalPathSU = NextSU; 600 CriticalPathMI = CriticalPathSU->getInstr(); 601 } else { 602 // We've reached the end of the critical path. 603 CriticalPathSU = nullptr; 604 CriticalPathMI = nullptr; 605 } 606 } 607 608 PrescanInstruction(MI); 609 610 SmallVector<unsigned, 2> ForbidRegs; 611 612 // If MI's defs have a special allocation requirement, don't allow 613 // any def registers to be changed. Also assume all registers 614 // defined in a call must not be changed (ABI). 615 if (MI.isCall() || MI.hasExtraDefRegAllocReq() || TII->isPredicated(MI)) 616 // If this instruction's defs have special allocation requirement, don't 617 // break this anti-dependency. 618 AntiDepReg = 0; 619 else if (AntiDepReg) { 620 // If this instruction has a use of AntiDepReg, breaking it 621 // is invalid. If the instruction defines other registers, 622 // save a list of them so that we don't pick a new register 623 // that overlaps any of them. 624 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 625 MachineOperand &MO = MI.getOperand(i); 626 if (!MO.isReg()) continue; 627 Register Reg = MO.getReg(); 628 if (Reg == 0) continue; 629 if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) { 630 AntiDepReg = 0; 631 break; 632 } 633 if (MO.isDef() && Reg != AntiDepReg) 634 ForbidRegs.push_back(Reg); 635 } 636 } 637 638 // Determine AntiDepReg's register class, if it is live and is 639 // consistently used within a single class. 640 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] 641 : nullptr; 642 assert((AntiDepReg == 0 || RC != nullptr) && 643 "Register should be live if it's causing an anti-dependence!"); 644 if (RC == reinterpret_cast<TargetRegisterClass *>(-1)) 645 AntiDepReg = 0; 646 647 // Look for a suitable register to use to break the anti-dependence. 648 // 649 // TODO: Instead of picking the first free register, consider which might 650 // be the best. 651 if (AntiDepReg != 0) { 652 std::pair<std::multimap<unsigned, MachineOperand *>::iterator, 653 std::multimap<unsigned, MachineOperand *>::iterator> 654 Range = RegRefs.equal_range(AntiDepReg); 655 if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second, 656 AntiDepReg, 657 LastNewReg[AntiDepReg], 658 RC, ForbidRegs)) { 659 LLVM_DEBUG(dbgs() << "Breaking anti-dependence edge on " 660 << printReg(AntiDepReg, TRI) << " with " 661 << RegRefs.count(AntiDepReg) << " references" 662 << " using " << printReg(NewReg, TRI) << "!\n"); 663 664 // Update the references to the old register to refer to the new 665 // register. 666 for (std::multimap<unsigned, MachineOperand *>::iterator 667 Q = Range.first, QE = Range.second; Q != QE; ++Q) { 668 Q->second->setReg(NewReg); 669 // If the SU for the instruction being updated has debug information 670 // related to the anti-dependency register, make sure to update that 671 // as well. 672 const SUnit *SU = MISUnitMap[Q->second->getParent()]; 673 if (!SU) continue; 674 UpdateDbgValues(DbgValues, Q->second->getParent(), 675 AntiDepReg, NewReg); 676 } 677 678 // We just went back in time and modified history; the 679 // liveness information for the anti-dependence reg is now 680 // inconsistent. Set the state as if it were dead. 681 Classes[NewReg] = Classes[AntiDepReg]; 682 DefIndices[NewReg] = DefIndices[AntiDepReg]; 683 KillIndices[NewReg] = KillIndices[AntiDepReg]; 684 assert(((KillIndices[NewReg] == ~0u) != 685 (DefIndices[NewReg] == ~0u)) && 686 "Kill and Def maps aren't consistent for NewReg!"); 687 688 Classes[AntiDepReg] = nullptr; 689 DefIndices[AntiDepReg] = KillIndices[AntiDepReg]; 690 KillIndices[AntiDepReg] = ~0u; 691 assert(((KillIndices[AntiDepReg] == ~0u) != 692 (DefIndices[AntiDepReg] == ~0u)) && 693 "Kill and Def maps aren't consistent for AntiDepReg!"); 694 695 RegRefs.erase(AntiDepReg); 696 LastNewReg[AntiDepReg] = NewReg; 697 ++Broken; 698 } 699 } 700 701 ScanInstruction(MI, Count); 702 } 703 704 return Broken; 705 } 706 707 AntiDepBreaker * 708 llvm::createCriticalAntiDepBreaker(MachineFunction &MFi, 709 const RegisterClassInfo &RCI) { 710 return new CriticalAntiDepBreaker(MFi, RCI); 711 } 712