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