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