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