1 //===-- RegisterPressure.cpp - Dynamic Register Pressure ------------------===// 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 file implements the RegisterPressure class which can be used to track 11 // MachineInstr level register pressure. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/RegisterPressure.h" 16 #include "llvm/CodeGen/LiveInterval.h" 17 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 18 #include "llvm/CodeGen/MachineRegisterInfo.h" 19 #include "llvm/CodeGen/RegisterClassInfo.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/raw_ostream.h" 22 23 using namespace llvm; 24 25 /// Increase pressure for each pressure set provided by TargetRegisterInfo. 26 static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure, 27 PSetIterator PSetI) { 28 unsigned Weight = PSetI.getWeight(); 29 for (; PSetI.isValid(); ++PSetI) 30 CurrSetPressure[*PSetI] += Weight; 31 } 32 33 /// Decrease pressure for each pressure set provided by TargetRegisterInfo. 34 static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure, 35 PSetIterator PSetI) { 36 unsigned Weight = PSetI.getWeight(); 37 for (; PSetI.isValid(); ++PSetI) { 38 assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow"); 39 CurrSetPressure[*PSetI] -= Weight; 40 } 41 } 42 43 LLVM_DUMP_METHOD 44 void llvm::dumpRegSetPressure(ArrayRef<unsigned> SetPressure, 45 const TargetRegisterInfo *TRI) { 46 bool Empty = true; 47 for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) { 48 if (SetPressure[i] != 0) { 49 dbgs() << TRI->getRegPressureSetName(i) << "=" << SetPressure[i] << '\n'; 50 Empty = false; 51 } 52 } 53 if (Empty) 54 dbgs() << "\n"; 55 } 56 57 LLVM_DUMP_METHOD 58 void RegisterPressure::dump(const TargetRegisterInfo *TRI) const { 59 dbgs() << "Max Pressure: "; 60 dumpRegSetPressure(MaxSetPressure, TRI); 61 dbgs() << "Live In: "; 62 for (unsigned Reg : LiveInRegs) 63 dbgs() << PrintVRegOrUnit(Reg, TRI) << " "; 64 dbgs() << '\n'; 65 dbgs() << "Live Out: "; 66 for (unsigned Reg : LiveOutRegs) 67 dbgs() << PrintVRegOrUnit(Reg, TRI) << " "; 68 dbgs() << '\n'; 69 } 70 71 LLVM_DUMP_METHOD 72 void RegPressureTracker::dump() const { 73 if (!isTopClosed() || !isBottomClosed()) { 74 dbgs() << "Curr Pressure: "; 75 dumpRegSetPressure(CurrSetPressure, TRI); 76 } 77 P.dump(TRI); 78 } 79 80 void PressureDiff::dump(const TargetRegisterInfo &TRI) const { 81 const char *sep = ""; 82 for (const PressureChange &Change : *this) { 83 if (!Change.isValid()) 84 break; 85 dbgs() << sep << TRI.getRegPressureSetName(Change.getPSet()) 86 << " " << Change.getUnitInc(); 87 sep = " "; 88 } 89 dbgs() << '\n'; 90 } 91 92 /// Increase the current pressure as impacted by these registers and bump 93 /// the high water mark if needed. 94 void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) { 95 for (unsigned RegUnit : RegUnits) { 96 PSetIterator PSetI = MRI->getPressureSets(RegUnit); 97 unsigned Weight = PSetI.getWeight(); 98 for (; PSetI.isValid(); ++PSetI) { 99 CurrSetPressure[*PSetI] += Weight; 100 P.MaxSetPressure[*PSetI] = 101 std::max(P.MaxSetPressure[*PSetI], CurrSetPressure[*PSetI]); 102 } 103 } 104 } 105 106 /// Simply decrease the current pressure as impacted by these registers. 107 void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) { 108 for (unsigned RegUnit : RegUnits) 109 decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnit)); 110 } 111 112 /// Clear the result so it can be used for another round of pressure tracking. 113 void IntervalPressure::reset() { 114 TopIdx = BottomIdx = SlotIndex(); 115 MaxSetPressure.clear(); 116 LiveInRegs.clear(); 117 LiveOutRegs.clear(); 118 } 119 120 /// Clear the result so it can be used for another round of pressure tracking. 121 void RegionPressure::reset() { 122 TopPos = BottomPos = MachineBasicBlock::const_iterator(); 123 MaxSetPressure.clear(); 124 LiveInRegs.clear(); 125 LiveOutRegs.clear(); 126 } 127 128 /// If the current top is not less than or equal to the next index, open it. 129 /// We happen to need the SlotIndex for the next top for pressure update. 130 void IntervalPressure::openTop(SlotIndex NextTop) { 131 if (TopIdx <= NextTop) 132 return; 133 TopIdx = SlotIndex(); 134 LiveInRegs.clear(); 135 } 136 137 /// If the current top is the previous instruction (before receding), open it. 138 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) { 139 if (TopPos != PrevTop) 140 return; 141 TopPos = MachineBasicBlock::const_iterator(); 142 LiveInRegs.clear(); 143 } 144 145 /// If the current bottom is not greater than the previous index, open it. 146 void IntervalPressure::openBottom(SlotIndex PrevBottom) { 147 if (BottomIdx > PrevBottom) 148 return; 149 BottomIdx = SlotIndex(); 150 LiveInRegs.clear(); 151 } 152 153 /// If the current bottom is the previous instr (before advancing), open it. 154 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) { 155 if (BottomPos != PrevBottom) 156 return; 157 BottomPos = MachineBasicBlock::const_iterator(); 158 LiveInRegs.clear(); 159 } 160 161 void LiveRegSet::init(const MachineRegisterInfo &MRI) { 162 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 163 unsigned NumRegUnits = TRI.getNumRegs(); 164 unsigned NumVirtRegs = MRI.getNumVirtRegs(); 165 Regs.setUniverse(NumRegUnits + NumVirtRegs); 166 this->NumRegUnits = NumRegUnits; 167 } 168 169 void LiveRegSet::clear() { 170 Regs.clear(); 171 } 172 173 static const LiveRange *getLiveRange(const LiveIntervals &LIS, unsigned Reg) { 174 if (TargetRegisterInfo::isVirtualRegister(Reg)) 175 return &LIS.getInterval(Reg); 176 return LIS.getCachedRegUnit(Reg); 177 } 178 179 void RegPressureTracker::reset() { 180 MBB = nullptr; 181 LIS = nullptr; 182 183 CurrSetPressure.clear(); 184 LiveThruPressure.clear(); 185 P.MaxSetPressure.clear(); 186 187 if (RequireIntervals) 188 static_cast<IntervalPressure&>(P).reset(); 189 else 190 static_cast<RegionPressure&>(P).reset(); 191 192 LiveRegs.clear(); 193 UntiedDefs.clear(); 194 } 195 196 /// Setup the RegPressureTracker. 197 /// 198 /// TODO: Add support for pressure without LiveIntervals. 199 void RegPressureTracker::init(const MachineFunction *mf, 200 const RegisterClassInfo *rci, 201 const LiveIntervals *lis, 202 const MachineBasicBlock *mbb, 203 MachineBasicBlock::const_iterator pos, 204 bool ShouldTrackUntiedDefs) 205 { 206 reset(); 207 208 MF = mf; 209 TRI = MF->getSubtarget().getRegisterInfo(); 210 RCI = rci; 211 MRI = &MF->getRegInfo(); 212 MBB = mbb; 213 TrackUntiedDefs = ShouldTrackUntiedDefs; 214 215 if (RequireIntervals) { 216 assert(lis && "IntervalPressure requires LiveIntervals"); 217 LIS = lis; 218 } 219 220 CurrPos = pos; 221 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0); 222 223 P.MaxSetPressure = CurrSetPressure; 224 225 LiveRegs.init(*MRI); 226 if (TrackUntiedDefs) 227 UntiedDefs.setUniverse(MRI->getNumVirtRegs()); 228 } 229 230 /// Does this pressure result have a valid top position and live ins. 231 bool RegPressureTracker::isTopClosed() const { 232 if (RequireIntervals) 233 return static_cast<IntervalPressure&>(P).TopIdx.isValid(); 234 return (static_cast<RegionPressure&>(P).TopPos == 235 MachineBasicBlock::const_iterator()); 236 } 237 238 /// Does this pressure result have a valid bottom position and live outs. 239 bool RegPressureTracker::isBottomClosed() const { 240 if (RequireIntervals) 241 return static_cast<IntervalPressure&>(P).BottomIdx.isValid(); 242 return (static_cast<RegionPressure&>(P).BottomPos == 243 MachineBasicBlock::const_iterator()); 244 } 245 246 247 SlotIndex RegPressureTracker::getCurrSlot() const { 248 MachineBasicBlock::const_iterator IdxPos = CurrPos; 249 while (IdxPos != MBB->end() && IdxPos->isDebugValue()) 250 ++IdxPos; 251 if (IdxPos == MBB->end()) 252 return LIS->getMBBEndIdx(MBB); 253 return LIS->getInstructionIndex(IdxPos).getRegSlot(); 254 } 255 256 /// Set the boundary for the top of the region and summarize live ins. 257 void RegPressureTracker::closeTop() { 258 if (RequireIntervals) 259 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot(); 260 else 261 static_cast<RegionPressure&>(P).TopPos = CurrPos; 262 263 assert(P.LiveInRegs.empty() && "inconsistent max pressure result"); 264 P.LiveInRegs.reserve(LiveRegs.size()); 265 LiveRegs.appendTo(P.LiveInRegs); 266 } 267 268 /// Set the boundary for the bottom of the region and summarize live outs. 269 void RegPressureTracker::closeBottom() { 270 if (RequireIntervals) 271 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot(); 272 else 273 static_cast<RegionPressure&>(P).BottomPos = CurrPos; 274 275 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result"); 276 P.LiveOutRegs.reserve(LiveRegs.size()); 277 LiveRegs.appendTo(P.LiveOutRegs); 278 } 279 280 /// Finalize the region boundaries and record live ins and live outs. 281 void RegPressureTracker::closeRegion() { 282 if (!isTopClosed() && !isBottomClosed()) { 283 assert(LiveRegs.size() == 0 && "no region boundary"); 284 return; 285 } 286 if (!isBottomClosed()) 287 closeBottom(); 288 else if (!isTopClosed()) 289 closeTop(); 290 // If both top and bottom are closed, do nothing. 291 } 292 293 /// The register tracker is unaware of global liveness so ignores normal 294 /// live-thru ranges. However, two-address or coalesced chains can also lead 295 /// to live ranges with no holes. Count these to inform heuristics that we 296 /// can never drop below this pressure. 297 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) { 298 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0); 299 assert(isBottomClosed() && "need bottom-up tracking to intialize."); 300 for (unsigned Reg : P.LiveOutRegs) { 301 if (TargetRegisterInfo::isVirtualRegister(Reg) 302 && !RPTracker.hasUntiedDef(Reg)) { 303 increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg)); 304 } 305 } 306 } 307 308 /// \brief Convenient wrapper for checking membership in RegisterOperands. 309 /// (std::count() doesn't have an early exit). 310 static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) { 311 return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end(); 312 } 313 314 namespace { 315 316 /// Collect this instruction's unique uses and defs into SmallVectors for 317 /// processing defs and uses in order. 318 /// 319 /// FIXME: always ignore tied opers 320 class RegisterOperandsCollector { 321 RegisterOperands &RegOpers; 322 const TargetRegisterInfo &TRI; 323 const MachineRegisterInfo &MRI; 324 bool IgnoreDead; 325 326 RegisterOperandsCollector(RegisterOperands &RegOpers, 327 const TargetRegisterInfo &TRI, 328 const MachineRegisterInfo &MRI, 329 bool IgnoreDead) 330 : RegOpers(RegOpers), TRI(TRI), MRI(MRI), IgnoreDead(IgnoreDead) {} 331 332 void collectInstr(const MachineInstr &MI) const { 333 for (ConstMIBundleOperands OperI(&MI); OperI.isValid(); ++OperI) 334 collectOperand(*OperI); 335 336 // Remove redundant physreg dead defs. 337 SmallVectorImpl<unsigned>::iterator I = 338 std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(), 339 std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs)); 340 RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end()); 341 } 342 343 /// Push this operand's register onto the correct vectors. 344 void collectOperand(const MachineOperand &MO) const { 345 if (!MO.isReg() || !MO.getReg()) 346 return; 347 unsigned Reg = MO.getReg(); 348 if (MO.readsReg()) 349 pushRegUnits(Reg, RegOpers.Uses); 350 if (MO.isDef()) { 351 if (MO.isDead()) { 352 if (!IgnoreDead) 353 pushRegUnits(Reg, RegOpers.DeadDefs); 354 } else 355 pushRegUnits(Reg, RegOpers.Defs); 356 } 357 } 358 359 void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) const { 360 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 361 if (containsReg(RegUnits, Reg)) 362 return; 363 RegUnits.push_back(Reg); 364 } else if (MRI.isAllocatable(Reg)) { 365 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) { 366 if (containsReg(RegUnits, *Units)) 367 continue; 368 RegUnits.push_back(*Units); 369 } 370 } 371 } 372 373 friend class llvm::RegisterOperands; 374 }; 375 376 } // namespace 377 378 void RegisterOperands::collect(const MachineInstr &MI, 379 const TargetRegisterInfo &TRI, 380 const MachineRegisterInfo &MRI, 381 bool IgnoreDead) { 382 RegisterOperandsCollector Collector(*this, TRI, MRI, IgnoreDead); 383 Collector.collectInstr(MI); 384 } 385 386 void RegisterOperands::detectDeadDefs(const MachineInstr &MI, 387 const LiveIntervals &LIS) { 388 SlotIndex SlotIdx = LIS.getInstructionIndex(&MI); 389 for (SmallVectorImpl<unsigned>::iterator RI = Defs.begin(); 390 RI != Defs.end(); /*empty*/) { 391 unsigned Reg = *RI; 392 const LiveRange *LR = getLiveRange(LIS, Reg); 393 if (LR != nullptr) { 394 LiveQueryResult LRQ = LR->Query(SlotIdx); 395 if (LRQ.isDeadDef()) { 396 // LiveIntervals knows this is a dead even though it's MachineOperand is 397 // not flagged as such. 398 DeadDefs.push_back(Reg); 399 RI = Defs.erase(RI); 400 continue; 401 } 402 } 403 ++RI; 404 } 405 } 406 407 /// Initialize an array of N PressureDiffs. 408 void PressureDiffs::init(unsigned N) { 409 Size = N; 410 if (N <= Max) { 411 memset(PDiffArray, 0, N * sizeof(PressureDiff)); 412 return; 413 } 414 Max = Size; 415 free(PDiffArray); 416 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff))); 417 } 418 419 void PressureDiffs::addInstruction(unsigned Idx, 420 const RegisterOperands &RegOpers, 421 const MachineRegisterInfo &MRI) { 422 PressureDiff &PDiff = (*this)[Idx]; 423 assert(!PDiff.begin()->isValid() && "stale PDiff"); 424 for (unsigned Reg : RegOpers.Defs) 425 PDiff.addPressureChange(Reg, true, &MRI); 426 427 for (unsigned Reg : RegOpers.Uses) 428 PDiff.addPressureChange(Reg, false, &MRI); 429 } 430 431 /// Add a change in pressure to the pressure diff of a given instruction. 432 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec, 433 const MachineRegisterInfo *MRI) { 434 PSetIterator PSetI = MRI->getPressureSets(RegUnit); 435 int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight(); 436 for (; PSetI.isValid(); ++PSetI) { 437 // Find an existing entry in the pressure diff for this PSet. 438 PressureDiff::iterator I = nonconst_begin(), E = nonconst_end(); 439 for (; I != E && I->isValid(); ++I) { 440 if (I->getPSet() >= *PSetI) 441 break; 442 } 443 // If all pressure sets are more constrained, skip the remaining PSets. 444 if (I == E) 445 break; 446 // Insert this PressureChange. 447 if (!I->isValid() || I->getPSet() != *PSetI) { 448 PressureChange PTmp = PressureChange(*PSetI); 449 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J) 450 std::swap(*J, PTmp); 451 } 452 // Update the units for this pressure set. 453 unsigned NewUnitInc = I->getUnitInc() + Weight; 454 if (NewUnitInc != 0) { 455 I->setUnitInc(NewUnitInc); 456 } else { 457 // Remove entry 458 PressureDiff::iterator J; 459 for (J = std::next(I); J != E && J->isValid(); ++J, ++I) 460 *I = *J; 461 if (J != E) 462 *I = *J; 463 } 464 } 465 } 466 467 /// Force liveness of registers. 468 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) { 469 for (unsigned Reg : Regs) { 470 if (LiveRegs.insert(Reg)) 471 increaseRegPressure(Reg); 472 } 473 } 474 475 /// Add Reg to the live in set and increase max pressure. 476 void RegPressureTracker::discoverLiveIn(unsigned Reg) { 477 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice"); 478 if (containsReg(P.LiveInRegs, Reg)) 479 return; 480 481 // At live in discovery, unconditionally increase the high water mark. 482 P.LiveInRegs.push_back(Reg); 483 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg)); 484 } 485 486 /// Add Reg to the live out set and increase max pressure. 487 void RegPressureTracker::discoverLiveOut(unsigned Reg) { 488 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice"); 489 if (containsReg(P.LiveOutRegs, Reg)) 490 return; 491 492 // At live out discovery, unconditionally increase the high water mark. 493 P.LiveOutRegs.push_back(Reg); 494 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg)); 495 } 496 497 /// Recede across the previous instruction. If LiveUses is provided, record any 498 /// RegUnits that are made live by the current instruction's uses. This includes 499 /// registers that are both defined and used by the instruction. If a pressure 500 /// difference pointer is provided record the changes is pressure caused by this 501 /// instruction independent of liveness. 502 void RegPressureTracker::recede(const RegisterOperands &RegOpers, 503 SmallVectorImpl<unsigned> *LiveUses) { 504 assert(!CurrPos->isDebugValue()); 505 506 // Boost pressure for all dead defs together. 507 increaseRegPressure(RegOpers.DeadDefs); 508 decreaseRegPressure(RegOpers.DeadDefs); 509 510 // Kill liveness at live defs. 511 // TODO: consider earlyclobbers? 512 for (unsigned Reg : RegOpers.Defs) { 513 if (LiveRegs.erase(Reg)) 514 decreaseRegPressure(Reg); 515 else 516 discoverLiveOut(Reg); 517 } 518 519 SlotIndex SlotIdx; 520 if (RequireIntervals) 521 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot(); 522 523 // Generate liveness for uses. 524 for (unsigned Reg : RegOpers.Uses) { 525 if (!LiveRegs.contains(Reg)) { 526 // Adjust liveouts if LiveIntervals are available. 527 if (RequireIntervals) { 528 const LiveRange *LR = getLiveRange(*LIS, Reg); 529 if (LR) { 530 LiveQueryResult LRQ = LR->Query(SlotIdx); 531 if (!LRQ.isKill() && !LRQ.valueDefined()) 532 discoverLiveOut(Reg); 533 } 534 } 535 increaseRegPressure(Reg); 536 LiveRegs.insert(Reg); 537 if (LiveUses && !containsReg(*LiveUses, Reg)) 538 LiveUses->push_back(Reg); 539 } 540 } 541 if (TrackUntiedDefs) { 542 for (unsigned Reg : RegOpers.Defs) { 543 if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg)) 544 UntiedDefs.insert(Reg); 545 } 546 } 547 } 548 549 void RegPressureTracker::recedeSkipDebugValues() { 550 assert(CurrPos != MBB->begin()); 551 if (!isBottomClosed()) 552 closeBottom(); 553 554 // Open the top of the region using block iterators. 555 if (!RequireIntervals && isTopClosed()) 556 static_cast<RegionPressure&>(P).openTop(CurrPos); 557 558 // Find the previous instruction. 559 do 560 --CurrPos; 561 while (CurrPos != MBB->begin() && CurrPos->isDebugValue()); 562 563 SlotIndex SlotIdx; 564 if (RequireIntervals) 565 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot(); 566 567 // Open the top of the region using slot indexes. 568 if (RequireIntervals && isTopClosed()) 569 static_cast<IntervalPressure&>(P).openTop(SlotIdx); 570 } 571 572 void RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses) { 573 recedeSkipDebugValues(); 574 575 const MachineInstr &MI = *CurrPos; 576 RegisterOperands RegOpers; 577 RegOpers.collect(MI, *TRI, *MRI); 578 if (RequireIntervals) 579 RegOpers.detectDeadDefs(MI, *LIS); 580 581 recede(RegOpers, LiveUses); 582 } 583 584 /// Advance across the current instruction. 585 void RegPressureTracker::advance() { 586 assert(!TrackUntiedDefs && "unsupported mode"); 587 588 assert(CurrPos != MBB->end()); 589 if (!isTopClosed()) 590 closeTop(); 591 592 SlotIndex SlotIdx; 593 if (RequireIntervals) 594 SlotIdx = getCurrSlot(); 595 596 // Open the bottom of the region using slot indexes. 597 if (isBottomClosed()) { 598 if (RequireIntervals) 599 static_cast<IntervalPressure&>(P).openBottom(SlotIdx); 600 else 601 static_cast<RegionPressure&>(P).openBottom(CurrPos); 602 } 603 604 RegisterOperands RegOpers; 605 RegOpers.collect(*CurrPos, *TRI, *MRI); 606 607 for (unsigned Reg : RegOpers.Uses) { 608 // Discover live-ins. 609 bool isLive = LiveRegs.contains(Reg); 610 if (!isLive) 611 discoverLiveIn(Reg); 612 // Kill liveness at last uses. 613 bool lastUse = false; 614 if (RequireIntervals) { 615 const LiveRange *LR = getLiveRange(*LIS, Reg); 616 lastUse = LR && LR->Query(SlotIdx).isKill(); 617 } else { 618 // Allocatable physregs are always single-use before register rewriting. 619 lastUse = !TargetRegisterInfo::isVirtualRegister(Reg); 620 } 621 if (lastUse && isLive) { 622 LiveRegs.erase(Reg); 623 decreaseRegPressure(Reg); 624 } else if (!lastUse && !isLive) 625 increaseRegPressure(Reg); 626 } 627 628 // Generate liveness for defs. 629 for (unsigned Reg : RegOpers.Defs) { 630 if (LiveRegs.insert(Reg)) 631 increaseRegPressure(Reg); 632 } 633 634 // Boost pressure for all dead defs together. 635 increaseRegPressure(RegOpers.DeadDefs); 636 decreaseRegPressure(RegOpers.DeadDefs); 637 638 // Find the next instruction. 639 do 640 ++CurrPos; 641 while (CurrPos != MBB->end() && CurrPos->isDebugValue()); 642 } 643 644 /// Find the max change in excess pressure across all sets. 645 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec, 646 ArrayRef<unsigned> NewPressureVec, 647 RegPressureDelta &Delta, 648 const RegisterClassInfo *RCI, 649 ArrayRef<unsigned> LiveThruPressureVec) { 650 Delta.Excess = PressureChange(); 651 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) { 652 unsigned POld = OldPressureVec[i]; 653 unsigned PNew = NewPressureVec[i]; 654 int PDiff = (int)PNew - (int)POld; 655 if (!PDiff) // No change in this set in the common case. 656 continue; 657 // Only consider change beyond the limit. 658 unsigned Limit = RCI->getRegPressureSetLimit(i); 659 if (!LiveThruPressureVec.empty()) 660 Limit += LiveThruPressureVec[i]; 661 662 if (Limit > POld) { 663 if (Limit > PNew) 664 PDiff = 0; // Under the limit 665 else 666 PDiff = PNew - Limit; // Just exceeded limit. 667 } else if (Limit > PNew) 668 PDiff = Limit - POld; // Just obeyed limit. 669 670 if (PDiff) { 671 Delta.Excess = PressureChange(i); 672 Delta.Excess.setUnitInc(PDiff); 673 break; 674 } 675 } 676 } 677 678 /// Find the max change in max pressure that either surpasses a critical PSet 679 /// limit or exceeds the current MaxPressureLimit. 680 /// 681 /// FIXME: comparing each element of the old and new MaxPressure vectors here is 682 /// silly. It's done now to demonstrate the concept but will go away with a 683 /// RegPressureTracker API change to work with pressure differences. 684 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec, 685 ArrayRef<unsigned> NewMaxPressureVec, 686 ArrayRef<PressureChange> CriticalPSets, 687 ArrayRef<unsigned> MaxPressureLimit, 688 RegPressureDelta &Delta) { 689 Delta.CriticalMax = PressureChange(); 690 Delta.CurrentMax = PressureChange(); 691 692 unsigned CritIdx = 0, CritEnd = CriticalPSets.size(); 693 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) { 694 unsigned POld = OldMaxPressureVec[i]; 695 unsigned PNew = NewMaxPressureVec[i]; 696 if (PNew == POld) // No change in this set in the common case. 697 continue; 698 699 if (!Delta.CriticalMax.isValid()) { 700 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i) 701 ++CritIdx; 702 703 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) { 704 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc(); 705 if (PDiff > 0) { 706 Delta.CriticalMax = PressureChange(i); 707 Delta.CriticalMax.setUnitInc(PDiff); 708 } 709 } 710 } 711 // Find the first increase above MaxPressureLimit. 712 // (Ignores negative MDiff). 713 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) { 714 Delta.CurrentMax = PressureChange(i); 715 Delta.CurrentMax.setUnitInc(PNew - POld); 716 if (CritIdx == CritEnd || Delta.CriticalMax.isValid()) 717 break; 718 } 719 } 720 } 721 722 /// Record the upward impact of a single instruction on current register 723 /// pressure. Unlike the advance/recede pressure tracking interface, this does 724 /// not discover live in/outs. 725 /// 726 /// This is intended for speculative queries. It leaves pressure inconsistent 727 /// with the current position, so must be restored by the caller. 728 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) { 729 assert(!MI->isDebugValue() && "Expect a nondebug instruction."); 730 731 // Account for register pressure similar to RegPressureTracker::recede(). 732 RegisterOperands RegOpers; 733 RegOpers.collect(*MI, *TRI, *MRI, /*IgnoreDead=*/true); 734 assert(RegOpers.DeadDefs.size() == 0); 735 if (RequireIntervals) 736 RegOpers.detectDeadDefs(*MI, *LIS); 737 738 // Kill liveness at live defs. 739 for (unsigned Reg : RegOpers.Defs) { 740 if (!containsReg(RegOpers.Uses, Reg)) 741 decreaseRegPressure(Reg); 742 } 743 // Generate liveness for uses. 744 for (unsigned Reg : RegOpers.Uses) { 745 if (!LiveRegs.contains(Reg)) 746 increaseRegPressure(Reg); 747 } 748 } 749 750 /// Consider the pressure increase caused by traversing this instruction 751 /// bottom-up. Find the pressure set with the most change beyond its pressure 752 /// limit based on the tracker's current pressure, and return the change in 753 /// number of register units of that pressure set introduced by this 754 /// instruction. 755 /// 756 /// This assumes that the current LiveOut set is sufficient. 757 /// 758 /// This is expensive for an on-the-fly query because it calls 759 /// bumpUpwardPressure to recompute the pressure sets based on current 760 /// liveness. This mainly exists to verify correctness, e.g. with 761 /// -verify-misched. getUpwardPressureDelta is the fast version of this query 762 /// that uses the per-SUnit cache of the PressureDiff. 763 void RegPressureTracker:: 764 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff, 765 RegPressureDelta &Delta, 766 ArrayRef<PressureChange> CriticalPSets, 767 ArrayRef<unsigned> MaxPressureLimit) { 768 // Snapshot Pressure. 769 // FIXME: The snapshot heap space should persist. But I'm planning to 770 // summarize the pressure effect so we don't need to snapshot at all. 771 std::vector<unsigned> SavedPressure = CurrSetPressure; 772 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure; 773 774 bumpUpwardPressure(MI); 775 776 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI, 777 LiveThruPressure); 778 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets, 779 MaxPressureLimit, Delta); 780 assert(Delta.CriticalMax.getUnitInc() >= 0 && 781 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure"); 782 783 // Restore the tracker's state. 784 P.MaxSetPressure.swap(SavedMaxPressure); 785 CurrSetPressure.swap(SavedPressure); 786 787 #ifndef NDEBUG 788 if (!PDiff) 789 return; 790 791 // Check if the alternate algorithm yields the same result. 792 RegPressureDelta Delta2; 793 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit); 794 if (Delta != Delta2) { 795 dbgs() << "PDiff: "; 796 PDiff->dump(*TRI); 797 dbgs() << "DELTA: " << *MI; 798 if (Delta.Excess.isValid()) 799 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet()) 800 << " " << Delta.Excess.getUnitInc() << "\n"; 801 if (Delta.CriticalMax.isValid()) 802 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet()) 803 << " " << Delta.CriticalMax.getUnitInc() << "\n"; 804 if (Delta.CurrentMax.isValid()) 805 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet()) 806 << " " << Delta.CurrentMax.getUnitInc() << "\n"; 807 if (Delta2.Excess.isValid()) 808 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet()) 809 << " " << Delta2.Excess.getUnitInc() << "\n"; 810 if (Delta2.CriticalMax.isValid()) 811 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet()) 812 << " " << Delta2.CriticalMax.getUnitInc() << "\n"; 813 if (Delta2.CurrentMax.isValid()) 814 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet()) 815 << " " << Delta2.CurrentMax.getUnitInc() << "\n"; 816 llvm_unreachable("RegP Delta Mismatch"); 817 } 818 #endif 819 } 820 821 /// This is the fast version of querying register pressure that does not 822 /// directly depend on current liveness. 823 /// 824 /// @param Delta captures information needed for heuristics. 825 /// 826 /// @param CriticalPSets Are the pressure sets that are known to exceed some 827 /// limit within the region, not necessarily at the current position. 828 /// 829 /// @param MaxPressureLimit Is the max pressure within the region, not 830 /// necessarily at the current position. 831 void RegPressureTracker:: 832 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff, 833 RegPressureDelta &Delta, 834 ArrayRef<PressureChange> CriticalPSets, 835 ArrayRef<unsigned> MaxPressureLimit) const { 836 unsigned CritIdx = 0, CritEnd = CriticalPSets.size(); 837 for (PressureDiff::const_iterator 838 PDiffI = PDiff.begin(), PDiffE = PDiff.end(); 839 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) { 840 841 unsigned PSetID = PDiffI->getPSet(); 842 unsigned Limit = RCI->getRegPressureSetLimit(PSetID); 843 if (!LiveThruPressure.empty()) 844 Limit += LiveThruPressure[PSetID]; 845 846 unsigned POld = CurrSetPressure[PSetID]; 847 unsigned MOld = P.MaxSetPressure[PSetID]; 848 unsigned MNew = MOld; 849 // Ignore DeadDefs here because they aren't captured by PressureChange. 850 unsigned PNew = POld + PDiffI->getUnitInc(); 851 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) 852 && "PSet overflow/underflow"); 853 if (PNew > MOld) 854 MNew = PNew; 855 // Check if current pressure has exceeded the limit. 856 if (!Delta.Excess.isValid()) { 857 unsigned ExcessInc = 0; 858 if (PNew > Limit) 859 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit; 860 else if (POld > Limit) 861 ExcessInc = Limit - POld; 862 if (ExcessInc) { 863 Delta.Excess = PressureChange(PSetID); 864 Delta.Excess.setUnitInc(ExcessInc); 865 } 866 } 867 // Check if max pressure has exceeded a critical pressure set max. 868 if (MNew == MOld) 869 continue; 870 if (!Delta.CriticalMax.isValid()) { 871 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID) 872 ++CritIdx; 873 874 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) { 875 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc(); 876 if (CritInc > 0 && CritInc <= INT16_MAX) { 877 Delta.CriticalMax = PressureChange(PSetID); 878 Delta.CriticalMax.setUnitInc(CritInc); 879 } 880 } 881 } 882 // Check if max pressure has exceeded the current max. 883 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) { 884 Delta.CurrentMax = PressureChange(PSetID); 885 Delta.CurrentMax.setUnitInc(MNew - MOld); 886 } 887 } 888 } 889 890 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx). 891 static bool findUseBetween(unsigned Reg, SlotIndex PriorUseIdx, 892 SlotIndex NextUseIdx, const MachineRegisterInfo &MRI, 893 const LiveIntervals *LIS) { 894 for (const MachineInstr &MI : MRI.use_nodbg_instructions(Reg)) { 895 SlotIndex InstSlot = LIS->getInstructionIndex(&MI).getRegSlot(); 896 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx) 897 return true; 898 } 899 return false; 900 } 901 902 /// Record the downward impact of a single instruction on current register 903 /// pressure. Unlike the advance/recede pressure tracking interface, this does 904 /// not discover live in/outs. 905 /// 906 /// This is intended for speculative queries. It leaves pressure inconsistent 907 /// with the current position, so must be restored by the caller. 908 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) { 909 assert(!MI->isDebugValue() && "Expect a nondebug instruction."); 910 911 // Account for register pressure similar to RegPressureTracker::recede(). 912 RegisterOperands RegOpers; 913 RegOpers.collect(*MI, *TRI, *MRI); 914 915 // Kill liveness at last uses. Assume allocatable physregs are single-use 916 // rather than checking LiveIntervals. 917 SlotIndex SlotIdx; 918 if (RequireIntervals) 919 SlotIdx = LIS->getInstructionIndex(MI).getRegSlot(); 920 921 for (unsigned Reg : RegOpers.Uses) { 922 if (RequireIntervals) { 923 // FIXME: allow the caller to pass in the list of vreg uses that remain 924 // to be bottom-scheduled to avoid searching uses at each query. 925 SlotIndex CurrIdx = getCurrSlot(); 926 const LiveRange *LR = getLiveRange(*LIS, Reg); 927 if (LR) { 928 LiveQueryResult LRQ = LR->Query(SlotIdx); 929 if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, *MRI, LIS)) 930 decreaseRegPressure(Reg); 931 } 932 } else if (!TargetRegisterInfo::isVirtualRegister(Reg)) { 933 // Allocatable physregs are always single-use before register rewriting. 934 decreaseRegPressure(Reg); 935 } 936 } 937 938 // Generate liveness for defs. 939 increaseRegPressure(RegOpers.Defs); 940 941 // Boost pressure for all dead defs together. 942 increaseRegPressure(RegOpers.DeadDefs); 943 decreaseRegPressure(RegOpers.DeadDefs); 944 } 945 946 /// Consider the pressure increase caused by traversing this instruction 947 /// top-down. Find the register class with the most change in its pressure limit 948 /// based on the tracker's current pressure, and return the number of excess 949 /// register units of that pressure set introduced by this instruction. 950 /// 951 /// This assumes that the current LiveIn set is sufficient. 952 /// 953 /// This is expensive for an on-the-fly query because it calls 954 /// bumpDownwardPressure to recompute the pressure sets based on current 955 /// liveness. We don't yet have a fast version of downward pressure tracking 956 /// analogous to getUpwardPressureDelta. 957 void RegPressureTracker:: 958 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta, 959 ArrayRef<PressureChange> CriticalPSets, 960 ArrayRef<unsigned> MaxPressureLimit) { 961 // Snapshot Pressure. 962 std::vector<unsigned> SavedPressure = CurrSetPressure; 963 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure; 964 965 bumpDownwardPressure(MI); 966 967 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI, 968 LiveThruPressure); 969 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets, 970 MaxPressureLimit, Delta); 971 assert(Delta.CriticalMax.getUnitInc() >= 0 && 972 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure"); 973 974 // Restore the tracker's state. 975 P.MaxSetPressure.swap(SavedMaxPressure); 976 CurrSetPressure.swap(SavedPressure); 977 } 978 979 /// Get the pressure of each PSet after traversing this instruction bottom-up. 980 void RegPressureTracker:: 981 getUpwardPressure(const MachineInstr *MI, 982 std::vector<unsigned> &PressureResult, 983 std::vector<unsigned> &MaxPressureResult) { 984 // Snapshot pressure. 985 PressureResult = CurrSetPressure; 986 MaxPressureResult = P.MaxSetPressure; 987 988 bumpUpwardPressure(MI); 989 990 // Current pressure becomes the result. Restore current pressure. 991 P.MaxSetPressure.swap(MaxPressureResult); 992 CurrSetPressure.swap(PressureResult); 993 } 994 995 /// Get the pressure of each PSet after traversing this instruction top-down. 996 void RegPressureTracker:: 997 getDownwardPressure(const MachineInstr *MI, 998 std::vector<unsigned> &PressureResult, 999 std::vector<unsigned> &MaxPressureResult) { 1000 // Snapshot pressure. 1001 PressureResult = CurrSetPressure; 1002 MaxPressureResult = P.MaxSetPressure; 1003 1004 bumpDownwardPressure(MI); 1005 1006 // Current pressure becomes the result. Restore current pressure. 1007 P.MaxSetPressure.swap(MaxPressureResult); 1008 CurrSetPressure.swap(PressureResult); 1009 } 1010