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