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