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