Reduce number of exported symbols
[oota-llvm.git] / lib / CodeGen / RegAllocLocal.cpp
1 //===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This register allocator allocates registers to a basic block at a time,
11 // attempting to keep values in registers and reusing registers as appropriate.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regalloc"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/SSARegMap.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Visibility.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/Statistic.h"
29 #include <algorithm>
30 #include <iostream>
31 using namespace llvm;
32
33 namespace {
34   static Statistic<> NumStores("ra-local", "Number of stores added");
35   static Statistic<> NumLoads ("ra-local", "Number of loads added");
36   static Statistic<> NumFolded("ra-local", "Number of loads/stores folded into "
37                                "instructions");
38   class VISIBILITY_HIDDEN RA : public MachineFunctionPass {
39     const TargetMachine *TM;
40     MachineFunction *MF;
41     const MRegisterInfo *RegInfo;
42     LiveVariables *LV;
43     bool *PhysRegsEverUsed;
44
45     // StackSlotForVirtReg - Maps virtual regs to the frame index where these
46     // values are spilled.
47     std::map<unsigned, int> StackSlotForVirtReg;
48
49     // Virt2PhysRegMap - This map contains entries for each virtual register
50     // that is currently available in a physical register.
51     DenseMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
52
53     unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
54       return Virt2PhysRegMap[VirtReg];
55     }
56
57     // PhysRegsUsed - This array is effectively a map, containing entries for
58     // each physical register that currently has a value (ie, it is in
59     // Virt2PhysRegMap).  The value mapped to is the virtual register
60     // corresponding to the physical register (the inverse of the
61     // Virt2PhysRegMap), or 0.  The value is set to 0 if this register is pinned
62     // because it is used by a future instruction.  If the entry for a physical
63     // register is -1, then the physical register is "not in the map".
64     //
65     std::vector<int> PhysRegsUsed;
66
67     // PhysRegsUseOrder - This contains a list of the physical registers that
68     // currently have a virtual register value in them.  This list provides an
69     // ordering of registers, imposing a reallocation order.  This list is only
70     // used if all registers are allocated and we have to spill one, in which
71     // case we spill the least recently used register.  Entries at the front of
72     // the list are the least recently used registers, entries at the back are
73     // the most recently used.
74     //
75     std::vector<unsigned> PhysRegsUseOrder;
76
77     // VirtRegModified - This bitset contains information about which virtual
78     // registers need to be spilled back to memory when their registers are
79     // scavenged.  If a virtual register has simply been rematerialized, there
80     // is no reason to spill it to memory when we need the register back.
81     //
82     std::vector<bool> VirtRegModified;
83
84     void markVirtRegModified(unsigned Reg, bool Val = true) {
85       assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
86       Reg -= MRegisterInfo::FirstVirtualRegister;
87       if (VirtRegModified.size() <= Reg) VirtRegModified.resize(Reg+1);
88       VirtRegModified[Reg] = Val;
89     }
90
91     bool isVirtRegModified(unsigned Reg) const {
92       assert(MRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
93       assert(Reg - MRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
94              && "Illegal virtual register!");
95       return VirtRegModified[Reg - MRegisterInfo::FirstVirtualRegister];
96     }
97
98     void MarkPhysRegRecentlyUsed(unsigned Reg) {
99       if(PhysRegsUseOrder.empty() ||
100          PhysRegsUseOrder.back() == Reg) return;  // Already most recently used
101
102       for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
103         if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
104           unsigned RegMatch = PhysRegsUseOrder[i-1];       // remove from middle
105           PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
106           // Add it to the end of the list
107           PhysRegsUseOrder.push_back(RegMatch);
108           if (RegMatch == Reg)
109             return;    // Found an exact match, exit early
110         }
111     }
112
113   public:
114     virtual const char *getPassName() const {
115       return "Local Register Allocator";
116     }
117
118     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
119       AU.addRequired<LiveVariables>();
120       AU.addRequiredID(PHIEliminationID);
121       AU.addRequiredID(TwoAddressInstructionPassID);
122       MachineFunctionPass::getAnalysisUsage(AU);
123     }
124
125   private:
126     /// runOnMachineFunction - Register allocate the whole function
127     bool runOnMachineFunction(MachineFunction &Fn);
128
129     /// AllocateBasicBlock - Register allocate the specified basic block.
130     void AllocateBasicBlock(MachineBasicBlock &MBB);
131
132
133     /// areRegsEqual - This method returns true if the specified registers are
134     /// related to each other.  To do this, it checks to see if they are equal
135     /// or if the first register is in the alias set of the second register.
136     ///
137     bool areRegsEqual(unsigned R1, unsigned R2) const {
138       if (R1 == R2) return true;
139       for (const unsigned *AliasSet = RegInfo->getAliasSet(R2);
140            *AliasSet; ++AliasSet) {
141         if (*AliasSet == R1) return true;
142       }
143       return false;
144     }
145
146     /// getStackSpaceFor - This returns the frame index of the specified virtual
147     /// register on the stack, allocating space if necessary.
148     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
149
150     /// removePhysReg - This method marks the specified physical register as no
151     /// longer being in use.
152     ///
153     void removePhysReg(unsigned PhysReg);
154
155     /// spillVirtReg - This method spills the value specified by PhysReg into
156     /// the virtual register slot specified by VirtReg.  It then updates the RA
157     /// data structures to indicate the fact that PhysReg is now available.
158     ///
159     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
160                       unsigned VirtReg, unsigned PhysReg);
161
162     /// spillPhysReg - This method spills the specified physical register into
163     /// the virtual register slot associated with it.  If OnlyVirtRegs is set to
164     /// true, then the request is ignored if the physical register does not
165     /// contain a virtual register.
166     ///
167     void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
168                       unsigned PhysReg, bool OnlyVirtRegs = false);
169
170     /// assignVirtToPhysReg - This method updates local state so that we know
171     /// that PhysReg is the proper container for VirtReg now.  The physical
172     /// register must not be used for anything else when this is called.
173     ///
174     void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
175
176     /// liberatePhysReg - Make sure the specified physical register is available
177     /// for use.  If there is currently a value in it, it is either moved out of
178     /// the way or spilled to memory.
179     ///
180     void liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
181                          unsigned PhysReg);
182
183     /// isPhysRegAvailable - Return true if the specified physical register is
184     /// free and available for use.  This also includes checking to see if
185     /// aliased registers are all free...
186     ///
187     bool isPhysRegAvailable(unsigned PhysReg) const;
188
189     /// getFreeReg - Look to see if there is a free register available in the
190     /// specified register class.  If not, return 0.
191     ///
192     unsigned getFreeReg(const TargetRegisterClass *RC);
193
194     /// getReg - Find a physical register to hold the specified virtual
195     /// register.  If all compatible physical registers are used, this method
196     /// spills the last used virtual register to the stack, and uses that
197     /// register.
198     ///
199     unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
200                     unsigned VirtReg);
201
202     /// reloadVirtReg - This method transforms the specified specified virtual
203     /// register use to refer to a physical register.  This method may do this
204     /// in one of several ways: if the register is available in a physical
205     /// register already, it uses that physical register.  If the value is not
206     /// in a physical register, and if there are physical registers available,
207     /// it loads it into a register.  If register pressure is high, and it is
208     /// possible, it tries to fold the load of the virtual register into the
209     /// instruction itself.  It avoids doing this if register pressure is low to
210     /// improve the chance that subsequent instructions can use the reloaded
211     /// value.  This method returns the modified instruction.
212     ///
213     MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
214                                 unsigned OpNum);
215
216
217     void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
218                        unsigned PhysReg);
219   };
220 }
221
222 /// getStackSpaceFor - This allocates space for the specified virtual register
223 /// to be held on the stack.
224 int RA::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
225   // Find the location Reg would belong...
226   std::map<unsigned, int>::iterator I =StackSlotForVirtReg.lower_bound(VirtReg);
227
228   if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
229     return I->second;          // Already has space allocated?
230
231   // Allocate a new stack object for this spill location...
232   int FrameIdx = MF->getFrameInfo()->CreateStackObject(RC->getSize(),
233                                                        RC->getAlignment());
234
235   // Assign the slot...
236   StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
237   return FrameIdx;
238 }
239
240
241 /// removePhysReg - This method marks the specified physical register as no
242 /// longer being in use.
243 ///
244 void RA::removePhysReg(unsigned PhysReg) {
245   PhysRegsUsed[PhysReg] = -1;      // PhyReg no longer used
246
247   std::vector<unsigned>::iterator It =
248     std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
249   if (It != PhysRegsUseOrder.end())
250     PhysRegsUseOrder.erase(It);
251 }
252
253
254 /// spillVirtReg - This method spills the value specified by PhysReg into the
255 /// virtual register slot specified by VirtReg.  It then updates the RA data
256 /// structures to indicate the fact that PhysReg is now available.
257 ///
258 void RA::spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
259                       unsigned VirtReg, unsigned PhysReg) {
260   assert(VirtReg && "Spilling a physical register is illegal!"
261          " Must not have appropriate kill for the register or use exists beyond"
262          " the intended one.");
263   DEBUG(std::cerr << "  Spilling register " << RegInfo->getName(PhysReg);
264         std::cerr << " containing %reg" << VirtReg;
265         if (!isVirtRegModified(VirtReg))
266         std::cerr << " which has not been modified, so no store necessary!");
267
268   // Otherwise, there is a virtual register corresponding to this physical
269   // register.  We only need to spill it into its stack slot if it has been
270   // modified.
271   if (isVirtRegModified(VirtReg)) {
272     const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
273     int FrameIndex = getStackSpaceFor(VirtReg, RC);
274     DEBUG(std::cerr << " to stack slot #" << FrameIndex);
275     RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RC);
276     ++NumStores;   // Update statistics
277   }
278
279   getVirt2PhysRegMapSlot(VirtReg) = 0;   // VirtReg no longer available
280
281   DEBUG(std::cerr << "\n");
282   removePhysReg(PhysReg);
283 }
284
285
286 /// spillPhysReg - This method spills the specified physical register into the
287 /// virtual register slot associated with it.  If OnlyVirtRegs is set to true,
288 /// then the request is ignored if the physical register does not contain a
289 /// virtual register.
290 ///
291 void RA::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
292                       unsigned PhysReg, bool OnlyVirtRegs) {
293   if (PhysRegsUsed[PhysReg] != -1) {            // Only spill it if it's used!
294     if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
295       spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
296   } else {
297     // If the selected register aliases any other registers, we must make
298     // sure that one of the aliases isn't alive...
299     for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
300          *AliasSet; ++AliasSet)
301       if (PhysRegsUsed[*AliasSet] != -1)     // Spill aliased register...
302         if (PhysRegsUsed[*AliasSet] || !OnlyVirtRegs)
303           spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
304   }
305 }
306
307
308 /// assignVirtToPhysReg - This method updates local state so that we know
309 /// that PhysReg is the proper container for VirtReg now.  The physical
310 /// register must not be used for anything else when this is called.
311 ///
312 void RA::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
313   assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
314   // Update information to note the fact that this register was just used, and
315   // it holds VirtReg.
316   PhysRegsUsed[PhysReg] = VirtReg;
317   getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
318   PhysRegsUseOrder.push_back(PhysReg);   // New use of PhysReg
319 }
320
321
322 /// isPhysRegAvailable - Return true if the specified physical register is free
323 /// and available for use.  This also includes checking to see if aliased
324 /// registers are all free...
325 ///
326 bool RA::isPhysRegAvailable(unsigned PhysReg) const {
327   if (PhysRegsUsed[PhysReg] != -1) return false;
328
329   // If the selected register aliases any other allocated registers, it is
330   // not free!
331   for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
332        *AliasSet; ++AliasSet)
333     if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
334       return false;                    // Can't use this reg then.
335   return true;
336 }
337
338
339 /// getFreeReg - Look to see if there is a free register available in the
340 /// specified register class.  If not, return 0.
341 ///
342 unsigned RA::getFreeReg(const TargetRegisterClass *RC) {
343   // Get iterators defining the range of registers that are valid to allocate in
344   // this class, which also specifies the preferred allocation order.
345   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
346   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
347
348   for (; RI != RE; ++RI)
349     if (isPhysRegAvailable(*RI)) {       // Is reg unused?
350       assert(*RI != 0 && "Cannot use register!");
351       return *RI; // Found an unused register!
352     }
353   return 0;
354 }
355
356
357 /// liberatePhysReg - Make sure the specified physical register is available for
358 /// use.  If there is currently a value in it, it is either moved out of the way
359 /// or spilled to memory.
360 ///
361 void RA::liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
362                          unsigned PhysReg) {
363   spillPhysReg(MBB, I, PhysReg);
364 }
365
366
367 /// getReg - Find a physical register to hold the specified virtual
368 /// register.  If all compatible physical registers are used, this method spills
369 /// the last used virtual register to the stack, and uses that register.
370 ///
371 unsigned RA::getReg(MachineBasicBlock &MBB, MachineInstr *I,
372                     unsigned VirtReg) {
373   const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
374
375   // First check to see if we have a free register of the requested type...
376   unsigned PhysReg = getFreeReg(RC);
377
378   // If we didn't find an unused register, scavenge one now!
379   if (PhysReg == 0) {
380     assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
381
382     // Loop over all of the preallocated registers from the least recently used
383     // to the most recently used.  When we find one that is capable of holding
384     // our register, use it.
385     for (unsigned i = 0; PhysReg == 0; ++i) {
386       assert(i != PhysRegsUseOrder.size() &&
387              "Couldn't find a register of the appropriate class!");
388
389       unsigned R = PhysRegsUseOrder[i];
390
391       // We can only use this register if it holds a virtual register (ie, it
392       // can be spilled).  Do not use it if it is an explicitly allocated
393       // physical register!
394       assert(PhysRegsUsed[R] != -1 &&
395              "PhysReg in PhysRegsUseOrder, but is not allocated?");
396       if (PhysRegsUsed[R]) {
397         // If the current register is compatible, use it.
398         if (RC->contains(R)) {
399           PhysReg = R;
400           break;
401         } else {
402           // If one of the registers aliased to the current register is
403           // compatible, use it.
404           for (const unsigned *AliasSet = RegInfo->getAliasSet(R);
405                *AliasSet; ++AliasSet) {
406             if (RC->contains(*AliasSet)) {
407               PhysReg = *AliasSet;    // Take an aliased register
408               break;
409             }
410           }
411         }
412       }
413     }
414
415     assert(PhysReg && "Physical register not assigned!?!?");
416
417     // At this point PhysRegsUseOrder[i] is the least recently used register of
418     // compatible register class.  Spill it to memory and reap its remains.
419     spillPhysReg(MBB, I, PhysReg);
420   }
421
422   // Now that we know which register we need to assign this to, do it now!
423   assignVirtToPhysReg(VirtReg, PhysReg);
424   return PhysReg;
425 }
426
427
428 /// reloadVirtReg - This method transforms the specified specified virtual
429 /// register use to refer to a physical register.  This method may do this in
430 /// one of several ways: if the register is available in a physical register
431 /// already, it uses that physical register.  If the value is not in a physical
432 /// register, and if there are physical registers available, it loads it into a
433 /// register.  If register pressure is high, and it is possible, it tries to
434 /// fold the load of the virtual register into the instruction itself.  It
435 /// avoids doing this if register pressure is low to improve the chance that
436 /// subsequent instructions can use the reloaded value.  This method returns the
437 /// modified instruction.
438 ///
439 MachineInstr *RA::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
440                                 unsigned OpNum) {
441   unsigned VirtReg = MI->getOperand(OpNum).getReg();
442
443   // If the virtual register is already available, just update the instruction
444   // and return.
445   if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
446     MarkPhysRegRecentlyUsed(PR);          // Already have this value available!
447     MI->getOperand(OpNum).setReg(PR);  // Assign the input register
448     return MI;
449   }
450
451   // Otherwise, we need to fold it into the current instruction, or reload it.
452   // If we have registers available to hold the value, use them.
453   const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
454   unsigned PhysReg = getFreeReg(RC);
455   int FrameIndex = getStackSpaceFor(VirtReg, RC);
456
457   if (PhysReg) {   // Register is available, allocate it!
458     assignVirtToPhysReg(VirtReg, PhysReg);
459   } else {         // No registers available.
460     // If we can fold this spill into this instruction, do so now.
461     if (MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, OpNum, FrameIndex)){
462       ++NumFolded;
463       // Since we changed the address of MI, make sure to update live variables
464       // to know that the new instruction has the properties of the old one.
465       LV->instructionChanged(MI, FMI);
466       return MBB.insert(MBB.erase(MI), FMI);
467     }
468
469     // It looks like we can't fold this virtual register load into this
470     // instruction.  Force some poor hapless value out of the register file to
471     // make room for the new register, and reload it.
472     PhysReg = getReg(MBB, MI, VirtReg);
473   }
474
475   markVirtRegModified(VirtReg, false);   // Note that this reg was just reloaded
476
477   DEBUG(std::cerr << "  Reloading %reg" << VirtReg << " into "
478                   << RegInfo->getName(PhysReg) << "\n");
479
480   // Add move instruction(s)
481   RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
482   ++NumLoads;    // Update statistics
483
484   PhysRegsEverUsed[PhysReg] = true;
485   MI->getOperand(OpNum).setReg(PhysReg);  // Assign the input register
486   return MI;
487 }
488
489
490
491 void RA::AllocateBasicBlock(MachineBasicBlock &MBB) {
492   // loop over each instruction
493   MachineBasicBlock::iterator MII = MBB.begin();
494   const TargetInstrInfo &TII = *TM->getInstrInfo();
495   
496   // If this is the first basic block in the machine function, add live-in
497   // registers as active.
498   if (&MBB == &*MF->begin()) {
499     for (MachineFunction::livein_iterator I = MF->livein_begin(),
500          E = MF->livein_end(); I != E; ++I) {
501       unsigned Reg = I->first;
502       PhysRegsEverUsed[Reg] = true;
503       PhysRegsUsed[Reg] = 0;            // It is free and reserved now
504       PhysRegsUseOrder.push_back(Reg);
505       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
506            *AliasSet; ++AliasSet) {
507         PhysRegsUseOrder.push_back(*AliasSet);
508         PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
509         PhysRegsEverUsed[*AliasSet] = true;
510       }
511     }    
512   }
513   
514   // Otherwise, sequentially allocate each instruction in the MBB.
515   while (MII != MBB.end()) {
516     MachineInstr *MI = MII++;
517     const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
518     DEBUG(std::cerr << "\nStarting RegAlloc of: " << *MI;
519           std::cerr << "  Regs have values: ";
520           for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
521             if (PhysRegsUsed[i] != -1)
522                std::cerr << "[" << RegInfo->getName(i)
523                          << ",%reg" << PhysRegsUsed[i] << "] ";
524           std::cerr << "\n");
525
526     // Loop over the implicit uses, making sure that they are at the head of the
527     // use order list, so they don't get reallocated.
528     for (const unsigned *ImplicitUses = TID.ImplicitUses;
529          *ImplicitUses; ++ImplicitUses)
530       MarkPhysRegRecentlyUsed(*ImplicitUses);
531
532     // Get the used operands into registers.  This has the potential to spill
533     // incoming values if we are out of registers.  Note that we completely
534     // ignore physical register uses here.  We assume that if an explicit
535     // physical register is referenced by the instruction, that it is guaranteed
536     // to be live-in, or the input is badly hosed.
537     //
538     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
539       MachineOperand& MO = MI->getOperand(i);
540       // here we are looking for only used operands (never def&use)
541       if (!MO.isDef() && MO.isRegister() && MO.getReg() &&
542           MRegisterInfo::isVirtualRegister(MO.getReg()))
543         MI = reloadVirtReg(MBB, MI, i);
544     }
545
546     // If this instruction is the last user of anything in registers, kill the
547     // value, freeing the register being used, so it doesn't need to be
548     // spilled to memory.
549     //
550     for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
551            KE = LV->killed_end(MI); KI != KE; ++KI) {
552       unsigned VirtReg = *KI;
553       unsigned PhysReg = VirtReg;
554       if (MRegisterInfo::isVirtualRegister(VirtReg)) {
555         // If the virtual register was never materialized into a register, it
556         // might not be in the map, but it won't hurt to zero it out anyway.
557         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
558         PhysReg = PhysRegSlot;
559         PhysRegSlot = 0;
560       }
561
562       if (PhysReg) {
563         DEBUG(std::cerr << "  Last use of " << RegInfo->getName(PhysReg)
564               << "[%reg" << VirtReg <<"], removing it from live set\n");
565         removePhysReg(PhysReg);
566       }
567     }
568
569     // Loop over all of the operands of the instruction, spilling registers that
570     // are defined, and marking explicit destinations in the PhysRegsUsed map.
571     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
572       MachineOperand& MO = MI->getOperand(i);
573       if (MO.isDef() && MO.isRegister() && MO.getReg() &&
574           MRegisterInfo::isPhysicalRegister(MO.getReg())) {
575         unsigned Reg = MO.getReg();
576         PhysRegsEverUsed[Reg] = true;
577         spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in the reg
578         PhysRegsUsed[Reg] = 0;            // It is free and reserved now
579         PhysRegsUseOrder.push_back(Reg);
580         for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
581              *AliasSet; ++AliasSet) {
582           PhysRegsUseOrder.push_back(*AliasSet);
583           PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
584           PhysRegsEverUsed[*AliasSet] = true;
585         }
586       }
587     }
588
589     // Loop over the implicit defs, spilling them as well.
590     for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
591          *ImplicitDefs; ++ImplicitDefs) {
592       unsigned Reg = *ImplicitDefs;
593       spillPhysReg(MBB, MI, Reg, true);
594       PhysRegsUseOrder.push_back(Reg);
595       PhysRegsUsed[Reg] = 0;            // It is free and reserved now
596       PhysRegsEverUsed[Reg] = true;
597
598       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
599            *AliasSet; ++AliasSet) {
600         PhysRegsUseOrder.push_back(*AliasSet);
601         PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
602         PhysRegsEverUsed[*AliasSet] = true;
603       }
604     }
605
606     // Okay, we have allocated all of the source operands and spilled any values
607     // that would be destroyed by defs of this instruction.  Loop over the
608     // explicit defs and assign them to a register, spilling incoming values if
609     // we need to scavenge a register.
610     //
611     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
612       MachineOperand& MO = MI->getOperand(i);
613       if (MO.isDef() && MO.isRegister() && MO.getReg() &&
614           MRegisterInfo::isVirtualRegister(MO.getReg())) {
615         unsigned DestVirtReg = MO.getReg();
616         unsigned DestPhysReg;
617
618         // If DestVirtReg already has a value, use it.
619         if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
620           DestPhysReg = getReg(MBB, MI, DestVirtReg);
621         PhysRegsEverUsed[DestPhysReg] = true;
622         markVirtRegModified(DestVirtReg);
623         MI->getOperand(i).setReg(DestPhysReg);  // Assign the output register
624       }
625     }
626
627     // If this instruction defines any registers that are immediately dead,
628     // kill them now.
629     //
630     for (LiveVariables::killed_iterator KI = LV->dead_begin(MI),
631            KE = LV->dead_end(MI); KI != KE; ++KI) {
632       unsigned VirtReg = *KI;
633       unsigned PhysReg = VirtReg;
634       if (MRegisterInfo::isVirtualRegister(VirtReg)) {
635         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
636         PhysReg = PhysRegSlot;
637         assert(PhysReg != 0);
638         PhysRegSlot = 0;
639       }
640
641       if (PhysReg) {
642         DEBUG(std::cerr << "  Register " << RegInfo->getName(PhysReg)
643               << " [%reg" << VirtReg
644               << "] is never used, removing it frame live list\n");
645         removePhysReg(PhysReg);
646       }
647     }
648     
649     // Finally, if this is a noop copy instruction, zap it.
650     unsigned SrcReg, DstReg;
651     if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg)
652       MBB.erase(MI);
653   }
654
655   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
656
657   // Spill all physical registers holding virtual registers now.
658   for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
659     if (PhysRegsUsed[i] != -1)
660       if (unsigned VirtReg = PhysRegsUsed[i])
661         spillVirtReg(MBB, MI, VirtReg, i);
662       else
663         removePhysReg(i);
664
665 #if 0
666   // This checking code is very expensive.
667   bool AllOk = true;
668   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
669            e = MF->getSSARegMap()->getLastVirtReg(); i <= e; ++i)
670     if (unsigned PR = Virt2PhysRegMap[i]) {
671       std::cerr << "Register still mapped: " << i << " -> " << PR << "\n";
672       AllOk = false;
673     }
674   assert(AllOk && "Virtual registers still in phys regs?");
675 #endif
676
677   // Clear any physical register which appear live at the end of the basic
678   // block, but which do not hold any virtual registers.  e.g., the stack
679   // pointer.
680   PhysRegsUseOrder.clear();
681 }
682
683
684 /// runOnMachineFunction - Register allocate the whole function
685 ///
686 bool RA::runOnMachineFunction(MachineFunction &Fn) {
687   DEBUG(std::cerr << "Machine Function " << "\n");
688   MF = &Fn;
689   TM = &Fn.getTarget();
690   RegInfo = TM->getRegisterInfo();
691   LV = &getAnalysis<LiveVariables>();
692
693   PhysRegsEverUsed = new bool[RegInfo->getNumRegs()];
694   std::fill(PhysRegsEverUsed, PhysRegsEverUsed+RegInfo->getNumRegs(), false);
695   Fn.setUsedPhysRegs(PhysRegsEverUsed);
696
697   PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
698
699   // initialize the virtual->physical register map to have a 'null'
700   // mapping for all virtual registers
701   Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
702
703   // Loop over all of the basic blocks, eliminating virtual register references
704   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
705        MBB != MBBe; ++MBB)
706     AllocateBasicBlock(*MBB);
707
708   StackSlotForVirtReg.clear();
709   PhysRegsUsed.clear();
710   VirtRegModified.clear();
711   Virt2PhysRegMap.clear();
712   return true;
713 }
714
715 FunctionPass *llvm::createLocalRegisterAllocator() {
716   return new RA();
717 }