Remove the TargetMachine forwards for TargetSubtargetInfo based
[oota-llvm.git] / lib / CodeGen / RegisterScavenging.cpp
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 // This file implements the machine register scavenger. It can provide
11 // information, such as unused registers, at any point in a machine basic block.
12 // It also provides a mechanism to make registers available by evicting them to
13 // spill slots.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/CodeGen/RegisterScavenging.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetSubtargetInfo.h"
30 using namespace llvm;
31
32 #define DEBUG_TYPE "reg-scavenging"
33
34 /// setUsed - Set the register and its sub-registers as being used.
35 void RegScavenger::setUsed(unsigned Reg) {
36   for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
37        SubRegs.isValid(); ++SubRegs)
38     RegsAvailable.reset(*SubRegs);
39 }
40
41 bool RegScavenger::isAliasUsed(unsigned Reg) const {
42   for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
43     if (isUsed(*AI, *AI == Reg))
44       return true;
45   return false;
46 }
47
48 void RegScavenger::initRegState() {
49   for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
50          IE = Scavenged.end(); I != IE; ++I) {
51     I->Reg = 0;
52     I->Restore = nullptr;
53   }
54
55   // All registers started out unused.
56   RegsAvailable.set();
57
58   if (!MBB)
59     return;
60
61   // Live-in registers are in use.
62   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
63          E = MBB->livein_end(); I != E; ++I)
64     setUsed(*I);
65
66   // Pristine CSRs are also unavailable.
67   BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
68   for (int I = PR.find_first(); I>0; I = PR.find_next(I))
69     setUsed(I);
70 }
71
72 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
73   MachineFunction &MF = *mbb->getParent();
74   const TargetMachine &TM = MF.getTarget();
75   TII = TM.getSubtargetImpl()->getInstrInfo();
76   TRI = TM.getSubtargetImpl()->getRegisterInfo();
77   MRI = &MF.getRegInfo();
78
79   assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
80          "Target changed?");
81
82   // It is not possible to use the register scavenger after late optimization
83   // passes that don't preserve accurate liveness information.
84   assert(MRI->tracksLiveness() &&
85          "Cannot use register scavenger with inaccurate liveness");
86
87   // Self-initialize.
88   if (!MBB) {
89     NumPhysRegs = TRI->getNumRegs();
90     RegsAvailable.resize(NumPhysRegs);
91     KillRegs.resize(NumPhysRegs);
92     DefRegs.resize(NumPhysRegs);
93
94     // Create callee-saved registers bitvector.
95     CalleeSavedRegs.resize(NumPhysRegs);
96     const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
97     if (CSRegs != nullptr)
98       for (unsigned i = 0; CSRegs[i]; ++i)
99         CalleeSavedRegs.set(CSRegs[i]);
100   }
101
102   MBB = mbb;
103   initRegState();
104
105   Tracking = false;
106 }
107
108 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
109   for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
110        SubRegs.isValid(); ++SubRegs)
111     BV.set(*SubRegs);
112 }
113
114 void RegScavenger::determineKillsAndDefs() {
115   assert(Tracking && "Must be tracking to determine kills and defs");
116
117   MachineInstr *MI = MBBI;
118   assert(!MI->isDebugValue() && "Debug values have no kills or defs");
119
120   // Find out which registers are early clobbered, killed, defined, and marked
121   // def-dead in this instruction.
122   // FIXME: The scavenger is not predication aware. If the instruction is
123   // predicated, conservatively assume "kill" markers do not actually kill the
124   // register. Similarly ignores "dead" markers.
125   bool isPred = TII->isPredicated(MI);
126   KillRegs.reset();
127   DefRegs.reset();
128   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
129     const MachineOperand &MO = MI->getOperand(i);
130     if (MO.isRegMask())
131       (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
132     if (!MO.isReg())
133       continue;
134     unsigned Reg = MO.getReg();
135     if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
136       continue;
137
138     if (MO.isUse()) {
139       // Ignore undef uses.
140       if (MO.isUndef())
141         continue;
142       if (!isPred && MO.isKill())
143         addRegWithSubRegs(KillRegs, Reg);
144     } else {
145       assert(MO.isDef());
146       if (!isPred && MO.isDead())
147         addRegWithSubRegs(KillRegs, Reg);
148       else
149         addRegWithSubRegs(DefRegs, 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(KillRegs);
163     setUnused(DefRegs);
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 (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
203     const MachineOperand &MO = MI->getOperand(i);
204     if (!MO.isReg())
205       continue;
206     unsigned Reg = MO.getReg();
207     if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
208       continue;
209     if (MO.isUse()) {
210       if (MO.isUndef())
211         continue;
212       if (!isUsed(Reg)) {
213         // Check if it's partial live: e.g.
214         // D0 = insert_subreg D0<undef>, S0
215         // ... D0
216         // The problem is the insert_subreg could be eliminated. The use of
217         // D0 is using a partially undef value. This is not *incorrect* since
218         // S1 is can be freely clobbered.
219         // Ideally we would like a way to model this, but leaving the
220         // insert_subreg around causes both correctness and performance issues.
221         bool SubUsed = false;
222         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
223           if (isUsed(*SubRegs)) {
224             SubUsed = true;
225             break;
226           }
227         if (!SubUsed) {
228           MBB->getParent()->verify(nullptr, "In Register Scavenger");
229           llvm_unreachable("Using an undefined register!");
230         }
231         (void)SubUsed;
232       }
233     } else {
234       assert(MO.isDef());
235 #if 0
236       // FIXME: Enable this once we've figured out how to correctly transfer
237       // implicit kills during codegen passes like the coalescer.
238       assert((KillRegs.test(Reg) || isUnused(Reg) ||
239               isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
240              "Re-defining a live register!");
241 #endif
242     }
243   }
244 #endif // NDEBUG
245
246   // Commit the changes.
247   setUnused(KillRegs);
248   setUsed(DefRegs);
249 }
250
251 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
252   used = RegsAvailable;
253   used.flip();
254   if (includeReserved)
255     used |= MRI->getReservedRegs();
256   else
257     used.reset(MRI->getReservedRegs());
258 }
259
260 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
261   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
262        I != E; ++I)
263     if (!isAliasUsed(*I)) {
264       DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
265             "\n");
266       return *I;
267     }
268   return 0;
269 }
270
271 /// getRegsAvailable - Return all available registers in the register class
272 /// in Mask.
273 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
274   BitVector Mask(TRI->getNumRegs());
275   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
276        I != E; ++I)
277     if (!isAliasUsed(*I))
278       Mask.set(*I);
279   return Mask;
280 }
281
282 /// findSurvivorReg - Return the candidate register that is unused for the
283 /// longest after StargMII. UseMI is set to the instruction where the search
284 /// stopped.
285 ///
286 /// No more than InstrLimit instructions are inspected.
287 ///
288 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
289                                        BitVector &Candidates,
290                                        unsigned InstrLimit,
291                                        MachineBasicBlock::iterator &UseMI) {
292   int Survivor = Candidates.find_first();
293   assert(Survivor > 0 && "No candidates for scavenging");
294
295   MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
296   assert(StartMI != ME && "MI already at terminator");
297   MachineBasicBlock::iterator RestorePointMI = StartMI;
298   MachineBasicBlock::iterator MI = StartMI;
299
300   bool inVirtLiveRange = false;
301   for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
302     if (MI->isDebugValue()) {
303       ++InstrLimit; // Don't count debug instructions
304       continue;
305     }
306     bool isVirtKillInsn = false;
307     bool isVirtDefInsn = false;
308     // Remove any candidates touched by instruction.
309     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
310       const MachineOperand &MO = MI->getOperand(i);
311       if (MO.isRegMask())
312         Candidates.clearBitsNotInMask(MO.getRegMask());
313       if (!MO.isReg() || MO.isUndef() || !MO.getReg())
314         continue;
315       if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
316         if (MO.isDef())
317           isVirtDefInsn = true;
318         else if (MO.isKill())
319           isVirtKillInsn = true;
320         continue;
321       }
322       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
323         Candidates.reset(*AI);
324     }
325     // If we're not in a virtual reg's live range, this is a valid
326     // restore point.
327     if (!inVirtLiveRange) RestorePointMI = MI;
328
329     // Update whether we're in the live range of a virtual register
330     if (isVirtKillInsn) inVirtLiveRange = false;
331     if (isVirtDefInsn) inVirtLiveRange = true;
332
333     // Was our survivor untouched by this instruction?
334     if (Candidates.test(Survivor))
335       continue;
336
337     // All candidates gone?
338     if (Candidates.none())
339       break;
340
341     Survivor = Candidates.find_first();
342   }
343   // If we ran off the end, that's where we want to restore.
344   if (MI == ME) RestorePointMI = ME;
345   assert (RestorePointMI != StartMI &&
346           "No available scavenger restore location!");
347
348   // We ran out of candidates, so stop the search.
349   UseMI = RestorePointMI;
350   return Survivor;
351 }
352
353 static unsigned getFrameIndexOperandNum(MachineInstr *MI) {
354   unsigned i = 0;
355   while (!MI->getOperand(i).isFI()) {
356     ++i;
357     assert(i < MI->getNumOperands() &&
358            "Instr doesn't have FrameIndex operand!");
359   }
360   return i;
361 }
362
363 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
364                                         MachineBasicBlock::iterator I,
365                                         int SPAdj) {
366   // Consider all allocatable registers in the register class initially
367   BitVector Candidates =
368     TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
369
370   // Exclude all the registers being used by the instruction.
371   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
372     MachineOperand &MO = I->getOperand(i);
373     if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
374         !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
375       Candidates.reset(MO.getReg());
376   }
377
378   // Try to find a register that's unused if there is one, as then we won't
379   // have to spill. Search explicitly rather than masking out based on
380   // RegsAvailable, as RegsAvailable does not take aliases into account.
381   // That's what getRegsAvailable() is for.
382   BitVector Available = getRegsAvailable(RC);
383   Available &= Candidates;
384   if (Available.any())
385     Candidates = Available;
386
387   // Find the register whose use is furthest away.
388   MachineBasicBlock::iterator UseMI;
389   unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
390
391   // If we found an unused register there is no reason to spill it.
392   if (!isAliasUsed(SReg)) {
393     DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
394     return SReg;
395   }
396
397   // Find an available scavenging slot.
398   unsigned SI;
399   for (SI = 0; SI < Scavenged.size(); ++SI)
400     if (Scavenged[SI].Reg == 0)
401       break;
402
403   if (SI == Scavenged.size()) {
404     // We need to scavenge a register but have no spill slot, the target
405     // must know how to do it (if not, we'll assert below).
406     Scavenged.push_back(ScavengedInfo());
407   }
408
409   // Avoid infinite regress
410   Scavenged[SI].Reg = SReg;
411
412   // If the target knows how to save/restore the register, let it do so;
413   // otherwise, use the emergency stack spill slot.
414   if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
415     // Spill the scavenged register before I.
416     assert(Scavenged[SI].FrameIndex >= 0 &&
417            "Cannot scavenge register without an emergency spill slot!");
418     TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex,
419                              RC, TRI);
420     MachineBasicBlock::iterator II = std::prev(I);
421
422     unsigned FIOperandNum = getFrameIndexOperandNum(II);
423     TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
424
425     // Restore the scavenged register before its use (or first terminator).
426     TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex,
427                               RC, TRI);
428     II = std::prev(UseMI);
429
430     FIOperandNum = getFrameIndexOperandNum(II);
431     TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
432   }
433
434   Scavenged[SI].Restore = std::prev(UseMI);
435
436   // Doing this here leads to infinite regress.
437   // Scavenged[SI].Reg = SReg;
438
439   DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<
440         "\n");
441
442   return SReg;
443 }