Ignore DBG_VALUE in a couple more places.
[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 is distributed under the University of Illinois Open Source
6 // 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/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/IndexedMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include <algorithm>
36 using namespace llvm;
37
38 STATISTIC(NumStores, "Number of stores added");
39 STATISTIC(NumLoads , "Number of loads added");
40
41 static RegisterRegAlloc
42   localRegAlloc("local", "local register allocator",
43                 createLocalRegisterAllocator);
44
45 namespace {
46   class RALocal : public MachineFunctionPass {
47   public:
48     static char ID;
49     RALocal() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1) {}
50   private:
51     const TargetMachine *TM;
52     MachineFunction *MF;
53     const TargetRegisterInfo *TRI;
54     const TargetInstrInfo *TII;
55
56     // StackSlotForVirtReg - Maps virtual regs to the frame index where these
57     // values are spilled.
58     IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
59
60     // Virt2PhysRegMap - This map contains entries for each virtual register
61     // that is currently available in a physical register.
62     IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2PhysRegMap;
63
64     unsigned &getVirt2PhysRegMapSlot(unsigned VirtReg) {
65       return Virt2PhysRegMap[VirtReg];
66     }
67
68     // PhysRegsUsed - This array is effectively a map, containing entries for
69     // each physical register that currently has a value (ie, it is in
70     // Virt2PhysRegMap).  The value mapped to is the virtual register
71     // corresponding to the physical register (the inverse of the
72     // Virt2PhysRegMap), or 0.  The value is set to 0 if this register is pinned
73     // because it is used by a future instruction, and to -2 if it is not
74     // allocatable.  If the entry for a physical register is -1, then the
75     // physical register is "not in the map".
76     //
77     std::vector<int> PhysRegsUsed;
78
79     // PhysRegsUseOrder - This contains a list of the physical registers that
80     // currently have a virtual register value in them.  This list provides an
81     // ordering of registers, imposing a reallocation order.  This list is only
82     // used if all registers are allocated and we have to spill one, in which
83     // case we spill the least recently used register.  Entries at the front of
84     // the list are the least recently used registers, entries at the back are
85     // the most recently used.
86     //
87     std::vector<unsigned> PhysRegsUseOrder;
88
89     // Virt2LastUseMap - This maps each virtual register to its last use
90     // (MachineInstr*, operand index pair).
91     IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
92     Virt2LastUseMap;
93
94     std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
95       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
96       return Virt2LastUseMap[Reg];
97     }
98
99     // VirtRegModified - This bitset contains information about which virtual
100     // registers need to be spilled back to memory when their registers are
101     // scavenged.  If a virtual register has simply been rematerialized, there
102     // is no reason to spill it to memory when we need the register back.
103     //
104     BitVector VirtRegModified;
105     
106     // UsedInMultipleBlocks - Tracks whether a particular register is used in
107     // more than one block.
108     BitVector UsedInMultipleBlocks;
109
110     void markVirtRegModified(unsigned Reg, bool Val = true) {
111       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
112       Reg -= TargetRegisterInfo::FirstVirtualRegister;
113       if (Val)
114         VirtRegModified.set(Reg);
115       else
116         VirtRegModified.reset(Reg);
117     }
118
119     bool isVirtRegModified(unsigned Reg) const {
120       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
121       assert(Reg - TargetRegisterInfo::FirstVirtualRegister < VirtRegModified.size()
122              && "Illegal virtual register!");
123       return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
124     }
125
126     void AddToPhysRegsUseOrder(unsigned Reg) {
127       std::vector<unsigned>::iterator It =
128         std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), Reg);
129       if (It != PhysRegsUseOrder.end())
130         PhysRegsUseOrder.erase(It);
131       PhysRegsUseOrder.push_back(Reg);
132     }
133
134     void MarkPhysRegRecentlyUsed(unsigned Reg) {
135       if (PhysRegsUseOrder.empty() ||
136           PhysRegsUseOrder.back() == Reg) return;  // Already most recently used
137
138       for (unsigned i = PhysRegsUseOrder.size(); i != 0; --i)
139         if (areRegsEqual(Reg, PhysRegsUseOrder[i-1])) {
140           unsigned RegMatch = PhysRegsUseOrder[i-1];       // remove from middle
141           PhysRegsUseOrder.erase(PhysRegsUseOrder.begin()+i-1);
142           // Add it to the end of the list
143           PhysRegsUseOrder.push_back(RegMatch);
144           if (RegMatch == Reg)
145             return;    // Found an exact match, exit early
146         }
147     }
148
149   public:
150     virtual const char *getPassName() const {
151       return "Local Register Allocator";
152     }
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.setPreservesCFG();
156       AU.addRequiredID(PHIEliminationID);
157       AU.addRequiredID(TwoAddressInstructionPassID);
158       MachineFunctionPass::getAnalysisUsage(AU);
159     }
160
161   private:
162     /// runOnMachineFunction - Register allocate the whole function
163     bool runOnMachineFunction(MachineFunction &Fn);
164
165     /// AllocateBasicBlock - Register allocate the specified basic block.
166     void AllocateBasicBlock(MachineBasicBlock &MBB);
167
168
169     /// areRegsEqual - This method returns true if the specified registers are
170     /// related to each other.  To do this, it checks to see if they are equal
171     /// or if the first register is in the alias set of the second register.
172     ///
173     bool areRegsEqual(unsigned R1, unsigned R2) const {
174       if (R1 == R2) return true;
175       for (const unsigned *AliasSet = TRI->getAliasSet(R2);
176            *AliasSet; ++AliasSet) {
177         if (*AliasSet == R1) return true;
178       }
179       return false;
180     }
181
182     /// getStackSpaceFor - This returns the frame index of the specified virtual
183     /// register on the stack, allocating space if necessary.
184     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
185
186     /// removePhysReg - This method marks the specified physical register as no
187     /// longer being in use.
188     ///
189     void removePhysReg(unsigned PhysReg);
190
191     /// spillVirtReg - This method spills the value specified by PhysReg into
192     /// the virtual register slot specified by VirtReg.  It then updates the RA
193     /// data structures to indicate the fact that PhysReg is now available.
194     ///
195     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
196                       unsigned VirtReg, unsigned PhysReg);
197
198     /// spillPhysReg - This method spills the specified physical register into
199     /// the virtual register slot associated with it.  If OnlyVirtRegs is set to
200     /// true, then the request is ignored if the physical register does not
201     /// contain a virtual register.
202     ///
203     void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
204                       unsigned PhysReg, bool OnlyVirtRegs = false);
205
206     /// assignVirtToPhysReg - This method updates local state so that we know
207     /// that PhysReg is the proper container for VirtReg now.  The physical
208     /// register must not be used for anything else when this is called.
209     ///
210     void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
211
212     /// isPhysRegAvailable - Return true if the specified physical register is
213     /// free and available for use.  This also includes checking to see if
214     /// aliased registers are all free...
215     ///
216     bool isPhysRegAvailable(unsigned PhysReg) const;
217
218     /// getFreeReg - Look to see if there is a free register available in the
219     /// specified register class.  If not, return 0.
220     ///
221     unsigned getFreeReg(const TargetRegisterClass *RC);
222
223     /// getReg - Find a physical register to hold the specified virtual
224     /// register.  If all compatible physical registers are used, this method
225     /// spills the last used virtual register to the stack, and uses that
226     /// register. If NoFree is true, that means the caller knows there isn't
227     /// a free register, do not call getFreeReg().
228     unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
229                     unsigned VirtReg, bool NoFree = false);
230
231     /// reloadVirtReg - This method transforms the specified virtual
232     /// register use to refer to a physical register.  This method may do this
233     /// in one of several ways: if the register is available in a physical
234     /// register already, it uses that physical register.  If the value is not
235     /// in a physical register, and if there are physical registers available,
236     /// it loads it into a register: PhysReg if that is an available physical
237     /// register, otherwise any physical register of the right class.
238     /// If register pressure is high, and it is possible, it tries to fold the
239     /// load of the virtual register into the instruction itself.  It avoids
240     /// doing this if register pressure is low to improve the chance that
241     /// subsequent instructions can use the reloaded value.  This method
242     /// returns the modified instruction.
243     ///
244     MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
245                                 unsigned OpNum, SmallSet<unsigned, 4> &RRegs,
246                                 unsigned PhysReg);
247
248     /// ComputeLocalLiveness - Computes liveness of registers within a basic
249     /// block, setting the killed/dead flags as appropriate.
250     void ComputeLocalLiveness(MachineBasicBlock& MBB);
251
252     void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
253                        unsigned PhysReg);
254   };
255   char RALocal::ID = 0;
256 }
257
258 /// getStackSpaceFor - This allocates space for the specified virtual register
259 /// to be held on the stack.
260 int RALocal::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
261   // Find the location Reg would belong...
262   int SS = StackSlotForVirtReg[VirtReg];
263   if (SS != -1)
264     return SS;          // Already has space allocated?
265
266   // Allocate a new stack object for this spill location...
267   int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
268                                                             RC->getAlignment());
269
270   // Assign the slot...
271   StackSlotForVirtReg[VirtReg] = FrameIdx;
272   return FrameIdx;
273 }
274
275
276 /// removePhysReg - This method marks the specified physical register as no
277 /// longer being in use.
278 ///
279 void RALocal::removePhysReg(unsigned PhysReg) {
280   PhysRegsUsed[PhysReg] = -1;      // PhyReg no longer used
281
282   std::vector<unsigned>::iterator It =
283     std::find(PhysRegsUseOrder.begin(), PhysRegsUseOrder.end(), PhysReg);
284   if (It != PhysRegsUseOrder.end())
285     PhysRegsUseOrder.erase(It);
286 }
287
288
289 /// spillVirtReg - This method spills the value specified by PhysReg into the
290 /// virtual register slot specified by VirtReg.  It then updates the RA data
291 /// structures to indicate the fact that PhysReg is now available.
292 ///
293 void RALocal::spillVirtReg(MachineBasicBlock &MBB,
294                            MachineBasicBlock::iterator I,
295                            unsigned VirtReg, unsigned PhysReg) {
296   assert(VirtReg && "Spilling a physical register is illegal!"
297          " Must not have appropriate kill for the register or use exists beyond"
298          " the intended one.");
299   DEBUG(dbgs() << "  Spilling register " << TRI->getName(PhysReg)
300                << " containing %reg" << VirtReg);
301   
302   if (!isVirtRegModified(VirtReg)) {
303     DEBUG(dbgs() << " which has not been modified, so no store necessary!");
304     std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
305     if (LastUse.first)
306       LastUse.first->getOperand(LastUse.second).setIsKill();
307   } else {
308     // Otherwise, there is a virtual register corresponding to this physical
309     // register.  We only need to spill it into its stack slot if it has been
310     // modified.
311     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
312     int FrameIndex = getStackSpaceFor(VirtReg, RC);
313     DEBUG(dbgs() << " to stack slot #" << FrameIndex);
314     // If the instruction reads the register that's spilled, (e.g. this can
315     // happen if it is a move to a physical register), then the spill
316     // instruction is not a kill.
317     bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
318     TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC);
319     ++NumStores;   // Update statistics
320   }
321
322   getVirt2PhysRegMapSlot(VirtReg) = 0;   // VirtReg no longer available
323
324   DEBUG(dbgs() << '\n');
325   removePhysReg(PhysReg);
326 }
327
328
329 /// spillPhysReg - This method spills the specified physical register into the
330 /// virtual register slot associated with it.  If OnlyVirtRegs is set to true,
331 /// then the request is ignored if the physical register does not contain a
332 /// virtual register.
333 ///
334 void RALocal::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
335                            unsigned PhysReg, bool OnlyVirtRegs) {
336   if (PhysRegsUsed[PhysReg] != -1) {            // Only spill it if it's used!
337     assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
338     if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
339       spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
340   } else {
341     // If the selected register aliases any other registers, we must make
342     // sure that one of the aliases isn't alive.
343     for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
344          *AliasSet; ++AliasSet)
345       if (PhysRegsUsed[*AliasSet] != -1 &&     // Spill aliased register.
346           PhysRegsUsed[*AliasSet] != -2)       // If allocatable.
347           if (PhysRegsUsed[*AliasSet])
348             spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
349   }
350 }
351
352
353 /// assignVirtToPhysReg - This method updates local state so that we know
354 /// that PhysReg is the proper container for VirtReg now.  The physical
355 /// register must not be used for anything else when this is called.
356 ///
357 void RALocal::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
358   assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
359   // Update information to note the fact that this register was just used, and
360   // it holds VirtReg.
361   PhysRegsUsed[PhysReg] = VirtReg;
362   getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
363   AddToPhysRegsUseOrder(PhysReg);   // New use of PhysReg
364 }
365
366
367 /// isPhysRegAvailable - Return true if the specified physical register is free
368 /// and available for use.  This also includes checking to see if aliased
369 /// registers are all free...
370 ///
371 bool RALocal::isPhysRegAvailable(unsigned PhysReg) const {
372   if (PhysRegsUsed[PhysReg] != -1) return false;
373
374   // If the selected register aliases any other allocated registers, it is
375   // not free!
376   for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
377        *AliasSet; ++AliasSet)
378     if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
379       return false;                    // Can't use this reg then.
380   return true;
381 }
382
383
384 /// getFreeReg - Look to see if there is a free register available in the
385 /// specified register class.  If not, return 0.
386 ///
387 unsigned RALocal::getFreeReg(const TargetRegisterClass *RC) {
388   // Get iterators defining the range of registers that are valid to allocate in
389   // this class, which also specifies the preferred allocation order.
390   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
391   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
392
393   for (; RI != RE; ++RI)
394     if (isPhysRegAvailable(*RI)) {       // Is reg unused?
395       assert(*RI != 0 && "Cannot use register!");
396       return *RI; // Found an unused register!
397     }
398   return 0;
399 }
400
401
402 /// getReg - Find a physical register to hold the specified virtual
403 /// register.  If all compatible physical registers are used, this method spills
404 /// the last used virtual register to the stack, and uses that register.
405 ///
406 unsigned RALocal::getReg(MachineBasicBlock &MBB, MachineInstr *I,
407                          unsigned VirtReg, bool NoFree) {
408   const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
409
410   // First check to see if we have a free register of the requested type...
411   unsigned PhysReg = NoFree ? 0 : getFreeReg(RC);
412
413   // If we didn't find an unused register, scavenge one now!
414   if (PhysReg == 0) {
415     assert(!PhysRegsUseOrder.empty() && "No allocated registers??");
416
417     // Loop over all of the preallocated registers from the least recently used
418     // to the most recently used.  When we find one that is capable of holding
419     // our register, use it.
420     for (unsigned i = 0; PhysReg == 0; ++i) {
421       assert(i != PhysRegsUseOrder.size() &&
422              "Couldn't find a register of the appropriate class!");
423
424       unsigned R = PhysRegsUseOrder[i];
425
426       // We can only use this register if it holds a virtual register (ie, it
427       // can be spilled).  Do not use it if it is an explicitly allocated
428       // physical register!
429       assert(PhysRegsUsed[R] != -1 &&
430              "PhysReg in PhysRegsUseOrder, but is not allocated?");
431       if (PhysRegsUsed[R] && PhysRegsUsed[R] != -2) {
432         // If the current register is compatible, use it.
433         if (RC->contains(R)) {
434           PhysReg = R;
435           break;
436         } else {
437           // If one of the registers aliased to the current register is
438           // compatible, use it.
439           for (const unsigned *AliasIt = TRI->getAliasSet(R);
440                *AliasIt; ++AliasIt) {
441             if (RC->contains(*AliasIt) &&
442                 // If this is pinned down for some reason, don't use it.  For
443                 // example, if CL is pinned, and we run across CH, don't use
444                 // CH as justification for using scavenging ECX (which will
445                 // fail).
446                 PhysRegsUsed[*AliasIt] != 0 &&
447                 
448                 // Make sure the register is allocatable.  Don't allocate SIL on
449                 // x86-32.
450                 PhysRegsUsed[*AliasIt] != -2) {
451               PhysReg = *AliasIt;    // Take an aliased register
452               break;
453             }
454           }
455         }
456       }
457     }
458
459     assert(PhysReg && "Physical register not assigned!?!?");
460
461     // At this point PhysRegsUseOrder[i] is the least recently used register of
462     // compatible register class.  Spill it to memory and reap its remains.
463     spillPhysReg(MBB, I, PhysReg);
464   }
465
466   // Now that we know which register we need to assign this to, do it now!
467   assignVirtToPhysReg(VirtReg, PhysReg);
468   return PhysReg;
469 }
470
471
472 /// reloadVirtReg - This method transforms the specified virtual
473 /// register use to refer to a physical register.  This method may do this in
474 /// one of several ways: if the register is available in a physical register
475 /// already, it uses that physical register.  If the value is not in a physical
476 /// register, and if there are physical registers available, it loads it into a
477 /// register: PhysReg if that is an available physical register, otherwise any
478 /// register.  If register pressure is high, and it is possible, it tries to
479 /// fold the load of the virtual register into the instruction itself.  It
480 /// avoids doing this if register pressure is low to improve the chance that
481 /// subsequent instructions can use the reloaded value.  This method returns
482 /// the modified instruction.
483 ///
484 MachineInstr *RALocal::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
485                                      unsigned OpNum,
486                                      SmallSet<unsigned, 4> &ReloadedRegs,
487                                      unsigned PhysReg) {
488   unsigned VirtReg = MI->getOperand(OpNum).getReg();
489
490   // If the virtual register is already available, just update the instruction
491   // and return.
492   if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
493     MarkPhysRegRecentlyUsed(PR);       // Already have this value available!
494     MI->getOperand(OpNum).setReg(PR);  // Assign the input register
495     if (!MI->isDebugValue())
496       getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
497     return MI;
498   }
499
500   // Otherwise, we need to fold it into the current instruction, or reload it.
501   // If we have registers available to hold the value, use them.
502   const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
503   // If we already have a PhysReg (this happens when the instruction is a
504   // reg-to-reg copy with a PhysReg destination) use that.
505   if (!PhysReg || !TargetRegisterInfo::isPhysicalRegister(PhysReg) ||
506       !isPhysRegAvailable(PhysReg))
507     PhysReg = getFreeReg(RC);
508   int FrameIndex = getStackSpaceFor(VirtReg, RC);
509
510   if (PhysReg) {   // Register is available, allocate it!
511     assignVirtToPhysReg(VirtReg, PhysReg);
512   } else {         // No registers available.
513     // Force some poor hapless value out of the register file to
514     // make room for the new register, and reload it.
515     PhysReg = getReg(MBB, MI, VirtReg, true);
516   }
517
518   markVirtRegModified(VirtReg, false);   // Note that this reg was just reloaded
519
520   DEBUG(dbgs() << "  Reloading %reg" << VirtReg << " into "
521                << TRI->getName(PhysReg) << "\n");
522
523   // Add move instruction(s)
524   TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC);
525   ++NumLoads;    // Update statistics
526
527   MF->getRegInfo().setPhysRegUsed(PhysReg);
528   MI->getOperand(OpNum).setReg(PhysReg);  // Assign the input register
529   getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
530
531   if (!ReloadedRegs.insert(PhysReg)) {
532     std::string msg;
533     raw_string_ostream Msg(msg);
534     Msg << "Ran out of registers during register allocation!";
535     if (MI->isInlineAsm()) {
536       Msg << "\nPlease check your inline asm statement for invalid "
537            << "constraints:\n";
538       MI->print(Msg, TM);
539     }
540     llvm_report_error(Msg.str());
541   }
542   for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
543        *SubRegs; ++SubRegs) {
544     if (!ReloadedRegs.insert(*SubRegs)) {
545       std::string msg;
546       raw_string_ostream Msg(msg);
547       Msg << "Ran out of registers during register allocation!";
548       if (MI->isInlineAsm()) {
549         Msg << "\nPlease check your inline asm statement for invalid "
550              << "constraints:\n";
551         MI->print(Msg, TM);
552       }
553       llvm_report_error(Msg.str());
554     }
555   }
556
557   return MI;
558 }
559
560 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
561 /// read/mod/write register, i.e. update partial register.
562 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
563   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
564     MachineOperand& MO = MI->getOperand(i);
565     if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
566         MO.isDef() && !MO.isDead())
567       return true;
568   }
569   return false;
570 }
571
572 /// isReadModWriteImplicitDef - True if this is an implicit def for a
573 /// read/mod/write register, i.e. update partial register.
574 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
575   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
576     MachineOperand& MO = MI->getOperand(i);
577     if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
578         !MO.isDef() && MO.isKill())
579       return true;
580   }
581   return false;
582 }
583
584 // precedes - Helper function to determine with MachineInstr A
585 // precedes MachineInstr B within the same MBB.
586 static bool precedes(MachineBasicBlock::iterator A,
587                      MachineBasicBlock::iterator B) {
588   if (A == B)
589     return false;
590   
591   MachineBasicBlock::iterator I = A->getParent()->begin();
592   while (I != A->getParent()->end()) {
593     if (I == A)
594       return true;
595     else if (I == B)
596       return false;
597     
598     ++I;
599   }
600   
601   return false;
602 }
603
604 /// ComputeLocalLiveness - Computes liveness of registers within a basic
605 /// block, setting the killed/dead flags as appropriate.
606 void RALocal::ComputeLocalLiveness(MachineBasicBlock& MBB) {
607   MachineRegisterInfo& MRI = MBB.getParent()->getRegInfo();
608   // Keep track of the most recently seen previous use or def of each reg, 
609   // so that we can update them with dead/kill markers.
610   DenseMap<unsigned, std::pair<MachineInstr*, unsigned> > LastUseDef;
611   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
612        I != E; ++I) {
613     if (I->isDebugValue())
614       continue;
615     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
616       MachineOperand& MO = I->getOperand(i);
617       // Uses don't trigger any flags, but we need to save
618       // them for later.  Also, we have to process these
619       // _before_ processing the defs, since an instr
620       // uses regs before it defs them.
621       if (MO.isReg() && MO.getReg() && MO.isUse()) {
622         LastUseDef[MO.getReg()] = std::make_pair(I, i);
623         
624         
625         if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) continue;
626         
627         const unsigned* Aliases = TRI->getAliasSet(MO.getReg());
628         if (Aliases) {
629           while (*Aliases) {
630             DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
631               alias = LastUseDef.find(*Aliases);
632             
633             if (alias != LastUseDef.end() && alias->second.first != I)
634               LastUseDef[*Aliases] = std::make_pair(I, i);
635             
636             ++Aliases;
637           }
638         }
639       }
640     }
641     
642     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
643       MachineOperand& MO = I->getOperand(i);
644       // Defs others than 2-addr redefs _do_ trigger flag changes:
645       //   - A def followed by a def is dead
646       //   - A use followed by a def is a kill
647       if (MO.isReg() && MO.getReg() && MO.isDef()) {
648         DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
649           last = LastUseDef.find(MO.getReg());
650         if (last != LastUseDef.end()) {
651           // Check if this is a two address instruction.  If so, then
652           // the def does not kill the use.
653           if (last->second.first == I &&
654               I->isRegTiedToUseOperand(i))
655             continue;
656           
657           MachineOperand& lastUD =
658                       last->second.first->getOperand(last->second.second);
659           if (lastUD.isDef())
660             lastUD.setIsDead(true);
661           else
662             lastUD.setIsKill(true);
663         }
664         
665         LastUseDef[MO.getReg()] = std::make_pair(I, i);
666       }
667     }
668   }
669   
670   // Live-out (of the function) registers contain return values of the function,
671   // so we need to make sure they are alive at return time.
672   if (!MBB.empty() && MBB.back().getDesc().isReturn()) {
673     MachineInstr* Ret = &MBB.back();
674     for (MachineRegisterInfo::liveout_iterator
675          I = MF->getRegInfo().liveout_begin(),
676          E = MF->getRegInfo().liveout_end(); I != E; ++I)
677       if (!Ret->readsRegister(*I)) {
678         Ret->addOperand(MachineOperand::CreateReg(*I, false, true));
679         LastUseDef[*I] = std::make_pair(Ret, Ret->getNumOperands()-1);
680       }
681   }
682   
683   // Finally, loop over the final use/def of each reg 
684   // in the block and determine if it is dead.
685   for (DenseMap<unsigned, std::pair<MachineInstr*, unsigned> >::iterator
686        I = LastUseDef.begin(), E = LastUseDef.end(); I != E; ++I) {
687     MachineInstr* MI = I->second.first;
688     unsigned idx = I->second.second;
689     MachineOperand& MO = MI->getOperand(idx);
690     
691     bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(MO.getReg());
692     
693     // A crude approximation of "live-out" calculation
694     bool usedOutsideBlock = isPhysReg ? false :   
695           UsedInMultipleBlocks.test(MO.getReg() -  
696                                     TargetRegisterInfo::FirstVirtualRegister);
697     if (!isPhysReg && !usedOutsideBlock)
698       for (MachineRegisterInfo::reg_iterator UI = MRI.reg_begin(MO.getReg()),
699            UE = MRI.reg_end(); UI != UE; ++UI)
700         // Two cases:
701         // - used in another block
702         // - used in the same block before it is defined (loop)
703         if (UI->getParent() != &MBB ||
704             (MO.isDef() && UI.getOperand().isUse() && precedes(&*UI, MI))) {
705           UsedInMultipleBlocks.set(MO.getReg() - 
706                                    TargetRegisterInfo::FirstVirtualRegister);
707           usedOutsideBlock = true;
708           break;
709         }
710     
711     // Physical registers and those that are not live-out of the block
712     // are killed/dead at their last use/def within this block.
713     if (isPhysReg || !usedOutsideBlock) {
714       if (MO.isUse()) {
715         // Don't mark uses that are tied to defs as kills.
716         if (!MI->isRegTiedToDefOperand(idx))
717           MO.setIsKill(true);
718       } else
719         MO.setIsDead(true);
720     }
721   }
722 }
723
724 void RALocal::AllocateBasicBlock(MachineBasicBlock &MBB) {
725   // loop over each instruction
726   MachineBasicBlock::iterator MII = MBB.begin();
727   
728   DEBUG({
729       const BasicBlock *LBB = MBB.getBasicBlock();
730       if (LBB)
731         dbgs() << "\nStarting RegAlloc of BB: " << LBB->getName();
732     });
733
734   // Add live-in registers as active.
735   for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
736          E = MBB.livein_end(); I != E; ++I) {
737     unsigned Reg = *I;
738     MF->getRegInfo().setPhysRegUsed(Reg);
739     PhysRegsUsed[Reg] = 0;            // It is free and reserved now
740     AddToPhysRegsUseOrder(Reg); 
741     for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
742          *SubRegs; ++SubRegs) {
743       if (PhysRegsUsed[*SubRegs] != -2) {
744         AddToPhysRegsUseOrder(*SubRegs); 
745         PhysRegsUsed[*SubRegs] = 0;  // It is free and reserved now
746         MF->getRegInfo().setPhysRegUsed(*SubRegs);
747       }
748     }
749   }
750   
751   ComputeLocalLiveness(MBB);
752   
753   // Otherwise, sequentially allocate each instruction in the MBB.
754   while (MII != MBB.end()) {
755     MachineInstr *MI = MII++;
756     const TargetInstrDesc &TID = MI->getDesc();
757     DEBUG({
758         dbgs() << "\nStarting RegAlloc of: " << *MI;
759         dbgs() << "  Regs have values: ";
760         for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
761           if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
762             dbgs() << "[" << TRI->getName(i)
763                    << ",%reg" << PhysRegsUsed[i] << "] ";
764         dbgs() << '\n';
765       });
766
767     // Determine whether this is a copy instruction.  The cases where the
768     // source or destination are phys regs are handled specially.
769     unsigned SrcCopyReg, DstCopyReg, SrcCopySubReg, DstCopySubReg;
770     unsigned SrcCopyPhysReg = 0U;
771     bool isCopy = TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg, 
772                                    SrcCopySubReg, DstCopySubReg);
773     if (isCopy && TargetRegisterInfo::isVirtualRegister(SrcCopyReg))
774       SrcCopyPhysReg = getVirt2PhysRegMapSlot(SrcCopyReg);
775
776     // Loop over the implicit uses, making sure that they are at the head of the
777     // use order list, so they don't get reallocated.
778     if (TID.ImplicitUses) {
779       for (const unsigned *ImplicitUses = TID.ImplicitUses;
780            *ImplicitUses; ++ImplicitUses)
781         MarkPhysRegRecentlyUsed(*ImplicitUses);
782     }
783
784     SmallVector<unsigned, 8> Kills;
785     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
786       MachineOperand& MO = MI->getOperand(i);
787       if (MO.isReg() && MO.isKill()) {
788         if (!MO.isImplicit())
789           Kills.push_back(MO.getReg());
790         else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
791           // These are extra physical register kills when a sub-register
792           // is defined (def of a sub-register is a read/mod/write of the
793           // larger registers). Ignore.
794           Kills.push_back(MO.getReg());
795       }
796     }
797
798     // If any physical regs are earlyclobber, spill any value they might
799     // have in them, then mark them unallocatable.
800     // If any virtual regs are earlyclobber, allocate them now (before
801     // freeing inputs that are killed).
802     if (MI->isInlineAsm()) {
803       for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
804         MachineOperand& MO = MI->getOperand(i);
805         if (MO.isReg() && MO.isDef() && MO.isEarlyClobber() &&
806             MO.getReg()) {
807           if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
808             unsigned DestVirtReg = MO.getReg();
809             unsigned DestPhysReg;
810
811             // If DestVirtReg already has a value, use it.
812             if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
813               DestPhysReg = getReg(MBB, MI, DestVirtReg);
814             MF->getRegInfo().setPhysRegUsed(DestPhysReg);
815             markVirtRegModified(DestVirtReg);
816             getVirtRegLastUse(DestVirtReg) =
817                    std::make_pair((MachineInstr*)0, 0);
818             DEBUG(dbgs() << "  Assigning " << TRI->getName(DestPhysReg)
819                          << " to %reg" << DestVirtReg << "\n");
820             MO.setReg(DestPhysReg);  // Assign the earlyclobber register
821           } else {
822             unsigned Reg = MO.getReg();
823             if (PhysRegsUsed[Reg] == -2) continue;  // Something like ESP.
824             // These are extra physical register defs when a sub-register
825             // is defined (def of a sub-register is a read/mod/write of the
826             // larger registers). Ignore.
827             if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
828
829             MF->getRegInfo().setPhysRegUsed(Reg);
830             spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
831             PhysRegsUsed[Reg] = 0;            // It is free and reserved now
832             AddToPhysRegsUseOrder(Reg); 
833
834             for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
835                  *SubRegs; ++SubRegs) {
836               if (PhysRegsUsed[*SubRegs] != -2) {
837                 MF->getRegInfo().setPhysRegUsed(*SubRegs);
838                 PhysRegsUsed[*SubRegs] = 0;  // It is free and reserved now
839                 AddToPhysRegsUseOrder(*SubRegs); 
840               }
841             }
842           }
843         }
844       }
845     }
846
847     // If a DBG_VALUE says something is located in a spilled register,
848     // change the DBG_VALUE to be undef, which prevents the register
849     // from being reloaded here.  Doing that would change the generated
850     // code, unless another use immediately follows this instruction.
851     if (MI->isDebugValue() &&
852         MI->getNumOperands()==3 && MI->getOperand(0).isReg()) {
853       unsigned VirtReg = MI->getOperand(0).getReg();
854       if (VirtReg && TargetRegisterInfo::isVirtualRegister(VirtReg) &&
855           !getVirt2PhysRegMapSlot(VirtReg))
856         MI->getOperand(0).setReg(0U);
857     }
858
859     // Get the used operands into registers.  This has the potential to spill
860     // incoming values if we are out of registers.  Note that we completely
861     // ignore physical register uses here.  We assume that if an explicit
862     // physical register is referenced by the instruction, that it is guaranteed
863     // to be live-in, or the input is badly hosed.
864     //
865     SmallSet<unsigned, 4> ReloadedRegs;
866     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
867       MachineOperand& MO = MI->getOperand(i);
868       // here we are looking for only used operands (never def&use)
869       if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
870           TargetRegisterInfo::isVirtualRegister(MO.getReg()))
871         MI = reloadVirtReg(MBB, MI, i, ReloadedRegs,
872                            isCopy ? DstCopyReg : 0);
873     }
874
875     // If this instruction is the last user of this register, kill the
876     // value, freeing the register being used, so it doesn't need to be
877     // spilled to memory.
878     //
879     for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
880       unsigned VirtReg = Kills[i];
881       unsigned PhysReg = VirtReg;
882       if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
883         // If the virtual register was never materialized into a register, it
884         // might not be in the map, but it won't hurt to zero it out anyway.
885         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
886         PhysReg = PhysRegSlot;
887         PhysRegSlot = 0;
888       } else if (PhysRegsUsed[PhysReg] == -2) {
889         // Unallocatable register dead, ignore.
890         continue;
891       } else {
892         assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
893                "Silently clearing a virtual register?");
894       }
895
896       if (PhysReg) {
897         DEBUG(dbgs() << "  Last use of " << TRI->getName(PhysReg)
898                      << "[%reg" << VirtReg <<"], removing it from live set\n");
899         removePhysReg(PhysReg);
900         for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
901              *SubRegs; ++SubRegs) {
902           if (PhysRegsUsed[*SubRegs] != -2) {
903             DEBUG(dbgs()  << "  Last use of "
904                           << TRI->getName(*SubRegs) << "[%reg" << VirtReg
905                           <<"], removing it from live set\n");
906             removePhysReg(*SubRegs);
907           }
908         }
909       }
910     }
911
912     // Loop over all of the operands of the instruction, spilling registers that
913     // are defined, and marking explicit destinations in the PhysRegsUsed map.
914     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
915       MachineOperand& MO = MI->getOperand(i);
916       if (MO.isReg() && MO.isDef() && !MO.isImplicit() && MO.getReg() &&
917           !MO.isEarlyClobber() &&
918           TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
919         unsigned Reg = MO.getReg();
920         if (PhysRegsUsed[Reg] == -2) continue;  // Something like ESP.
921         // These are extra physical register defs when a sub-register
922         // is defined (def of a sub-register is a read/mod/write of the
923         // larger registers). Ignore.
924         if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
925
926         MF->getRegInfo().setPhysRegUsed(Reg);
927         spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
928         PhysRegsUsed[Reg] = 0;            // It is free and reserved now
929         AddToPhysRegsUseOrder(Reg); 
930
931         for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
932              *SubRegs; ++SubRegs) {
933           if (PhysRegsUsed[*SubRegs] != -2) {
934             MF->getRegInfo().setPhysRegUsed(*SubRegs);
935             PhysRegsUsed[*SubRegs] = 0;  // It is free and reserved now
936             AddToPhysRegsUseOrder(*SubRegs); 
937           }
938         }
939       }
940     }
941
942     // Loop over the implicit defs, spilling them as well.
943     if (TID.ImplicitDefs) {
944       for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
945            *ImplicitDefs; ++ImplicitDefs) {
946         unsigned Reg = *ImplicitDefs;
947         if (PhysRegsUsed[Reg] != -2) {
948           spillPhysReg(MBB, MI, Reg, true);
949           AddToPhysRegsUseOrder(Reg); 
950           PhysRegsUsed[Reg] = 0;            // It is free and reserved now
951         }
952         MF->getRegInfo().setPhysRegUsed(Reg);
953         for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
954              *SubRegs; ++SubRegs) {
955           if (PhysRegsUsed[*SubRegs] != -2) {
956             AddToPhysRegsUseOrder(*SubRegs); 
957             PhysRegsUsed[*SubRegs] = 0;  // It is free and reserved now
958             MF->getRegInfo().setPhysRegUsed(*SubRegs);
959           }
960         }
961       }
962     }
963
964     SmallVector<unsigned, 8> DeadDefs;
965     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
966       MachineOperand& MO = MI->getOperand(i);
967       if (MO.isReg() && MO.isDead())
968         DeadDefs.push_back(MO.getReg());
969     }
970
971     // Okay, we have allocated all of the source operands and spilled any values
972     // that would be destroyed by defs of this instruction.  Loop over the
973     // explicit defs and assign them to a register, spilling incoming values if
974     // we need to scavenge a register.
975     //
976     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
977       MachineOperand& MO = MI->getOperand(i);
978       if (MO.isReg() && MO.isDef() && MO.getReg() &&
979           !MO.isEarlyClobber() &&
980           TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
981         unsigned DestVirtReg = MO.getReg();
982         unsigned DestPhysReg;
983
984         // If DestVirtReg already has a value, use it.
985         if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg))) {
986           // If this is a copy try to reuse the input as the output;
987           // that will make the copy go away.
988           // If this is a copy, the source reg is a phys reg, and
989           // that reg is available, use that phys reg for DestPhysReg.
990           // If this is a copy, the source reg is a virtual reg, and
991           // the phys reg that was assigned to that virtual reg is now
992           // available, use that phys reg for DestPhysReg.  (If it's now
993           // available that means this was the last use of the source.)
994           if (isCopy &&
995               TargetRegisterInfo::isPhysicalRegister(SrcCopyReg) &&
996               isPhysRegAvailable(SrcCopyReg)) {
997             DestPhysReg = SrcCopyReg;
998             assignVirtToPhysReg(DestVirtReg, DestPhysReg);
999           } else if (isCopy &&
1000               TargetRegisterInfo::isVirtualRegister(SrcCopyReg) &&
1001               SrcCopyPhysReg && isPhysRegAvailable(SrcCopyPhysReg) &&
1002               MF->getRegInfo().getRegClass(DestVirtReg)->
1003                                contains(SrcCopyPhysReg)) {
1004             DestPhysReg = SrcCopyPhysReg;
1005             assignVirtToPhysReg(DestVirtReg, DestPhysReg);
1006           } else
1007             DestPhysReg = getReg(MBB, MI, DestVirtReg);
1008         }
1009         MF->getRegInfo().setPhysRegUsed(DestPhysReg);
1010         markVirtRegModified(DestVirtReg);
1011         getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
1012         DEBUG(dbgs() << "  Assigning " << TRI->getName(DestPhysReg)
1013                      << " to %reg" << DestVirtReg << "\n");
1014         MO.setReg(DestPhysReg);  // Assign the output register
1015       }
1016     }
1017
1018     // If this instruction defines any registers that are immediately dead,
1019     // kill them now.
1020     //
1021     for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
1022       unsigned VirtReg = DeadDefs[i];
1023       unsigned PhysReg = VirtReg;
1024       if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
1025         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
1026         PhysReg = PhysRegSlot;
1027         assert(PhysReg != 0);
1028         PhysRegSlot = 0;
1029       } else if (PhysRegsUsed[PhysReg] == -2) {
1030         // Unallocatable register dead, ignore.
1031         continue;
1032       }
1033
1034       if (PhysReg) {
1035         DEBUG(dbgs()  << "  Register " << TRI->getName(PhysReg)
1036                       << " [%reg" << VirtReg
1037                       << "] is never used, removing it from live set\n");
1038         removePhysReg(PhysReg);
1039         for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
1040              *AliasSet; ++AliasSet) {
1041           if (PhysRegsUsed[*AliasSet] != -2) {
1042             DEBUG(dbgs()  << "  Register " << TRI->getName(*AliasSet)
1043                           << " [%reg" << *AliasSet
1044                           << "] is never used, removing it from live set\n");
1045             removePhysReg(*AliasSet);
1046           }
1047         }
1048       }
1049     }
1050     
1051     // Finally, if this is a noop copy instruction, zap it.  (Except that if
1052     // the copy is dead, it must be kept to avoid messing up liveness info for
1053     // the register scavenger.  See pr4100.)
1054     if (TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
1055                          SrcCopySubReg, DstCopySubReg) &&
1056         SrcCopyReg == DstCopyReg && DeadDefs.empty())
1057       MBB.erase(MI);
1058   }
1059
1060   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1061
1062   // Spill all physical registers holding virtual registers now.
1063   for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
1064     if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
1065       if (unsigned VirtReg = PhysRegsUsed[i])
1066         spillVirtReg(MBB, MI, VirtReg, i);
1067       else
1068         removePhysReg(i);
1069     }
1070
1071 #if 0
1072   // This checking code is very expensive.
1073   bool AllOk = true;
1074   for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
1075            e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
1076     if (unsigned PR = Virt2PhysRegMap[i]) {
1077       cerr << "Register still mapped: " << i << " -> " << PR << "\n";
1078       AllOk = false;
1079     }
1080   assert(AllOk && "Virtual registers still in phys regs?");
1081 #endif
1082
1083   // Clear any physical register which appear live at the end of the basic
1084   // block, but which do not hold any virtual registers.  e.g., the stack
1085   // pointer.
1086   PhysRegsUseOrder.clear();
1087 }
1088
1089 /// runOnMachineFunction - Register allocate the whole function
1090 ///
1091 bool RALocal::runOnMachineFunction(MachineFunction &Fn) {
1092   DEBUG(dbgs() << "Machine Function\n");
1093   MF = &Fn;
1094   TM = &Fn.getTarget();
1095   TRI = TM->getRegisterInfo();
1096   TII = TM->getInstrInfo();
1097
1098   PhysRegsUsed.assign(TRI->getNumRegs(), -1);
1099   
1100   // At various places we want to efficiently check to see whether a register
1101   // is allocatable.  To handle this, we mark all unallocatable registers as
1102   // being pinned down, permanently.
1103   {
1104     BitVector Allocable = TRI->getAllocatableSet(Fn);
1105     for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
1106       if (!Allocable[i])
1107         PhysRegsUsed[i] = -2;  // Mark the reg unallocable.
1108   }
1109
1110   // initialize the virtual->physical register map to have a 'null'
1111   // mapping for all virtual registers
1112   unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
1113   StackSlotForVirtReg.grow(LastVirtReg);
1114   Virt2PhysRegMap.grow(LastVirtReg);
1115   Virt2LastUseMap.grow(LastVirtReg);
1116   VirtRegModified.resize(LastVirtReg+1-TargetRegisterInfo::FirstVirtualRegister);
1117   UsedInMultipleBlocks.resize(LastVirtReg+1-TargetRegisterInfo::FirstVirtualRegister);
1118  
1119   // Loop over all of the basic blocks, eliminating virtual register references
1120   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
1121        MBB != MBBe; ++MBB)
1122     AllocateBasicBlock(*MBB);
1123
1124   StackSlotForVirtReg.clear();
1125   PhysRegsUsed.clear();
1126   VirtRegModified.clear();
1127   UsedInMultipleBlocks.clear();
1128   Virt2PhysRegMap.clear();
1129   Virt2LastUseMap.clear();
1130   return true;
1131 }
1132
1133 FunctionPass *llvm::createLocalRegisterAllocator() {
1134   return new RALocal();
1135 }