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