Use 'static const char' instead of 'static const int'.
[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 RA : public MachineFunctionPass {
46   public:
47     static const char ID;
48     RA() : 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   const char RA::ID = 0;
232 }
233
234 /// getStackSpaceFor - This allocates space for the specified virtual register
235 /// to be held on the stack.
236 int RA::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 RA::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 RA::spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
271                       unsigned VirtReg, unsigned PhysReg) {
272   assert(VirtReg && "Spilling a physical register is illegal!"
273          " Must not have appropriate kill for the register or use exists beyond"
274          " the intended one.");
275   DOUT << "  Spilling register " << RegInfo->getName(PhysReg)
276        << " containing %reg" << VirtReg;
277   if (!isVirtRegModified(VirtReg))
278     DOUT << " which has not been modified, so no store necessary!";
279
280   // Otherwise, there is a virtual register corresponding to this physical
281   // register.  We only need to spill it into its stack slot if it has been
282   // modified.
283   if (isVirtRegModified(VirtReg)) {
284     const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
285     int FrameIndex = getStackSpaceFor(VirtReg, RC);
286     DOUT << " to stack slot #" << FrameIndex;
287     RegInfo->storeRegToStackSlot(MBB, I, PhysReg, FrameIndex, RC);
288     ++NumStores;   // Update statistics
289   }
290
291   getVirt2PhysRegMapSlot(VirtReg) = 0;   // VirtReg no longer available
292
293   DOUT << "\n";
294   removePhysReg(PhysReg);
295 }
296
297
298 /// spillPhysReg - This method spills the specified physical register into the
299 /// virtual register slot associated with it.  If OnlyVirtRegs is set to true,
300 /// then the request is ignored if the physical register does not contain a
301 /// virtual register.
302 ///
303 void RA::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
304                       unsigned PhysReg, bool OnlyVirtRegs) {
305   if (PhysRegsUsed[PhysReg] != -1) {            // Only spill it if it's used!
306     assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
307     if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
308       spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
309   } else {
310     // If the selected register aliases any other registers, we must make
311     // sure that one of the aliases isn't alive.
312     for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
313          *AliasSet; ++AliasSet)
314       if (PhysRegsUsed[*AliasSet] != -1 &&     // Spill aliased register.
315           PhysRegsUsed[*AliasSet] != -2)       // If allocatable.
316         if (PhysRegsUsed[*AliasSet] == 0) {
317           // This must have been a dead def due to something like this:
318           // %EAX :=
319           //      := op %AL
320           // No more use of %EAX, %AH, etc.
321           // %EAX isn't dead upon definition, but %AH is. However %AH isn't
322           // an operand of definition MI so it's not marked as such.
323           DOUT << "  Register " << RegInfo->getName(*AliasSet)
324                << " [%reg" << *AliasSet
325                << "] is never used, removing it frame live list\n";
326           removePhysReg(*AliasSet);
327         } else
328           spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
329   }
330 }
331
332
333 /// assignVirtToPhysReg - This method updates local state so that we know
334 /// that PhysReg is the proper container for VirtReg now.  The physical
335 /// register must not be used for anything else when this is called.
336 ///
337 void RA::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
338   assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
339   // Update information to note the fact that this register was just used, and
340   // it holds VirtReg.
341   PhysRegsUsed[PhysReg] = VirtReg;
342   getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
343   PhysRegsUseOrder.push_back(PhysReg);   // New use of PhysReg
344 }
345
346
347 /// isPhysRegAvailable - Return true if the specified physical register is free
348 /// and available for use.  This also includes checking to see if aliased
349 /// registers are all free...
350 ///
351 bool RA::isPhysRegAvailable(unsigned PhysReg) const {
352   if (PhysRegsUsed[PhysReg] != -1) return false;
353
354   // If the selected register aliases any other allocated registers, it is
355   // not free!
356   for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
357        *AliasSet; ++AliasSet)
358     if (PhysRegsUsed[*AliasSet] != -1) // Aliased register in use?
359       return false;                    // Can't use this reg then.
360   return true;
361 }
362
363
364 /// getFreeReg - Look to see if there is a free register available in the
365 /// specified register class.  If not, return 0.
366 ///
367 unsigned RA::getFreeReg(const TargetRegisterClass *RC) {
368   // Get iterators defining the range of registers that are valid to allocate in
369   // this class, which also specifies the preferred allocation order.
370   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
371   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
372
373   for (; RI != RE; ++RI)
374     if (isPhysRegAvailable(*RI)) {       // Is reg unused?
375       assert(*RI != 0 && "Cannot use register!");
376       return *RI; // Found an unused register!
377     }
378   return 0;
379 }
380
381
382 /// liberatePhysReg - Make sure the specified physical register is available for
383 /// use.  If there is currently a value in it, it is either moved out of the way
384 /// or spilled to memory.
385 ///
386 void RA::liberatePhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
387                          unsigned PhysReg) {
388   spillPhysReg(MBB, I, PhysReg);
389 }
390
391
392 /// getReg - Find a physical register to hold the specified virtual
393 /// register.  If all compatible physical registers are used, this method spills
394 /// the last used virtual register to the stack, and uses that register.
395 ///
396 unsigned RA::getReg(MachineBasicBlock &MBB, MachineInstr *I,
397                     unsigned VirtReg) {
398   const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
399
400   // First check to see if we have a free register of the requested type...
401   unsigned PhysReg = getFreeReg(RC);
402
403   // If we didn't find an unused register, scavenge one now!
404   if (PhysReg == 0) {
405     assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
406
407     // Loop over all of the preallocated registers from the least recently used
408     // to the most recently used.  When we find one that is capable of holding
409     // our register, use it.
410     for (unsigned i = 0; PhysReg == 0; ++i) {
411       assert(i != PhysRegsUseOrder.size() &&
412              "Couldn't find a register of the appropriate class!");
413
414       unsigned R = PhysRegsUseOrder[i];
415
416       // We can only use this register if it holds a virtual register (ie, it
417       // can be spilled).  Do not use it if it is an explicitly allocated
418       // physical register!
419       assert(PhysRegsUsed[R] != -1 &&
420              "PhysReg in PhysRegsUseOrder, but is not allocated?");
421       if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
422         // If the current register is compatible, use it.
423         if (RC->contains(R)) {
424           PhysReg = R;
425           break;
426         } else {
427           // If one of the registers aliased to the current register is
428           // compatible, use it.
429           for (const unsigned *AliasIt = RegInfo->getAliasSet(R);
430                *AliasIt; ++AliasIt) {
431             if (RC->contains(*AliasIt) &&
432                 // If this is pinned down for some reason, don't use it.  For
433                 // example, if CL is pinned, and we run across CH, don't use
434                 // CH as justification for using scavenging ECX (which will
435                 // fail).
436                 PhysRegsUsed[*AliasIt] != 0 &&
437                 
438                 // Make sure the register is allocatable.  Don't allocate SIL on
439                 // x86-32.
440                 PhysRegsUsed[*AliasIt] != -2) {
441               PhysReg = *AliasIt;    // Take an aliased register
442               break;
443             }
444           }
445         }
446       }
447     }
448
449     assert(PhysReg && "Physical register not assigned!?!?");
450
451     // At this point PhysRegsUseOrder[i] is the least recently used register of
452     // compatible register class.  Spill it to memory and reap its remains.
453     spillPhysReg(MBB, I, PhysReg);
454   }
455
456   // Now that we know which register we need to assign this to, do it now!
457   assignVirtToPhysReg(VirtReg, PhysReg);
458   return PhysReg;
459 }
460
461
462 /// reloadVirtReg - This method transforms the specified specified virtual
463 /// register use to refer to a physical register.  This method may do this in
464 /// one of several ways: if the register is available in a physical register
465 /// already, it uses that physical register.  If the value is not in a physical
466 /// register, and if there are physical registers available, it loads it into a
467 /// register.  If register pressure is high, and it is possible, it tries to
468 /// fold the load of the virtual register into the instruction itself.  It
469 /// avoids doing this if register pressure is low to improve the chance that
470 /// subsequent instructions can use the reloaded value.  This method returns the
471 /// modified instruction.
472 ///
473 MachineInstr *RA::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
474                                 unsigned OpNum) {
475   unsigned VirtReg = MI->getOperand(OpNum).getReg();
476
477   // If the virtual register is already available, just update the instruction
478   // and return.
479   if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
480     MarkPhysRegRecentlyUsed(PR);          // Already have this value available!
481     MI->getOperand(OpNum).setReg(PR);  // Assign the input register
482     return MI;
483   }
484
485   // Otherwise, we need to fold it into the current instruction, or reload it.
486   // If we have registers available to hold the value, use them.
487   const TargetRegisterClass *RC = MF->getSSARegMap()->getRegClass(VirtReg);
488   unsigned PhysReg = getFreeReg(RC);
489   int FrameIndex = getStackSpaceFor(VirtReg, RC);
490
491   if (PhysReg) {   // Register is available, allocate it!
492     assignVirtToPhysReg(VirtReg, PhysReg);
493   } else {         // No registers available.
494     // If we can fold this spill into this instruction, do so now.
495     if (MachineInstr* FMI = RegInfo->foldMemoryOperand(MI, OpNum, FrameIndex)){
496       ++NumFolded;
497       // Since we changed the address of MI, make sure to update live variables
498       // to know that the new instruction has the properties of the old one.
499       LV->instructionChanged(MI, FMI);
500       return MBB.insert(MBB.erase(MI), FMI);
501     }
502
503     // It looks like we can't fold this virtual register load into this
504     // instruction.  Force some poor hapless value out of the register file to
505     // make room for the new register, and reload it.
506     PhysReg = getReg(MBB, MI, VirtReg);
507   }
508
509   markVirtRegModified(VirtReg, false);   // Note that this reg was just reloaded
510
511   DOUT << "  Reloading %reg" << VirtReg << " into "
512        << RegInfo->getName(PhysReg) << "\n";
513
514   // Add move instruction(s)
515   RegInfo->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
516   ++NumLoads;    // Update statistics
517
518   MF->setPhysRegUsed(PhysReg);
519   MI->getOperand(OpNum).setReg(PhysReg);  // Assign the input register
520   return MI;
521 }
522
523
524
525 void RA::AllocateBasicBlock(MachineBasicBlock &MBB) {
526   // loop over each instruction
527   MachineBasicBlock::iterator MII = MBB.begin();
528   const TargetInstrInfo &TII = *TM->getInstrInfo();
529   
530   DEBUG(const BasicBlock *LBB = MBB.getBasicBlock();
531         if (LBB) DOUT << "\nStarting RegAlloc of BB: " << LBB->getName());
532
533   // If this is the first basic block in the machine function, add live-in
534   // registers as active.
535   if (&MBB == &*MF->begin()) {
536     for (MachineFunction::livein_iterator I = MF->livein_begin(),
537          E = MF->livein_end(); I != E; ++I) {
538       unsigned Reg = I->first;
539       MF->setPhysRegUsed(Reg);
540       PhysRegsUsed[Reg] = 0;            // It is free and reserved now
541       PhysRegsUseOrder.push_back(Reg);
542       for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
543            *AliasSet; ++AliasSet) {
544         if (PhysRegsUsed[*AliasSet] != -2) {
545           PhysRegsUseOrder.push_back(*AliasSet);
546           PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
547           MF->setPhysRegUsed(*AliasSet);
548         }
549       }
550     }    
551   }
552   
553   // Otherwise, sequentially allocate each instruction in the MBB.
554   while (MII != MBB.end()) {
555     MachineInstr *MI = MII++;
556     const TargetInstrDescriptor &TID = TII.get(MI->getOpcode());
557     DEBUG(DOUT << "\nStarting RegAlloc of: " << *MI;
558           DOUT << "  Regs have values: ";
559           for (unsigned i = 0; i != RegInfo->getNumRegs(); ++i)
560             if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
561                DOUT << "[" << RegInfo->getName(i)
562                     << ",%reg" << PhysRegsUsed[i] << "] ";
563           DOUT << "\n");
564
565     // Loop over the implicit uses, making sure that they are at the head of the
566     // use order list, so they don't get reallocated.
567     if (TID.ImplicitUses) {
568       for (const unsigned *ImplicitUses = TID.ImplicitUses;
569            *ImplicitUses; ++ImplicitUses)
570         MarkPhysRegRecentlyUsed(*ImplicitUses);
571     }
572
573     SmallVector<unsigned, 8> Kills;
574     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
575       MachineOperand& MO = MI->getOperand(i);
576       if (MO.isRegister() && MO.isKill())
577         Kills.push_back(MO.getReg());
578     }
579
580     // Get the used operands into registers.  This has the potential to spill
581     // incoming values if we are out of registers.  Note that we completely
582     // ignore physical register uses here.  We assume that if an explicit
583     // physical register is referenced by the instruction, that it is guaranteed
584     // to be live-in, or the input is badly hosed.
585     //
586     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
587       MachineOperand& MO = MI->getOperand(i);
588       // here we are looking for only used operands (never def&use)
589       if (MO.isRegister() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
590           MRegisterInfo::isVirtualRegister(MO.getReg()))
591         MI = reloadVirtReg(MBB, MI, i);
592     }
593
594     // If this instruction is the last user of this register, kill the
595     // value, freeing the register being used, so it doesn't need to be
596     // spilled to memory.
597     //
598     for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
599       unsigned VirtReg = Kills[i];
600       unsigned PhysReg = VirtReg;
601       if (MRegisterInfo::isVirtualRegister(VirtReg)) {
602         // If the virtual register was never materialized into a register, it
603         // might not be in the map, but it won't hurt to zero it out anyway.
604         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
605         PhysReg = PhysRegSlot;
606         PhysRegSlot = 0;
607       } else if (PhysRegsUsed[PhysReg] == -2) {
608         // Unallocatable register dead, ignore.
609         continue;
610       }
611
612       if (PhysReg) {
613         DOUT << "  Last use of " << RegInfo->getName(PhysReg)
614              << "[%reg" << VirtReg <<"], removing it from live set\n";
615         removePhysReg(PhysReg);
616         for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
617              *AliasSet; ++AliasSet) {
618           if (PhysRegsUsed[*AliasSet] != -2) {
619             DOUT  << "  Last use of "
620                   << RegInfo->getName(*AliasSet)
621                   << "[%reg" << VirtReg <<"], removing it from live set\n";
622             removePhysReg(*AliasSet);
623           }
624         }
625       }
626     }
627
628     // Loop over all of the operands of the instruction, spilling registers that
629     // are defined, and marking explicit destinations in the PhysRegsUsed map.
630     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
631       MachineOperand& MO = MI->getOperand(i);
632       if (MO.isRegister() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
633           MRegisterInfo::isPhysicalRegister(MO.getReg())) {
634         unsigned Reg = MO.getReg();
635         if (PhysRegsUsed[Reg] == -2) continue;  // Something like ESP.
636             
637         MF->setPhysRegUsed(Reg);
638         spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
639         PhysRegsUsed[Reg] = 0;            // It is free and reserved now
640         PhysRegsUseOrder.push_back(Reg);
641         for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
642              *AliasSet; ++AliasSet) {
643           if (PhysRegsUsed[*AliasSet] != -2) {
644             PhysRegsUseOrder.push_back(*AliasSet);
645             PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
646             MF->setPhysRegUsed(*AliasSet);
647           }
648         }
649       }
650     }
651
652     // Loop over the implicit defs, spilling them as well.
653     if (TID.ImplicitDefs) {
654       for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
655            *ImplicitDefs; ++ImplicitDefs) {
656         unsigned Reg = *ImplicitDefs;
657         bool IsNonAllocatable = PhysRegsUsed[Reg] == -2;
658         if (!IsNonAllocatable) {
659           spillPhysReg(MBB, MI, Reg, true);
660           PhysRegsUseOrder.push_back(Reg);
661           PhysRegsUsed[Reg] = 0;            // It is free and reserved now
662         }
663         MF->setPhysRegUsed(Reg);
664
665         for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
666              *AliasSet; ++AliasSet) {
667           if (PhysRegsUsed[*AliasSet] != -2) {
668             if (!IsNonAllocatable) {
669               PhysRegsUseOrder.push_back(*AliasSet);
670               PhysRegsUsed[*AliasSet] = 0;  // It is free and reserved now
671             }
672             MF->setPhysRegUsed(*AliasSet);
673           }
674         }
675       }
676     }
677
678     SmallVector<unsigned, 8> DeadDefs;
679     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
680       MachineOperand& MO = MI->getOperand(i);
681       if (MO.isRegister() && MO.isDead())
682         DeadDefs.push_back(MO.getReg());
683     }
684
685     // Okay, we have allocated all of the source operands and spilled any values
686     // that would be destroyed by defs of this instruction.  Loop over the
687     // explicit defs and assign them to a register, spilling incoming values if
688     // we need to scavenge a register.
689     //
690     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
691       MachineOperand& MO = MI->getOperand(i);
692       if (MO.isRegister() && MO.isDef() && MO.getReg() &&
693           MRegisterInfo::isVirtualRegister(MO.getReg())) {
694         unsigned DestVirtReg = MO.getReg();
695         unsigned DestPhysReg;
696
697         // If DestVirtReg already has a value, use it.
698         if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
699           DestPhysReg = getReg(MBB, MI, DestVirtReg);
700         MF->setPhysRegUsed(DestPhysReg);
701         markVirtRegModified(DestVirtReg);
702         MI->getOperand(i).setReg(DestPhysReg);  // Assign the output register
703       }
704     }
705
706     // If this instruction defines any registers that are immediately dead,
707     // kill them now.
708     //
709     for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
710       unsigned VirtReg = DeadDefs[i];
711       unsigned PhysReg = VirtReg;
712       if (MRegisterInfo::isVirtualRegister(VirtReg)) {
713         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
714         PhysReg = PhysRegSlot;
715         assert(PhysReg != 0);
716         PhysRegSlot = 0;
717       } else if (PhysRegsUsed[PhysReg] == -2) {
718         // Unallocatable register dead, ignore.
719         continue;
720       }
721
722       if (PhysReg) {
723         DOUT  << "  Register " << RegInfo->getName(PhysReg)
724               << " [%reg" << VirtReg
725               << "] is never used, removing it frame live list\n";
726         removePhysReg(PhysReg);
727         for (const unsigned *AliasSet = RegInfo->getAliasSet(PhysReg);
728              *AliasSet; ++AliasSet) {
729           if (PhysRegsUsed[*AliasSet] != -2) {
730             DOUT  << "  Register " << RegInfo->getName(*AliasSet)
731                   << " [%reg" << *AliasSet
732                   << "] is never used, removing it frame live list\n";
733             removePhysReg(*AliasSet);
734           }
735         }
736       }
737     }
738     
739     // Finally, if this is a noop copy instruction, zap it.
740     unsigned SrcReg, DstReg;
741     if (TII.isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg) {
742       LV->removeVirtualRegistersKilled(MI);
743       LV->removeVirtualRegistersDead(MI);
744       MBB.erase(MI);
745     }
746   }
747
748   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
749
750   // Spill all physical registers holding virtual registers now.
751   for (unsigned i = 0, e = RegInfo->getNumRegs(); i != e; ++i)
752     if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
753       if (unsigned VirtReg = PhysRegsUsed[i])
754         spillVirtReg(MBB, MI, VirtReg, i);
755       else
756         removePhysReg(i);
757
758 #if 0
759   // This checking code is very expensive.
760   bool AllOk = true;
761   for (unsigned i = MRegisterInfo::FirstVirtualRegister,
762            e = MF->getSSARegMap()->getLastVirtReg(); i <= e; ++i)
763     if (unsigned PR = Virt2PhysRegMap[i]) {
764       cerr << "Register still mapped: " << i << " -> " << PR << "\n";
765       AllOk = false;
766     }
767   assert(AllOk && "Virtual registers still in phys regs?");
768 #endif
769
770   // Clear any physical register which appear live at the end of the basic
771   // block, but which do not hold any virtual registers.  e.g., the stack
772   // pointer.
773   PhysRegsUseOrder.clear();
774 }
775
776
777 /// runOnMachineFunction - Register allocate the whole function
778 ///
779 bool RA::runOnMachineFunction(MachineFunction &Fn) {
780   DOUT << "Machine Function " << "\n";
781   MF = &Fn;
782   TM = &Fn.getTarget();
783   RegInfo = TM->getRegisterInfo();
784   LV = &getAnalysis<LiveVariables>();
785
786   PhysRegsUsed.assign(RegInfo->getNumRegs(), -1);
787   
788   // At various places we want to efficiently check to see whether a register
789   // is allocatable.  To handle this, we mark all unallocatable registers as
790   // being pinned down, permanently.
791   {
792     BitVector Allocable = RegInfo->getAllocatableSet(Fn);
793     for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
794       if (!Allocable[i])
795         PhysRegsUsed[i] = -2;  // Mark the reg unallocable.
796   }
797
798   // initialize the virtual->physical register map to have a 'null'
799   // mapping for all virtual registers
800   Virt2PhysRegMap.grow(MF->getSSARegMap()->getLastVirtReg());
801
802   // Loop over all of the basic blocks, eliminating virtual register references
803   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
804        MBB != MBBe; ++MBB)
805     AllocateBasicBlock(*MBB);
806
807   StackSlotForVirtReg.clear();
808   PhysRegsUsed.clear();
809   VirtRegModified.clear();
810   Virt2PhysRegMap.clear();
811   return true;
812 }
813
814 FunctionPass *llvm::createLocalRegisterAllocator() {
815   return new RA();
816 }