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