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