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