Rename FunctionFrameInfo to MachineFrameInfo
[oota-llvm.git] / lib / CodeGen / RegAllocLocal.cpp
1 //===-- RegAllocLocal.cpp - A BasicBlock generic register allocator -------===//
2 //
3 // This register allocator allocates registers to a basic block at a time,
4 // attempting to keep values in registers and reusing registers as appropriate.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/CodeGen/MachineFunctionPass.h"
9 #include "llvm/CodeGen/MachineInstr.h"
10 #include "llvm/CodeGen/SSARegMap.h"
11 #include "llvm/CodeGen/MachineFrameInfo.h"
12 #include "llvm/Target/MachineInstrInfo.h"
13 #include "llvm/Target/TargetMachine.h"
14 #include "Support/Statistic.h"
15 #include "Support/CommandLine.h"
16 #include <iostream>
17 #include <set>
18
19 namespace {
20   Statistic<> NumSpilled ("ra-local", "Number of registers spilled");
21   Statistic<> NumReloaded("ra-local", "Number of registers reloaded");
22   cl::opt<bool> DisableKill("no-kill", cl::Hidden, 
23                             cl::desc("Disable register kill in local-ra"));
24
25   class RA : public MachineFunctionPass {
26     const TargetMachine *TM;
27     MachineFunction *MF;
28     const MRegisterInfo *RegInfo;
29
30     // StackSlotForVirtReg - Maps SSA Regs => frame index where these values are
31     // spilled
32     std::map<unsigned, int> StackSlotForVirtReg;
33
34     // Virt2PhysRegMap - This map contains entries for each virtual register
35     // that is currently available in a physical register.
36     //
37     std::map<unsigned, unsigned> Virt2PhysRegMap;
38     
39     // PhysRegsUsed - This map contains entries for each physical register that
40     // currently has a value (ie, it is in Virt2PhysRegMap).  The value mapped
41     // to is the virtual register corresponding to the physical register (the
42     // inverse of the Virt2PhysRegMap), or 0.  The value is set to 0 if this
43     // register is pinned because it is used by a future instruction.
44     //
45     std::map<unsigned, unsigned> PhysRegsUsed;
46
47     // PhysRegsUseOrder - This contains a list of the physical registers that
48     // currently have a virtual register value in them.  This list provides an
49     // ordering of registers, imposing a reallocation order.  This list is only
50     // used if all registers are allocated and we have to spill one, in which
51     // case we spill the least recently used register.  Entries at the front of
52     // the list are the least recently used registers, entries at the back are
53     // the most recently used.
54     //
55     std::vector<unsigned> PhysRegsUseOrder;
56
57     // LastUserOf map - This multimap contains the set of registers that each
58     // key instruction is the last user of.  If an instruction has an entry in
59     // this map, that means that the specified operands are killed after the 
60     // instruction is executed, thus they don't need to be spilled into memory
61     //
62     std::multimap<MachineInstr*, unsigned> LastUserOf;
63
64     void MarkPhysRegRecentlyUsed(unsigned Reg) {
65       assert(!PhysRegsUseOrder.empty() && "No registers used!");
66       if (PhysRegsUseOrder.back() == Reg) return;  // Already most recently used
67
68       for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
69         if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
70           unsigned RegMatch = PhysRegsUseOrder[i-1];       // remove from middle
71           PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
72           // Add it to the end of the list
73           PhysRegsUseOrder.push_back(RegMatch);
74           if (RegMatch == Reg) 
75             return;    // Found an exact match, exit early
76         }
77     }
78
79   public:
80     virtual const char *getPassName() const {
81       return "Local Register Allocator";
82     }
83
84   private:
85     /// runOnMachineFunction - Register allocate the whole function
86     bool runOnMachineFunction(MachineFunction &Fn);
87
88     /// AllocateBasicBlock - Register allocate the specified basic block.
89     void AllocateBasicBlock(MachineBasicBlock &MBB);
90
91     /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
92     /// in predecessor basic blocks.
93     void EliminatePHINodes(MachineBasicBlock &MBB);
94
95     /// CalculateLastUseOfVReg - Calculate an approximation of the killing
96     /// uses for the virtual registers in the function.  Here we try to capture
97     /// registers that are defined and only used within the same basic block.
98     /// Because we don't have use-def chains yet, we have to do this the hard
99     /// way.
100     ///
101     void CalculateLastUseOfVReg(MachineBasicBlock &MBB,
102                         std::map<unsigned, MachineInstr*> &LastUseOfVReg) const;
103
104
105     /// areRegsEqual - This method returns true if the specified registers are
106     /// related to each other.  To do this, it checks to see if they are equal
107     /// or if the first register is in the alias set of the second register.
108     ///
109     bool areRegsEqual(unsigned R1, unsigned R2) const {
110       if (R1 == R2) return true;
111       if (const unsigned *AliasSet = RegInfo->getAliasSet(R2))
112         for (unsigned i = 0; AliasSet[i]; ++i)
113           if (AliasSet[i] == R1) return true;
114       return false;
115     }
116
117     /// getStackSpaceFor - This returns the frame index of the specified virtual
118     /// register on the stack, allocating space if neccesary.
119     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
120
121     void removePhysReg(unsigned PhysReg);
122
123     /// spillVirtReg - This method spills the value specified by PhysReg into
124     /// the virtual register slot specified by VirtReg.  It then updates the RA
125     /// data structures to indicate the fact that PhysReg is now available.
126     ///
127     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
128                       unsigned VirtReg, unsigned PhysReg);
129
130     /// spillPhysReg - This method spills the specified physical register into
131     /// the virtual register slot associated with it.
132     //
133     void spillPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
134                       unsigned PhysReg) {
135       std::map<unsigned, unsigned>::iterator PI = PhysRegsUsed.find(PhysReg);
136       if (PI != PhysRegsUsed.end()) {             // Only spill it if it's used!
137         spillVirtReg(MBB, I, PI->second, PhysReg);
138       } else if (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg)) {
139         // If the selected register aliases any other registers, we must make
140         // sure that one of the aliases isn't alive...
141         for (unsigned i = 0; AliasSet[i]; ++i) {
142           PI = PhysRegsUsed.find(AliasSet[i]);
143           if (PI != PhysRegsUsed.end())     // Spill aliased register...
144             spillVirtReg(MBB, I, PI->second, AliasSet[i]);
145         }
146       }
147     }
148
149     void AssignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
150
151     /// isPhysRegAvailable - Return true if the specified physical register is
152     /// free and available for use.  This also includes checking to see if
153     /// aliased registers are all free...
154     ///
155     bool isPhysRegAvailable(unsigned PhysReg) const;
156     
157     /// getFreeReg - Find a physical register to hold the specified virtual
158     /// register.  If all compatible physical registers are used, this method
159     /// spills the last used virtual register to the stack, and uses that
160     /// register.
161     ///
162     unsigned getFreeReg(MachineBasicBlock &MBB,
163                         MachineBasicBlock::iterator &I,
164                         unsigned virtualReg);
165
166     /// reloadVirtReg - This method loads the specified virtual register into a
167     /// physical register, returning the physical register chosen.  This updates
168     /// the regalloc data structures to reflect the fact that the virtual reg is
169     /// now alive in a physical register, and the previous one isn't.
170     ///
171     unsigned reloadVirtReg(MachineBasicBlock &MBB,
172                            MachineBasicBlock::iterator &I, unsigned VirtReg);
173   };
174 }
175
176
177 /// getStackSpaceFor - This allocates space for the specified virtual
178 /// register to be held on the stack.
179 int RA::getStackSpaceFor(unsigned VirtReg,
180                               const TargetRegisterClass *RC) {
181   // Find the location VirtReg would belong...
182   std::map<unsigned, int>::iterator I =
183     StackSlotForVirtReg.lower_bound(VirtReg);
184
185   if (I != StackSlotForVirtReg.end() && I->first == VirtReg)
186     return I->second;          // Already has space allocated?
187
188   // Allocate a new stack object for this spill location...
189   int FrameIdx =
190     MF->getFrameInfo()->CreateStackObject(RC->getSize(), RC->getAlignment());
191
192   // Assign the slot...
193   StackSlotForVirtReg.insert(I, std::make_pair(VirtReg, FrameIdx));
194   return FrameIdx;
195 }
196
197
198 /// removePhysReg - This method marks the specified physical register as no 
199 /// longer being in use.
200 ///
201 void RA::removePhysReg(unsigned PhysReg) {
202   PhysRegsUsed.erase(PhysReg);      // PhyReg no longer used
203
204   std::vector<unsigned>::iterator It =
205     std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
206   assert(It != PhysRegsUseOrder.end() &&
207          "Spilled a physical register, but it was not in use list!");
208   PhysRegsUseOrder.erase(It);
209 }
210
211 /// spillVirtReg - This method spills the value specified by PhysReg into the
212 /// virtual register slot specified by VirtReg.  It then updates the RA data
213 /// structures to indicate the fact that PhysReg is now available.
214 ///
215 void RA::spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
216                       unsigned VirtReg, unsigned PhysReg) {
217   // If this is just a marker register, we don't need to spill it.
218   if (VirtReg != 0) {
219     const TargetRegisterClass *RegClass =
220       MF->getSSARegMap()->getRegClass(VirtReg);
221     int FrameIndex = getStackSpaceFor(VirtReg, RegClass);
222
223     // Add move instruction(s)
224     RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RegClass);
225     ++NumSpilled;   // Update statistics
226     Virt2PhysRegMap.erase(VirtReg);   // VirtReg no longer available
227   }
228
229   removePhysReg(PhysReg);
230 }
231
232
233 /// isPhysRegAvailable - Return true if the specified physical register is free
234 /// and available for use.  This also includes checking to see if aliased
235 /// registers are all free...
236 ///
237 bool RA::isPhysRegAvailable(unsigned PhysReg) const {
238   if (PhysRegsUsed.count(PhysReg)) return false;
239
240   // If the selected register aliases any other allocated registers, it is
241   // not free!
242   if (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg))
243     for (unsigned i = 0; AliasSet[i]; ++i)
244       if (PhysRegsUsed.count(AliasSet[i])) // Aliased register in use?
245         return false;                      // Can't use this reg then.
246   return true;
247 }
248
249
250
251 /// getFreeReg - Find a physical register to hold the specified virtual
252 /// register.  If all compatible physical registers are used, this method spills
253 /// the last used virtual register to the stack, and uses that register.
254 ///
255 unsigned RA::getFreeReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
256                         unsigned VirtReg) {
257   const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
258
259   // Get iterators defining the range of registers that are valid to allocate in
260   // this class, which also specifies the preferred allocation order.
261   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
262   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
263
264   // First check to see if we have a free register of the requested type...
265   unsigned PhysReg = 0;
266   for (; RI != RE; ++RI) {
267     unsigned R = *RI;
268     if (isPhysRegAvailable(R)) {       // Is reg unused?
269       // Found an unused register!
270       PhysReg = R;
271       assert(PhysReg != 0 && "Cannot use register!");
272       break;
273     }
274   }
275
276   // If we didn't find an unused register, scavenge one now!
277   if (PhysReg == 0) {
278     assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
279
280     // Loop over all of the preallocated registers from the least recently used
281     // to the most recently used.  When we find one that is capable of holding
282     // our register, use it.
283     for (unsigned i = 0; PhysReg == 0; ++i) {
284       assert(i != PhysRegsUseOrder.size() &&
285              "Couldn't find a register of the appropriate class!");
286       
287       unsigned R = PhysRegsUseOrder[i];
288       // If the current register is compatible, use it.
289       if (RegInfo->getRegClass(R) == RC) {
290         PhysReg = R;
291         break;
292       } else {
293         // If one of the registers aliased to the current register is
294         // compatible, use it.
295         if (const unsigned *AliasSet = RegInfo->getAliasSet(R))
296           for (unsigned a = 0; AliasSet[a]; ++a)
297             if (RegInfo->getRegClass(AliasSet[a]) == RC) {
298               PhysReg = AliasSet[a];    // Take an aliased register
299               break;
300             }
301       }
302     }
303
304     assert(PhysReg && "Physical register not assigned!?!?");
305
306     // At this point PhysRegsUseOrder[i] is the least recently used register of
307     // compatible register class.  Spill it to memory and reap its remains.
308     spillPhysReg(MBB, I, PhysReg);
309   }
310
311   // Now that we know which register we need to assign this to, do it now!
312   AssignVirtToPhysReg(VirtReg, PhysReg);
313   return PhysReg;
314 }
315
316
317 void RA::AssignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
318   assert(PhysRegsUsed.find(PhysReg) == PhysRegsUsed.end() &&
319          "Phys reg already assigned!");
320   // Update information to note the fact that this register was just used, and
321   // it holds VirtReg.
322   PhysRegsUsed[PhysReg] = VirtReg;
323   Virt2PhysRegMap[VirtReg] = PhysReg;
324   PhysRegsUseOrder.push_back(PhysReg);   // New use of PhysReg
325 }
326
327
328 /// reloadVirtReg - This method loads the specified virtual register into a
329 /// physical register, returning the physical register chosen.  This updates the
330 /// regalloc data structures to reflect the fact that the virtual reg is now
331 /// alive in a physical register, and the previous one isn't.
332 ///
333 unsigned RA::reloadVirtReg(MachineBasicBlock &MBB,
334                            MachineBasicBlock::iterator &I,
335                            unsigned VirtReg) {
336   std::map<unsigned, unsigned>::iterator It = Virt2PhysRegMap.find(VirtReg);
337   if (It != Virt2PhysRegMap.end()) {
338     MarkPhysRegRecentlyUsed(It->second);
339     return It->second;               // Already have this value available!
340   }
341
342   unsigned PhysReg = getFreeReg(MBB, I, VirtReg);
343
344   const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
345   int FrameIndex = getStackSpaceFor(VirtReg, RC);
346
347   // Add move instruction(s)
348   RegInfo->loadRegFromStackSlot(MBB, I, PhysReg, FrameIndex, RC);
349   ++NumReloaded;    // Update statistics
350   return PhysReg;
351 }
352
353 /// CalculateLastUseOfVReg - Calculate an approximation of the killing uses for
354 /// the virtual registers in the function.  Here we try to capture registers 
355 /// that are defined and only used within the same basic block.  Because we 
356 /// don't have use-def chains yet, we have to do this the hard way.
357 ///
358 void RA::CalculateLastUseOfVReg(MachineBasicBlock &MBB, 
359                       std::map<unsigned, MachineInstr*> &LastUseOfVReg) const {
360   // Calculate the last machine instruction in this basic block that uses the
361   // specified virtual register defined in this basic block.
362   std::map<unsigned, MachineInstr*> LastLocalUses;
363
364   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;++I){
365     MachineInstr *MI = *I;
366     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
367       MachineOperand &Op = MI->getOperand(i);
368       if (Op.isVirtualRegister()) {
369         if (Op.opIsDef()) {   // Definition of a new virtual reg?
370           LastLocalUses[Op.getAllocatedRegNum()] = 0;  // Record it
371         } else {              // Use of a virtual reg.
372           std::map<unsigned, MachineInstr*>::iterator It = 
373                                LastLocalUses.find(Op.getAllocatedRegNum());
374           if (It != LastLocalUses.end())  // Local use?
375             It->second = MI;              // Update last use
376           else
377             LastUseOfVReg[Op.getAllocatedRegNum()] = 0;
378         }
379       }
380     }
381   }
382
383   // Move local uses over... if there are any uses of a local already in the 
384   // lastuse map, the newly inserted entry is ignored.
385   LastUseOfVReg.insert(LastLocalUses.begin(), LastLocalUses.end());
386 }
387  
388
389 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
390 /// predecessor basic blocks.
391 ///
392 void RA::EliminatePHINodes(MachineBasicBlock &MBB) {
393   const MachineInstrInfo &MII = TM->getInstrInfo();
394
395   while (MBB.front()->getOpcode() == MachineInstrInfo::PHI) {
396     MachineInstr *MI = MBB.front();
397     // Unlink the PHI node from the basic block... but don't delete the PHI yet
398     MBB.erase(MBB.begin());
399     
400     assert(MI->getOperand(0).isVirtualRegister() &&
401            "PHI node doesn't write virt reg?");
402
403     unsigned virtualReg = MI->getOperand(0).getAllocatedRegNum();
404     
405     for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
406       MachineOperand &opVal = MI->getOperand(i-1);
407       
408       // Get the MachineBasicBlock equivalent of the BasicBlock that is the
409       // source path the phi
410       MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
411
412       // Check to make sure we haven't already emitted the copy for this block.
413       // This can happen because PHI nodes may have multiple entries for the
414       // same basic block.  It doesn't matter which entry we use though, because
415       // all incoming values are guaranteed to be the same for a particular bb.
416       //
417       // Note that this is N^2 in the number of phi node entries, but since the
418       // # of entries is tiny, this is not a problem.
419       //
420       bool HaveNotEmitted = true;
421       for (int op = MI->getNumOperands() - 1; op != i; op -= 2)
422         if (&opBlock == MI->getOperand(op).getMachineBasicBlock()) {
423           HaveNotEmitted = false;
424           break;
425         }
426
427       if (HaveNotEmitted) {
428         MachineBasicBlock::iterator opI = opBlock.end();
429         MachineInstr *opMI = *--opI;
430         
431         // must backtrack over ALL the branches in the previous block
432         while (MII.isBranch(opMI->getOpcode()) && opI != opBlock.begin())
433           opMI = *--opI;
434         
435         // move back to the first branch instruction so new instructions
436         // are inserted right in front of it and not in front of a non-branch
437         if (!MII.isBranch(opMI->getOpcode()))
438           ++opI;
439
440         const TargetRegisterClass *RC =
441           MF->getSSARegMap()->getRegClass(virtualReg);
442
443         assert(opVal.isVirtualRegister() &&
444                "Machine PHI Operands must all be virtual registers!");
445         RegInfo->copyRegToReg(opBlock, opI, virtualReg, opVal.getReg(), RC);
446       }
447     }
448     
449     // really delete the PHI instruction now!
450     delete MI;
451   }
452 }
453
454
455 void RA::AllocateBasicBlock(MachineBasicBlock &MBB) {
456   // loop over each instruction
457   MachineBasicBlock::iterator I = MBB.begin();
458   for (; I != MBB.end(); ++I) {
459     MachineInstr *MI = *I;
460     const MachineInstrDescriptor &MID = TM->getInstrInfo().get(MI->getOpcode());
461
462     // Loop over all of the operands of the instruction, spilling registers that
463     // are defined, and marking explicit destinations in the PhysRegsUsed map.
464
465     // FIXME: We don't need to spill a register if this is the last use of the
466     // value!
467     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
468       if (MI->getOperand(i).opIsDef() &&
469           MI->getOperand(i).isPhysicalRegister()) {
470         unsigned Reg = MI->getOperand(i).getAllocatedRegNum();
471         spillPhysReg(MBB, I, Reg);
472         PhysRegsUsed[Reg] = 0;            // It is free and reserved now
473         PhysRegsUseOrder.push_back(Reg);
474       }
475
476     // Loop over the implicit defs, spilling them, as above.
477     if (const unsigned *ImplicitDefs = MID.ImplicitDefs)
478       for (unsigned i = 0; ImplicitDefs[i]; ++i) {
479         unsigned Reg = ImplicitDefs[i];
480
481         // We don't want to spill implicit definitions if they were explicitly
482         // chosen.  For this reason, check to see now if the register we are
483         // to spill has a vreg of 0.
484         if (PhysRegsUsed.count(Reg) && PhysRegsUsed[Reg] != 0)
485           spillPhysReg(MBB, I, Reg);
486         else if (PhysRegsUsed.count(Reg)) {
487           // Remove the entry from PhysRegsUseOrder to avoid having two entries!
488           removePhysReg(Reg);
489         }
490         PhysRegsUseOrder.push_back(Reg);
491         PhysRegsUsed[Reg] = 0;            // It is free and reserved now
492       }
493
494     // Loop over the implicit uses, making sure that they are at the head of the
495     // use order list, so they don't get reallocated.
496     if (const unsigned *ImplicitUses = MID.ImplicitUses)
497       for (unsigned i = 0; ImplicitUses[i]; ++i)
498         MarkPhysRegRecentlyUsed(ImplicitUses[i]);
499
500     // Loop over all of the operands again, getting the used operands into
501     // registers.  This has the potiential to spill incoming values if we are
502     // out of registers.
503     //
504     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
505       if (MI->getOperand(i).opIsUse() &&
506           MI->getOperand(i).isVirtualRegister()) {
507         unsigned VirtSrcReg = MI->getOperand(i).getAllocatedRegNum();
508         unsigned PhysSrcReg = reloadVirtReg(MBB, I, VirtSrcReg);
509         MI->SetMachineOperandReg(i, PhysSrcReg);  // Assign the input register
510       }
511     
512     // Okay, we have allocated all of the source operands and spilled any values
513     // that would be destroyed by defs of this instruction.  Loop over the
514     // implicit defs and assign them to a register, spilling the incoming value
515     // if we need to scavange a register.
516     //
517     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
518       if (MI->getOperand(i).opIsDef() &&
519           !MI->getOperand(i).isPhysicalRegister()) {
520         unsigned DestVirtReg = MI->getOperand(i).getAllocatedRegNum();
521         unsigned DestPhysReg;
522
523         if (TM->getInstrInfo().isTwoAddrInstr(MI->getOpcode()) && i == 0) {
524           // must be same register number as the first operand
525           // This maps a = b + c into b += c, and saves b into a's spot
526           assert(MI->getOperand(1).isRegister()  &&
527                  MI->getOperand(1).getAllocatedRegNum() &&
528                  MI->getOperand(1).opIsUse() &&
529                  "Two address instruction invalid!");
530           DestPhysReg = MI->getOperand(1).getAllocatedRegNum();
531
532           // Spill the incoming value, because we are about to change the
533           // register contents.
534           spillPhysReg(MBB, I, DestPhysReg);
535           AssignVirtToPhysReg(DestVirtReg, DestPhysReg);
536         } else {
537           DestPhysReg = getFreeReg(MBB, I, DestVirtReg);
538         }
539         MI->SetMachineOperandReg(i, DestPhysReg);  // Assign the output register
540       }
541
542     if (!DisableKill) {
543       // If this instruction is the last user of anything in registers, kill the
544       // value, freeing the register being used, so it doesn't need to be
545       // spilled to memory at the end of the block.
546       std::multimap<MachineInstr*, unsigned>::iterator LUOI = 
547              LastUserOf.lower_bound(MI);
548       for (; LUOI != LastUserOf.end() && LUOI->first == MI; ++MI) {
549         unsigned VirtReg = LUOI->second;                       // entry found?
550         unsigned PhysReg = Virt2PhysRegMap[VirtReg];
551         if (PhysReg) {
552           DEBUG(std::cout << "V: " << VirtReg << " P: " << PhysReg
553                           << " Last use of: " << *MI);
554           removePhysReg(PhysReg);
555         }
556         Virt2PhysRegMap.erase(VirtReg);
557       }
558     }
559   }
560
561   // Rewind the iterator to point to the first flow control instruction...
562   const MachineInstrInfo &MII = TM->getInstrInfo();
563   I = MBB.end();
564   do {
565     --I;
566   } while ((MII.isReturn((*I)->getOpcode()) ||
567             MII.isBranch((*I)->getOpcode())) && I != MBB.begin());
568            
569   if (!MII.isReturn((*I)->getOpcode()) && !MII.isBranch((*I)->getOpcode()))
570     ++I;
571
572   // Spill all physical registers holding virtual registers now.
573   while (!PhysRegsUsed.empty())
574     spillVirtReg(MBB, I, PhysRegsUsed.begin()->second,
575                  PhysRegsUsed.begin()->first);
576
577   assert(Virt2PhysRegMap.empty() && "Virtual registers still in phys regs?");
578   assert(PhysRegsUseOrder.empty() && "Physical regs still allocated?");
579 }
580
581
582 /// runOnMachineFunction - Register allocate the whole function
583 ///
584 bool RA::runOnMachineFunction(MachineFunction &Fn) {
585   DEBUG(std::cerr << "Machine Function " << "\n");
586   MF = &Fn;
587   TM = &Fn.getTarget();
588   RegInfo = TM->getRegisterInfo();
589
590   // First pass: eliminate PHI instructions by inserting copies into predecessor
591   // blocks, and calculate a simple approximation of killing uses for virtual 
592   // registers.
593   //
594   std::map<unsigned, MachineInstr*> LastUseOfVReg;
595   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
596        MBB != MBBe; ++MBB) {
597     if (!DisableKill)
598       CalculateLastUseOfVReg(*MBB, LastUseOfVReg);
599     EliminatePHINodes(*MBB);
600   }
601
602   // At this point LastUseOfVReg has been filled in to contain the last 
603   // MachineInstr user of the specified virtual register, if that user is 
604   // within the same basic block as the definition (otherwise it contains
605   // null).  Invert this mapping now:
606   if (!DisableKill)
607     for (std::map<unsigned, MachineInstr*>::iterator I = LastUseOfVReg.begin(),
608          E = LastUseOfVReg.end(); I != E; ++I)
609       if (I->second)
610         LastUserOf.insert(std::make_pair(I->second, I->first));
611
612   // We're done with the temporary list now.
613   LastUseOfVReg.clear();
614
615   // Loop over all of the basic blocks, eliminating virtual register references
616   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
617        MBB != MBBe; ++MBB)
618     AllocateBasicBlock(*MBB);
619
620   LastUserOf.clear();
621   StackSlotForVirtReg.clear();
622   return true;
623 }
624
625 Pass *createLocalRegisterAllocator() {
626   return new RA();
627 }