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