Use uint16_t to store register overlaps to reduce static data.
[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 #define DEBUG_TYPE "reg-scavenging"
18 #include "llvm/CodeGen/RegisterScavenging.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/STLExtras.h"
34 using namespace llvm;
35
36 /// setUsed - Set the register and its sub-registers as being used.
37 void RegScavenger::setUsed(unsigned Reg) {
38   RegsAvailable.reset(Reg);
39
40   for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
41        unsigned SubReg = *SubRegs; ++SubRegs)
42     RegsAvailable.reset(SubReg);
43 }
44
45 bool RegScavenger::isAliasUsed(unsigned Reg) const {
46   if (isUsed(Reg))
47     return true;
48   for (const uint16_t *R = TRI->getAliasSet(Reg); *R; ++R)
49     if (isUsed(*R))
50       return true;
51   return false;
52 }
53
54 void RegScavenger::initRegState() {
55   ScavengedReg = 0;
56   ScavengedRC = NULL;
57   ScavengeRestore = NULL;
58
59   // All registers started out unused.
60   RegsAvailable.set();
61
62   if (!MBB)
63     return;
64
65   // Live-in registers are in use.
66   for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
67          E = MBB->livein_end(); I != E; ++I)
68     setUsed(*I);
69
70   // Pristine CSRs are also unavailable.
71   BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
72   for (int I = PR.find_first(); I>0; I = PR.find_next(I))
73     setUsed(I);
74 }
75
76 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
77   MachineFunction &MF = *mbb->getParent();
78   const TargetMachine &TM = MF.getTarget();
79   TII = TM.getInstrInfo();
80   TRI = TM.getRegisterInfo();
81   MRI = &MF.getRegInfo();
82
83   assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
84          "Target changed?");
85
86   // Self-initialize.
87   if (!MBB) {
88     NumPhysRegs = TRI->getNumRegs();
89     RegsAvailable.resize(NumPhysRegs);
90     KillRegs.resize(NumPhysRegs);
91     DefRegs.resize(NumPhysRegs);
92
93     // Create reserved registers bitvector.
94     ReservedRegs = TRI->getReservedRegs(MF);
95
96     // Create callee-saved registers bitvector.
97     CalleeSavedRegs.resize(NumPhysRegs);
98     const uint16_t *CSRegs = TRI->getCalleeSavedRegs(&MF);
99     if (CSRegs != NULL)
100       for (unsigned i = 0; CSRegs[i]; ++i)
101         CalleeSavedRegs.set(CSRegs[i]);
102   }
103
104   MBB = mbb;
105   initRegState();
106
107   Tracking = false;
108 }
109
110 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
111   BV.set(Reg);
112   for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
113     BV.set(*R);
114 }
115
116 void RegScavenger::forward() {
117   // Move ptr forward.
118   if (!Tracking) {
119     MBBI = MBB->begin();
120     Tracking = true;
121   } else {
122     assert(MBBI != MBB->end() && "Already past the end of the basic block!");
123     MBBI = llvm::next(MBBI);
124   }
125   assert(MBBI != MBB->end() && "Already at the end of the basic block!");
126
127   MachineInstr *MI = MBBI;
128
129   if (MI == ScavengeRestore) {
130     ScavengedReg = 0;
131     ScavengedRC = NULL;
132     ScavengeRestore = NULL;
133   }
134
135   if (MI->isDebugValue())
136     return;
137
138   // Find out which registers are early clobbered, killed, defined, and marked
139   // def-dead in this instruction.
140   // FIXME: The scavenger is not predication aware. If the instruction is
141   // predicated, conservatively assume "kill" markers do not actually kill the
142   // register. Similarly ignores "dead" markers.
143   bool isPred = TII->isPredicated(MI);
144   KillRegs.reset();
145   DefRegs.reset();
146   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
147     const MachineOperand &MO = MI->getOperand(i);
148     if (MO.isRegMask())
149       (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
150     if (!MO.isReg())
151       continue;
152     unsigned Reg = MO.getReg();
153     if (!Reg || isReserved(Reg))
154       continue;
155
156     if (MO.isUse()) {
157       // Ignore undef uses.
158       if (MO.isUndef())
159         continue;
160       if (!isPred && MO.isKill())
161         addRegWithSubRegs(KillRegs, Reg);
162     } else {
163       assert(MO.isDef());
164       if (!isPred && MO.isDead())
165         addRegWithSubRegs(KillRegs, Reg);
166       else
167         addRegWithSubRegs(DefRegs, Reg);
168     }
169   }
170
171   // Verify uses and defs.
172 #ifndef NDEBUG
173   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
174     const MachineOperand &MO = MI->getOperand(i);
175     if (!MO.isReg())
176       continue;
177     unsigned Reg = MO.getReg();
178     if (!Reg || isReserved(Reg))
179       continue;
180     if (MO.isUse()) {
181       if (MO.isUndef())
182         continue;
183       if (!isUsed(Reg)) {
184         // Check if it's partial live: e.g.
185         // D0 = insert_subreg D0<undef>, S0
186         // ... D0
187         // The problem is the insert_subreg could be eliminated. The use of
188         // D0 is using a partially undef value. This is not *incorrect* since
189         // S1 is can be freely clobbered.
190         // Ideally we would like a way to model this, but leaving the
191         // insert_subreg around causes both correctness and performance issues.
192         bool SubUsed = false;
193         for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
194              unsigned SubReg = *SubRegs; ++SubRegs)
195           if (isUsed(SubReg)) {
196             SubUsed = true;
197             break;
198           }
199         if (!SubUsed) {
200           MBB->getParent()->verify(NULL, "In Register Scavenger");
201           llvm_unreachable("Using an undefined register!");
202         }
203         (void)SubUsed;
204       }
205     } else {
206       assert(MO.isDef());
207 #if 0
208       // FIXME: Enable this once we've figured out how to correctly transfer
209       // implicit kills during codegen passes like the coalescer.
210       assert((KillRegs.test(Reg) || isUnused(Reg) ||
211               isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
212              "Re-defining a live register!");
213 #endif
214     }
215   }
216 #endif // NDEBUG
217
218   // Commit the changes.
219   setUnused(KillRegs);
220   setUsed(DefRegs);
221 }
222
223 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
224   used = RegsAvailable;
225   used.flip();
226   if (includeReserved)
227     used |= ReservedRegs;
228   else
229     used.reset(ReservedRegs);
230 }
231
232 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
233   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
234        I != E; ++I)
235     if (!isAliasUsed(*I)) {
236       DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
237             "\n");
238       return *I;
239     }
240   return 0;
241 }
242
243 /// getRegsAvailable - Return all available registers in the register class
244 /// in Mask.
245 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
246   BitVector Mask(TRI->getNumRegs());
247   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
248        I != E; ++I)
249     if (!isAliasUsed(*I))
250       Mask.set(*I);
251   return Mask;
252 }
253
254 /// findSurvivorReg - Return the candidate register that is unused for the
255 /// longest after StargMII. UseMI is set to the instruction where the search
256 /// stopped.
257 ///
258 /// No more than InstrLimit instructions are inspected.
259 ///
260 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
261                                        BitVector &Candidates,
262                                        unsigned InstrLimit,
263                                        MachineBasicBlock::iterator &UseMI) {
264   int Survivor = Candidates.find_first();
265   assert(Survivor > 0 && "No candidates for scavenging");
266
267   MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
268   assert(StartMI != ME && "MI already at terminator");
269   MachineBasicBlock::iterator RestorePointMI = StartMI;
270   MachineBasicBlock::iterator MI = StartMI;
271
272   bool inVirtLiveRange = false;
273   for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
274     if (MI->isDebugValue()) {
275       ++InstrLimit; // Don't count debug instructions
276       continue;
277     }
278     bool isVirtKillInsn = false;
279     bool isVirtDefInsn = false;
280     // Remove any candidates touched by instruction.
281     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
282       const MachineOperand &MO = MI->getOperand(i);
283       if (MO.isRegMask())
284         Candidates.clearBitsNotInMask(MO.getRegMask());
285       if (!MO.isReg() || MO.isUndef() || !MO.getReg())
286         continue;
287       if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
288         if (MO.isDef())
289           isVirtDefInsn = true;
290         else if (MO.isKill())
291           isVirtKillInsn = true;
292         continue;
293       }
294       Candidates.reset(MO.getReg());
295       for (const uint16_t *R = TRI->getAliasSet(MO.getReg()); *R; R++)
296         Candidates.reset(*R);
297     }
298     // If we're not in a virtual reg's live range, this is a valid
299     // restore point.
300     if (!inVirtLiveRange) RestorePointMI = MI;
301
302     // Update whether we're in the live range of a virtual register
303     if (isVirtKillInsn) inVirtLiveRange = false;
304     if (isVirtDefInsn) inVirtLiveRange = true;
305
306     // Was our survivor untouched by this instruction?
307     if (Candidates.test(Survivor))
308       continue;
309
310     // All candidates gone?
311     if (Candidates.none())
312       break;
313
314     Survivor = Candidates.find_first();
315   }
316   // If we ran off the end, that's where we want to restore.
317   if (MI == ME) RestorePointMI = ME;
318   assert (RestorePointMI != StartMI &&
319           "No available scavenger restore location!");
320
321   // We ran out of candidates, so stop the search.
322   UseMI = RestorePointMI;
323   return Survivor;
324 }
325
326 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
327                                         MachineBasicBlock::iterator I,
328                                         int SPAdj) {
329   // Consider all allocatable registers in the register class initially
330   BitVector Candidates =
331     TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
332
333   // Exclude all the registers being used by the instruction.
334   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
335     MachineOperand &MO = I->getOperand(i);
336     if (MO.isReg() && MO.getReg() != 0 &&
337         !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
338       Candidates.reset(MO.getReg());
339   }
340
341   // Try to find a register that's unused if there is one, as then we won't
342   // have to spill. Search explicitly rather than masking out based on
343   // RegsAvailable, as RegsAvailable does not take aliases into account.
344   // That's what getRegsAvailable() is for.
345   BitVector Available = getRegsAvailable(RC);
346   Available &= Candidates;
347   if (Available.any())
348     Candidates = Available;
349
350   // Find the register whose use is furthest away.
351   MachineBasicBlock::iterator UseMI;
352   unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
353
354   // If we found an unused register there is no reason to spill it.
355   if (!isAliasUsed(SReg)) {
356     DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
357     return SReg;
358   }
359
360   assert(ScavengedReg == 0 &&
361          "Scavenger slot is live, unable to scavenge another register!");
362
363   // Avoid infinite regress
364   ScavengedReg = SReg;
365
366   // If the target knows how to save/restore the register, let it do so;
367   // otherwise, use the emergency stack spill slot.
368   if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
369     // Spill the scavenged register before I.
370     assert(ScavengingFrameIndex >= 0 &&
371            "Cannot scavenge register without an emergency spill slot!");
372     TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI);
373     MachineBasicBlock::iterator II = prior(I);
374     TRI->eliminateFrameIndex(II, SPAdj, this);
375
376     // Restore the scavenged register before its use (or first terminator).
377     TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI);
378     II = prior(UseMI);
379     TRI->eliminateFrameIndex(II, SPAdj, this);
380   }
381
382   ScavengeRestore = prior(UseMI);
383
384   // Doing this here leads to infinite regress.
385   // ScavengedReg = SReg;
386   ScavengedRC = RC;
387
388   DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<
389         "\n");
390
391   return SReg;
392 }