1 //===- RegisterScavenging.cpp - Machine register scavenging ---------------===//
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 /// \file
11 /// This file implements the machine register scavenger. It can provide
12 /// information, such as unused registers, at any point in a machine basic
13 /// block. It also provides a mechanism to make registers available by evicting
14 /// them to spill slots.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/CodeGen/RegisterScavenging.h"
19 
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/PassSupport.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetFrameLowering.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <iterator>
41 #include <limits>
42 #include <string>
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "reg-scavenging"
47 
48 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
49 
50 void RegScavenger::setRegUsed(unsigned Reg, LaneBitmask LaneMask) {
51   LiveUnits.addRegMasked(Reg, LaneMask);
52 }
53 
54 void RegScavenger::init(MachineBasicBlock &MBB) {
55   MachineFunction &MF = *MBB.getParent();
56   TII = MF.getSubtarget().getInstrInfo();
57   TRI = MF.getSubtarget().getRegisterInfo();
58   MRI = &MF.getRegInfo();
59   LiveUnits.init(*TRI);
60 
61   assert((NumRegUnits == 0 || NumRegUnits == TRI->getNumRegUnits()) &&
62          "Target changed?");
63 
64   // Self-initialize.
65   if (!this->MBB) {
66     NumRegUnits = TRI->getNumRegUnits();
67     KillRegUnits.resize(NumRegUnits);
68     DefRegUnits.resize(NumRegUnits);
69     TmpRegUnits.resize(NumRegUnits);
70   }
71   this->MBB = &MBB;
72 
73   for (ScavengedInfo &SI : Scavenged) {
74     SI.Reg = 0;
75     SI.Restore = nullptr;
76   }
77 
78   Tracking = false;
79 }
80 
81 void RegScavenger::enterBasicBlock(MachineBasicBlock &MBB) {
82   init(MBB);
83   LiveUnits.addLiveIns(MBB);
84 }
85 
86 void RegScavenger::enterBasicBlockEnd(MachineBasicBlock &MBB) {
87   init(MBB);
88   LiveUnits.addLiveOuts(MBB);
89 
90   // Move internal iterator at the last instruction of the block.
91   if (MBB.begin() != MBB.end()) {
92     MBBI = std::prev(MBB.end());
93     Tracking = true;
94   }
95 }
96 
97 void RegScavenger::addRegUnits(BitVector &BV, unsigned Reg) {
98   for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
99     BV.set(*RUI);
100 }
101 
102 void RegScavenger::removeRegUnits(BitVector &BV, unsigned Reg) {
103   for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
104     BV.reset(*RUI);
105 }
106 
107 void RegScavenger::determineKillsAndDefs() {
108   assert(Tracking && "Must be tracking to determine kills and defs");
109 
110   MachineInstr &MI = *MBBI;
111   assert(!MI.isDebugValue() && "Debug values have no kills or defs");
112 
113   // Find out which registers are early clobbered, killed, defined, and marked
114   // def-dead in this instruction.
115   KillRegUnits.reset();
116   DefRegUnits.reset();
117   for (const MachineOperand &MO : MI.operands()) {
118     if (MO.isRegMask()) {
119       TmpRegUnits.clear();
120       for (unsigned RU = 0, RUEnd = TRI->getNumRegUnits(); RU != RUEnd; ++RU) {
121         for (MCRegUnitRootIterator RURI(RU, TRI); RURI.isValid(); ++RURI) {
122           if (MO.clobbersPhysReg(*RURI)) {
123             TmpRegUnits.set(RU);
124             break;
125           }
126         }
127       }
128 
129       // Apply the mask.
130       KillRegUnits |= TmpRegUnits;
131     }
132     if (!MO.isReg())
133       continue;
134     unsigned Reg = MO.getReg();
135     if (!TargetRegisterInfo::isPhysicalRegister(Reg) || isReserved(Reg))
136       continue;
137 
138     if (MO.isUse()) {
139       // Ignore undef uses.
140       if (MO.isUndef())
141         continue;
142       if (MO.isKill())
143         addRegUnits(KillRegUnits, Reg);
144     } else {
145       assert(MO.isDef());
146       if (MO.isDead())
147         addRegUnits(KillRegUnits, Reg);
148       else
149         addRegUnits(DefRegUnits, Reg);
150     }
151   }
152 }
153 
154 void RegScavenger::unprocess() {
155   assert(Tracking && "Cannot unprocess because we're not tracking");
156 
157   MachineInstr &MI = *MBBI;
158   if (!MI.isDebugValue()) {
159     determineKillsAndDefs();
160 
161     // Commit the changes.
162     setUsed(KillRegUnits);
163     setUnused(DefRegUnits);
164   }
165 
166   if (MBBI == MBB->begin()) {
167     MBBI = MachineBasicBlock::iterator(nullptr);
168     Tracking = false;
169   } else
170     --MBBI;
171 }
172 
173 void RegScavenger::forward() {
174   // Move ptr forward.
175   if (!Tracking) {
176     MBBI = MBB->begin();
177     Tracking = true;
178   } else {
179     assert(MBBI != MBB->end() && "Already past the end of the basic block!");
180     MBBI = std::next(MBBI);
181   }
182   assert(MBBI != MBB->end() && "Already at the end of the basic block!");
183 
184   MachineInstr &MI = *MBBI;
185 
186   for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
187          IE = Scavenged.end(); I != IE; ++I) {
188     if (I->Restore != &MI)
189       continue;
190 
191     I->Reg = 0;
192     I->Restore = nullptr;
193   }
194 
195   if (MI.isDebugValue())
196     return;
197 
198   determineKillsAndDefs();
199 
200   // Verify uses and defs.
201 #ifndef NDEBUG
202   for (const MachineOperand &MO : MI.operands()) {
203     if (!MO.isReg())
204       continue;
205     unsigned Reg = MO.getReg();
206     if (!TargetRegisterInfo::isPhysicalRegister(Reg) || isReserved(Reg))
207       continue;
208     if (MO.isUse()) {
209       if (MO.isUndef())
210         continue;
211       if (!isRegUsed(Reg)) {
212         // Check if it's partial live: e.g.
213         // D0 = insert_subreg D0<undef>, S0
214         // ... D0
215         // The problem is the insert_subreg could be eliminated. The use of
216         // D0 is using a partially undef value. This is not *incorrect* since
217         // S1 is can be freely clobbered.
218         // Ideally we would like a way to model this, but leaving the
219         // insert_subreg around causes both correctness and performance issues.
220         bool SubUsed = false;
221         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
222           if (isRegUsed(*SubRegs)) {
223             SubUsed = true;
224             break;
225           }
226         bool SuperUsed = false;
227         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
228           if (isRegUsed(*SR)) {
229             SuperUsed = true;
230             break;
231           }
232         }
233         if (!SubUsed && !SuperUsed) {
234           MBB->getParent()->verify(nullptr, "In Register Scavenger");
235           llvm_unreachable("Using an undefined register!");
236         }
237         (void)SubUsed;
238         (void)SuperUsed;
239       }
240     } else {
241       assert(MO.isDef());
242 #if 0
243       // FIXME: Enable this once we've figured out how to correctly transfer
244       // implicit kills during codegen passes like the coalescer.
245       assert((KillRegs.test(Reg) || isUnused(Reg) ||
246               isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
247              "Re-defining a live register!");
248 #endif
249     }
250   }
251 #endif // NDEBUG
252 
253   // Commit the changes.
254   setUnused(KillRegUnits);
255   setUsed(DefRegUnits);
256 }
257 
258 void RegScavenger::backward() {
259   assert(Tracking && "Must be tracking to determine kills and defs");
260 
261   const MachineInstr &MI = *MBBI;
262   LiveUnits.stepBackward(MI);
263 
264   // Expire scavenge spill frameindex uses.
265   for (ScavengedInfo &I : Scavenged) {
266     if (I.Restore == &MI) {
267       I.Reg = 0;
268       I.Restore = nullptr;
269     }
270   }
271 
272   if (MBBI == MBB->begin()) {
273     MBBI = MachineBasicBlock::iterator(nullptr);
274     Tracking = false;
275   } else
276     --MBBI;
277 }
278 
279 bool RegScavenger::isRegUsed(unsigned Reg, bool includeReserved) const {
280   if (isReserved(Reg))
281     return includeReserved;
282   return !LiveUnits.available(Reg);
283 }
284 
285 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
286   for (unsigned Reg : *RC) {
287     if (!isRegUsed(Reg)) {
288       DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(Reg) <<
289             "\n");
290       return Reg;
291     }
292   }
293   return 0;
294 }
295 
296 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
297   BitVector Mask(TRI->getNumRegs());
298   for (unsigned Reg : *RC)
299     if (!isRegUsed(Reg))
300       Mask.set(Reg);
301   return Mask;
302 }
303 
304 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
305                                        BitVector &Candidates,
306                                        unsigned InstrLimit,
307                                        MachineBasicBlock::iterator &UseMI) {
308   int Survivor = Candidates.find_first();
309   assert(Survivor > 0 && "No candidates for scavenging");
310 
311   MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
312   assert(StartMI != ME && "MI already at terminator");
313   MachineBasicBlock::iterator RestorePointMI = StartMI;
314   MachineBasicBlock::iterator MI = StartMI;
315 
316   bool inVirtLiveRange = false;
317   for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
318     if (MI->isDebugValue()) {
319       ++InstrLimit; // Don't count debug instructions
320       continue;
321     }
322     bool isVirtKillInsn = false;
323     bool isVirtDefInsn = false;
324     // Remove any candidates touched by instruction.
325     for (const MachineOperand &MO : MI->operands()) {
326       if (MO.isRegMask())
327         Candidates.clearBitsNotInMask(MO.getRegMask());
328       if (!MO.isReg() || MO.isUndef() || !MO.getReg())
329         continue;
330       if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
331         if (MO.isDef())
332           isVirtDefInsn = true;
333         else if (MO.isKill())
334           isVirtKillInsn = true;
335         continue;
336       }
337       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
338         Candidates.reset(*AI);
339     }
340     // If we're not in a virtual reg's live range, this is a valid
341     // restore point.
342     if (!inVirtLiveRange) RestorePointMI = MI;
343 
344     // Update whether we're in the live range of a virtual register
345     if (isVirtKillInsn) inVirtLiveRange = false;
346     if (isVirtDefInsn) inVirtLiveRange = true;
347 
348     // Was our survivor untouched by this instruction?
349     if (Candidates.test(Survivor))
350       continue;
351 
352     // All candidates gone?
353     if (Candidates.none())
354       break;
355 
356     Survivor = Candidates.find_first();
357   }
358   // If we ran off the end, that's where we want to restore.
359   if (MI == ME) RestorePointMI = ME;
360   assert(RestorePointMI != StartMI &&
361          "No available scavenger restore location!");
362 
363   // We ran out of candidates, so stop the search.
364   UseMI = RestorePointMI;
365   return Survivor;
366 }
367 
368 /// Given the bitvector \p Available of free register units at position
369 /// \p From. Search backwards to find a register that is part of \p
370 /// Candidates and not used/clobbered until the point \p To. If there is
371 /// multiple candidates continue searching and pick the one that is not used/
372 /// clobbered for the longest time.
373 /// Returns the register and the earliest position we know it to be free or
374 /// the position MBB.end() if no register is available.
375 static std::pair<MCPhysReg, MachineBasicBlock::iterator>
376 findSurvivorBackwards(const MachineRegisterInfo &MRI,
377     MachineBasicBlock::iterator From, MachineBasicBlock::iterator To,
378     const LiveRegUnits &LiveOut, ArrayRef<MCPhysReg> AllocationOrder) {
379   bool FoundTo = false;
380   MCPhysReg Survivor = 0;
381   MachineBasicBlock::iterator Pos;
382   MachineBasicBlock &MBB = *From->getParent();
383   unsigned InstrLimit = 25;
384   unsigned InstrCountDown = InstrLimit;
385   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
386   LiveRegUnits Used(TRI);
387 
388   for (MachineBasicBlock::iterator I = From;; --I) {
389     const MachineInstr &MI = *I;
390 
391     Used.accumulateBackward(MI);
392 
393     if (I == To) {
394       // See if one of the registers in RC wasn't used so far.
395       for (MCPhysReg Reg : AllocationOrder) {
396         if (!MRI.isReserved(Reg) && Used.available(Reg) &&
397             LiveOut.available(Reg))
398           return std::make_pair(Reg, MBB.end());
399       }
400       // Otherwise we will continue up to InstrLimit instructions to find
401       // the register which is not defined/used for the longest time.
402       FoundTo = true;
403       Pos = To;
404     }
405     if (FoundTo) {
406       if (Survivor == 0 || !Used.available(Survivor)) {
407         MCPhysReg AvilableReg = 0;
408         for (MCPhysReg Reg : AllocationOrder) {
409           if (!MRI.isReserved(Reg) && Used.available(Reg)) {
410             AvilableReg = Reg;
411             break;
412           }
413         }
414         if (AvilableReg == 0)
415           break;
416         Survivor = AvilableReg;
417       }
418       if (--InstrCountDown == 0)
419         break;
420 
421       // Keep searching when we find a vreg since the spilled register will
422       // be usefull for this other vreg as well later.
423       bool FoundVReg = false;
424       for (const MachineOperand &MO : MI.operands()) {
425         if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
426           FoundVReg = true;
427           break;
428         }
429       }
430       if (FoundVReg) {
431         InstrCountDown = InstrLimit;
432         Pos = I;
433       }
434       if (I == MBB.begin())
435         break;
436     }
437   }
438 
439   return std::make_pair(Survivor, Pos);
440 }
441 
442 static unsigned getFrameIndexOperandNum(MachineInstr &MI) {
443   unsigned i = 0;
444   while (!MI.getOperand(i).isFI()) {
445     ++i;
446     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
447   }
448   return i;
449 }
450 
451 RegScavenger::ScavengedInfo &
452 RegScavenger::spill(unsigned Reg, const TargetRegisterClass &RC, int SPAdj,
453                     MachineBasicBlock::iterator Before,
454                     MachineBasicBlock::iterator &UseMI) {
455   // Find an available scavenging slot with size and alignment matching
456   // the requirements of the class RC.
457   const MachineFunction &MF = *Before->getParent()->getParent();
458   const MachineFrameInfo &MFI = MF.getFrameInfo();
459   unsigned NeedSize = TRI->getSpillSize(RC);
460   unsigned NeedAlign = TRI->getSpillAlignment(RC);
461 
462   unsigned SI = Scavenged.size(), Diff = std::numeric_limits<unsigned>::max();
463   int FIB = MFI.getObjectIndexBegin(), FIE = MFI.getObjectIndexEnd();
464   for (unsigned I = 0; I < Scavenged.size(); ++I) {
465     if (Scavenged[I].Reg != 0)
466       continue;
467     // Verify that this slot is valid for this register.
468     int FI = Scavenged[I].FrameIndex;
469     if (FI < FIB || FI >= FIE)
470       continue;
471     unsigned S = MFI.getObjectSize(FI);
472     unsigned A = MFI.getObjectAlignment(FI);
473     if (NeedSize > S || NeedAlign > A)
474       continue;
475     // Avoid wasting slots with large size and/or large alignment. Pick one
476     // that is the best fit for this register class (in street metric).
477     // Picking a larger slot than necessary could happen if a slot for a
478     // larger register is reserved before a slot for a smaller one. When
479     // trying to spill a smaller register, the large slot would be found
480     // first, thus making it impossible to spill the larger register later.
481     unsigned D = (S-NeedSize) + (A-NeedAlign);
482     if (D < Diff) {
483       SI = I;
484       Diff = D;
485     }
486   }
487 
488   if (SI == Scavenged.size()) {
489     // We need to scavenge a register but have no spill slot, the target
490     // must know how to do it (if not, we'll assert below).
491     Scavenged.push_back(ScavengedInfo(FIE));
492   }
493 
494   // Avoid infinite regress
495   Scavenged[SI].Reg = Reg;
496 
497   // If the target knows how to save/restore the register, let it do so;
498   // otherwise, use the emergency stack spill slot.
499   if (!TRI->saveScavengerRegister(*MBB, Before, UseMI, &RC, Reg)) {
500     // Spill the scavenged register before \p Before.
501     int FI = Scavenged[SI].FrameIndex;
502     if (FI < FIB || FI >= FIE) {
503       std::string Msg = std::string("Error while trying to spill ") +
504           TRI->getName(Reg) + " from class " + TRI->getRegClassName(&RC) +
505           ": Cannot scavenge register without an emergency spill slot!";
506       report_fatal_error(Msg.c_str());
507     }
508     TII->storeRegToStackSlot(*MBB, Before, Reg, true, Scavenged[SI].FrameIndex,
509                              &RC, TRI);
510     MachineBasicBlock::iterator II = std::prev(Before);
511 
512     unsigned FIOperandNum = getFrameIndexOperandNum(*II);
513     TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
514 
515     // Restore the scavenged register before its use (or first terminator).
516     TII->loadRegFromStackSlot(*MBB, UseMI, Reg, Scavenged[SI].FrameIndex,
517                               &RC, TRI);
518     II = std::prev(UseMI);
519 
520     FIOperandNum = getFrameIndexOperandNum(*II);
521     TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
522   }
523   return Scavenged[SI];
524 }
525 
526 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
527                                         MachineBasicBlock::iterator I,
528                                         int SPAdj) {
529   MachineInstr &MI = *I;
530   const MachineFunction &MF = *MI.getParent()->getParent();
531   // Consider all allocatable registers in the register class initially
532   BitVector Candidates = TRI->getAllocatableSet(MF, RC);
533 
534   // Exclude all the registers being used by the instruction.
535   for (const MachineOperand &MO : MI.operands()) {
536     if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
537         !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
538       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
539         Candidates.reset(*AI);
540   }
541 
542   // Try to find a register that's unused if there is one, as then we won't
543   // have to spill.
544   BitVector Available = getRegsAvailable(RC);
545   Available &= Candidates;
546   if (Available.any())
547     Candidates = Available;
548 
549   // Find the register whose use is furthest away.
550   MachineBasicBlock::iterator UseMI;
551   unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
552 
553   // If we found an unused register there is no reason to spill it.
554   if (!isRegUsed(SReg)) {
555     DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
556     return SReg;
557   }
558 
559   ScavengedInfo &Scavenged = spill(SReg, *RC, SPAdj, I, UseMI);
560   Scavenged.Restore = &*std::prev(UseMI);
561 
562   DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<
563         "\n");
564 
565   return SReg;
566 }
567 
568 unsigned RegScavenger::scavengeRegisterBackwards(const TargetRegisterClass &RC,
569                                                  MachineBasicBlock::iterator To,
570                                                  bool RestoreAfter, int SPAdj) {
571   const MachineBasicBlock &MBB = *To->getParent();
572   const MachineFunction &MF = *MBB.getParent();
573 
574   // Find the register whose use is furthest away.
575   MachineBasicBlock::iterator UseMI;
576   ArrayRef<MCPhysReg> AllocationOrder = RC.getRawAllocationOrder(MF);
577   std::pair<MCPhysReg, MachineBasicBlock::iterator> P =
578       findSurvivorBackwards(*MRI, MBBI, To, LiveUnits, AllocationOrder);
579   MCPhysReg Reg = P.first;
580   MachineBasicBlock::iterator SpillBefore = P.second;
581   assert(Reg != 0 && "No register left to scavenge!");
582   // Found an available register?
583   if (SpillBefore != MBB.end()) {
584     MachineBasicBlock::iterator ReloadAfter =
585       RestoreAfter ? std::next(MBBI) : MBBI;
586     MachineBasicBlock::iterator ReloadBefore = std::next(ReloadAfter);
587     DEBUG(dbgs() << "Reload before: " << *ReloadBefore << '\n');
588     ScavengedInfo &Scavenged = spill(Reg, RC, SPAdj, SpillBefore, ReloadBefore);
589     Scavenged.Restore = &*std::prev(SpillBefore);
590     LiveUnits.removeReg(Reg);
591     DEBUG(dbgs() << "Scavenged register with spill: " << PrintReg(Reg, TRI)
592           << " until " << *SpillBefore);
593   } else {
594     DEBUG(dbgs() << "Scavenged free register: " << PrintReg(Reg, TRI) << '\n');
595   }
596   return Reg;
597 }
598 
599 /// Allocate a register for the virtual register \p VReg. The last use of
600 /// \p VReg is around the current position of the register scavenger \p RS.
601 /// \p ReserveAfter controls whether the scavenged register needs to be reserved
602 /// after the current instruction, otherwise it will only be reserved before the
603 /// current instruction.
604 static unsigned scavengeVReg(MachineRegisterInfo &MRI, RegScavenger &RS,
605                              unsigned VReg, bool ReserveAfter) {
606   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
607 #ifndef NDEBUG
608   // Verify that all definitions and uses are in the same basic block.
609   const MachineBasicBlock *CommonMBB = nullptr;
610   // Real definition for the reg, re-definitions are not considered.
611   const MachineInstr *RealDef = nullptr;
612   for (MachineOperand &MO : MRI.reg_nodbg_operands(VReg)) {
613     MachineBasicBlock *MBB = MO.getParent()->getParent();
614     if (CommonMBB == nullptr)
615       CommonMBB = MBB;
616     assert(MBB == CommonMBB && "All defs+uses must be in the same basic block");
617     if (MO.isDef()) {
618       const MachineInstr &MI = *MO.getParent();
619       if (!MI.readsRegister(VReg, &TRI)) {
620         assert((!RealDef || RealDef == &MI) &&
621                "Can have at most one definition which is not a redefinition");
622         RealDef = &MI;
623       }
624     }
625   }
626   assert(RealDef != nullptr && "Must have at least 1 Def");
627 #endif
628 
629   // We should only have one definition of the register. However to accomodate
630   // the requirements of two address code we also allow definitions in
631   // subsequent instructions provided they also read the register. That way
632   // we get a single contiguous lifetime.
633   //
634   // Definitions in MRI.def_begin() are unordered, search for the first.
635   MachineRegisterInfo::def_iterator FirstDef =
636     std::find_if(MRI.def_begin(VReg), MRI.def_end(),
637                  [VReg, &TRI](const MachineOperand &MO) {
638       return !MO.getParent()->readsRegister(VReg, &TRI);
639     });
640   assert(FirstDef != MRI.def_end() &&
641          "Must have one definition that does not redefine vreg");
642   MachineInstr &DefMI = *FirstDef->getParent();
643 
644   // The register scavenger will report a free register inserting an emergency
645   // spill/reload if necessary.
646   int SPAdj = 0;
647   const TargetRegisterClass &RC = *MRI.getRegClass(VReg);
648   unsigned SReg = RS.scavengeRegisterBackwards(RC, DefMI.getIterator(),
649                                                ReserveAfter, SPAdj);
650   MRI.replaceRegWith(VReg, SReg);
651   ++NumScavengedRegs;
652   return SReg;
653 }
654 
655 /// Allocate (scavenge) vregs inside a single basic block.
656 /// Returns true if the target spill callback created new vregs and a 2nd pass
657 /// is necessary.
658 static bool scavengeFrameVirtualRegsInBlock(MachineRegisterInfo &MRI,
659                                             RegScavenger &RS,
660                                             MachineBasicBlock &MBB) {
661   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
662   RS.enterBasicBlockEnd(MBB);
663 
664   unsigned InitialNumVirtRegs = MRI.getNumVirtRegs();
665   bool NextInstructionReadsVReg = false;
666   for (MachineBasicBlock::iterator I = MBB.end(); I != MBB.begin(); ) {
667     --I;
668     // Move RegScavenger to the position between *I and *std::next(I).
669     RS.backward(I);
670 
671     // Look for unassigned vregs in the uses of *std::next(I).
672     if (NextInstructionReadsVReg) {
673       MachineBasicBlock::iterator N = std::next(I);
674       const MachineInstr &NMI = *N;
675       for (const MachineOperand &MO : NMI.operands()) {
676         if (!MO.isReg())
677           continue;
678         unsigned Reg = MO.getReg();
679         // We only care about virtual registers and ignore virtual registers
680         // created by the target callbacks in the process (those will be handled
681         // in a scavenging round).
682         if (!TargetRegisterInfo::isVirtualRegister(Reg) ||
683             TargetRegisterInfo::virtReg2Index(Reg) >= InitialNumVirtRegs)
684           continue;
685         if (!MO.readsReg())
686           continue;
687 
688         unsigned SReg = scavengeVReg(MRI, RS, Reg, true);
689         N->addRegisterKilled(SReg, &TRI, false);
690         RS.setRegUsed(SReg);
691       }
692     }
693 
694     // Look for unassigned vregs in the defs of *I.
695     NextInstructionReadsVReg = false;
696     const MachineInstr &MI = *I;
697     for (const MachineOperand &MO : MI.operands()) {
698       if (!MO.isReg())
699         continue;
700       unsigned Reg = MO.getReg();
701       // Only vregs, no newly created vregs (see above).
702       if (!TargetRegisterInfo::isVirtualRegister(Reg) ||
703           TargetRegisterInfo::virtReg2Index(Reg) >= InitialNumVirtRegs)
704         continue;
705       // We have to look at all operands anyway so we can precalculate here
706       // whether there is a reading operand. This allows use to skip the use
707       // step in the next iteration if there was none.
708       assert(!MO.isInternalRead() && "Cannot assign inside bundles");
709       assert((!MO.isUndef() || MO.isDef()) && "Cannot handle undef uses");
710       if (MO.readsReg()) {
711         NextInstructionReadsVReg = true;
712       }
713       if (MO.isDef()) {
714         unsigned SReg = scavengeVReg(MRI, RS, Reg, false);
715         I->addRegisterDead(SReg, &TRI, false);
716       }
717     }
718   }
719 #ifndef NDEBUG
720   for (const MachineOperand &MO : MBB.front().operands()) {
721     if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
722       continue;
723     assert(!MO.isInternalRead() && "Cannot assign inside bundles");
724     assert((!MO.isUndef() || MO.isDef()) && "Cannot handle undef uses");
725     assert(!MO.readsReg() && "Vreg use in first instruction not allowed");
726   }
727 #endif
728 
729   return MRI.getNumVirtRegs() != InitialNumVirtRegs;
730 }
731 
732 void llvm::scavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger &RS) {
733   // FIXME: Iterating over the instruction stream is unnecessary. We can simply
734   // iterate over the vreg use list, which at this point only contains machine
735   // operands for which eliminateFrameIndex need a new scratch reg.
736   MachineRegisterInfo &MRI = MF.getRegInfo();
737   // Shortcut.
738   if (MRI.getNumVirtRegs() == 0) {
739     MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
740     return;
741   }
742 
743   // Run through the instructions and find any virtual registers.
744   for (MachineBasicBlock &MBB : MF) {
745     if (MBB.empty())
746       continue;
747 
748     bool Again = scavengeFrameVirtualRegsInBlock(MRI, RS, MBB);
749     if (Again) {
750       DEBUG(dbgs() << "Warning: Required two scavenging passes for block "
751             << MBB.getName() << '\n');
752       Again = scavengeFrameVirtualRegsInBlock(MRI, RS, MBB);
753       // The target required a 2nd run (because it created new vregs while
754       // spilling). Refuse to do another pass to keep compiletime in check.
755       if (Again)
756         report_fatal_error("Incomplete scavenging after 2nd pass");
757     }
758   }
759 
760   MRI.clearVirtRegs();
761   MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
762 }
763 
764 namespace {
765 /// This class runs register scavenging independ of the PrologEpilogInserter.
766 /// This is used in for testing.
767 class ScavengerTest : public MachineFunctionPass {
768 public:
769   static char ID;
770   ScavengerTest() : MachineFunctionPass(ID) {}
771   bool runOnMachineFunction(MachineFunction &MF) {
772     const TargetSubtargetInfo &STI = MF.getSubtarget();
773     const TargetFrameLowering &TFL = *STI.getFrameLowering();
774 
775     RegScavenger RS;
776     // Let's hope that calling those outside of PrologEpilogueInserter works
777     // well enough to initialize the scavenger with some emergency spillslots
778     // for the target.
779     BitVector SavedRegs;
780     TFL.determineCalleeSaves(MF, SavedRegs, &RS);
781     TFL.processFunctionBeforeFrameFinalized(MF, &RS);
782 
783     // Let's scavenge the current function
784     scavengeFrameVirtualRegs(MF, RS);
785     return true;
786   }
787 };
788 char ScavengerTest::ID;
789 
790 } // end anonymous namespace
791 
792 INITIALIZE_PASS(ScavengerTest, "scavenger-test",
793                 "Scavenge virtual registers inside basic blocks", false, false)
794