It's not safe eliminate copies where src and dst have different sub-register indices.
[oota-llvm.git] / lib / CodeGen / RegAllocFast.cpp
1 //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
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/LiveVariables.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegAllocRegistry.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/IndexedMap.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 STATISTIC(NumStores, "Number of stores added");
40 STATISTIC(NumLoads , "Number of loads added");
41
42 static RegisterRegAlloc
43   fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
44
45 namespace {
46   class RAFast : public MachineFunctionPass {
47   public:
48     static char ID;
49     RAFast() : 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     // UsedInInstr - BitVector of physregs that are used in the current
80     // instruction, and so cannot be allocated.
81     BitVector UsedInInstr;
82
83     // Virt2LastUseMap - This maps each virtual register to its last use
84     // (MachineInstr*, operand index pair).
85     IndexedMap<std::pair<MachineInstr*, unsigned>, VirtReg2IndexFunctor>
86     Virt2LastUseMap;
87
88     std::pair<MachineInstr*,unsigned>& getVirtRegLastUse(unsigned Reg) {
89       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
90       return Virt2LastUseMap[Reg];
91     }
92
93     // VirtRegModified - This bitset contains information about which virtual
94     // registers need to be spilled back to memory when their registers are
95     // scavenged.  If a virtual register has simply been rematerialized, there
96     // is no reason to spill it to memory when we need the register back.
97     //
98     BitVector VirtRegModified;
99
100     // UsedInMultipleBlocks - Tracks whether a particular register is used in
101     // more than one block.
102     BitVector UsedInMultipleBlocks;
103
104     void markVirtRegModified(unsigned Reg, bool Val = true) {
105       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
106       Reg -= TargetRegisterInfo::FirstVirtualRegister;
107       if (Val)
108         VirtRegModified.set(Reg);
109       else
110         VirtRegModified.reset(Reg);
111     }
112
113     bool isVirtRegModified(unsigned Reg) const {
114       assert(TargetRegisterInfo::isVirtualRegister(Reg) && "Illegal VirtReg!");
115       assert(Reg - TargetRegisterInfo::FirstVirtualRegister <
116              VirtRegModified.size() && "Illegal virtual register!");
117       return VirtRegModified[Reg - TargetRegisterInfo::FirstVirtualRegister];
118     }
119
120   public:
121     virtual const char *getPassName() const {
122       return "Fast Register Allocator";
123     }
124
125     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
126       AU.setPreservesCFG();
127       AU.addRequired<LiveVariables>();
128       AU.addRequiredID(PHIEliminationID);
129       AU.addRequiredID(TwoAddressInstructionPassID);
130       MachineFunctionPass::getAnalysisUsage(AU);
131     }
132
133   private:
134     /// runOnMachineFunction - Register allocate the whole function
135     bool runOnMachineFunction(MachineFunction &Fn);
136
137     /// AllocateBasicBlock - Register allocate the specified basic block.
138     void AllocateBasicBlock(MachineBasicBlock &MBB);
139
140
141     /// areRegsEqual - This method returns true if the specified registers are
142     /// related to each other.  To do this, it checks to see if they are equal
143     /// or if the first register is in the alias set of the second register.
144     ///
145     bool areRegsEqual(unsigned R1, unsigned R2) const {
146       if (R1 == R2) return true;
147       for (const unsigned *AliasSet = TRI->getAliasSet(R2);
148            *AliasSet; ++AliasSet) {
149         if (*AliasSet == R1) return true;
150       }
151       return false;
152     }
153
154     /// getStackSpaceFor - This returns the frame index of the specified virtual
155     /// register on the stack, allocating space if necessary.
156     int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
157
158     /// removePhysReg - This method marks the specified physical register as no
159     /// longer being in use.
160     ///
161     void removePhysReg(unsigned PhysReg);
162
163     /// spillVirtReg - This method spills the value specified by PhysReg into
164     /// the virtual register slot specified by VirtReg.  It then updates the RA
165     /// data structures to indicate the fact that PhysReg is now available.
166     ///
167     void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
168                       unsigned VirtReg, unsigned PhysReg);
169
170     /// spillPhysReg - This method spills the specified physical register into
171     /// the virtual register slot associated with it.  If OnlyVirtRegs is set to
172     /// true, then the request is ignored if the physical register does not
173     /// contain a virtual register.
174     ///
175     void spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
176                       unsigned PhysReg, bool OnlyVirtRegs = false);
177
178     /// assignVirtToPhysReg - This method updates local state so that we know
179     /// that PhysReg is the proper container for VirtReg now.  The physical
180     /// register must not be used for anything else when this is called.
181     ///
182     void assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg);
183
184     /// isPhysRegAvailable - Return true if the specified physical register is
185     /// free and available for use.  This also includes checking to see if
186     /// aliased registers are all free...
187     ///
188     bool isPhysRegAvailable(unsigned PhysReg) const;
189
190     /// isPhysRegSpillable - Can PhysReg be freed by spilling?
191     bool isPhysRegSpillable(unsigned PhysReg) const;
192
193     /// getFreeReg - Look to see if there is a free register available in the
194     /// specified register class.  If not, return 0.
195     ///
196     unsigned getFreeReg(const TargetRegisterClass *RC);
197
198     /// getReg - Find a physical register to hold the specified virtual
199     /// register.  If all compatible physical registers are used, this method
200     /// spills the last used virtual register to the stack, and uses that
201     /// register. If NoFree is true, that means the caller knows there isn't
202     /// a free register, do not call getFreeReg().
203     unsigned getReg(MachineBasicBlock &MBB, MachineInstr *MI,
204                     unsigned VirtReg, bool NoFree = false);
205
206     /// reloadVirtReg - This method transforms the specified virtual
207     /// register use to refer to a physical register.  This method may do this
208     /// in one of several ways: if the register is available in a physical
209     /// register already, it uses that physical register.  If the value is not
210     /// in a physical register, and if there are physical registers available,
211     /// it loads it into a register: PhysReg if that is an available physical
212     /// register, otherwise any physical register of the right class.
213     /// If register pressure is high, and it is possible, it tries to fold the
214     /// load of the virtual register into the instruction itself.  It avoids
215     /// doing this if register pressure is low to improve the chance that
216     /// subsequent instructions can use the reloaded value.  This method
217     /// returns the modified instruction.
218     ///
219     MachineInstr *reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
220                                 unsigned OpNum, SmallSet<unsigned, 4> &RRegs,
221                                 unsigned PhysReg);
222
223     void reloadPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I,
224                        unsigned PhysReg);
225   };
226   char RAFast::ID = 0;
227 }
228
229 /// getStackSpaceFor - This allocates space for the specified virtual register
230 /// to be held on the stack.
231 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
232   // Find the location Reg would belong...
233   int SS = StackSlotForVirtReg[VirtReg];
234   if (SS != -1)
235     return SS;          // Already has space allocated?
236
237   // Allocate a new stack object for this spill location...
238   int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
239                                                             RC->getAlignment());
240
241   // Assign the slot.
242   StackSlotForVirtReg[VirtReg] = FrameIdx;
243   return FrameIdx;
244 }
245
246
247 /// removePhysReg - This method marks the specified physical register as no
248 /// longer being in use.
249 ///
250 void RAFast::removePhysReg(unsigned PhysReg) {
251   PhysRegsUsed[PhysReg] = -1;      // PhyReg no longer used
252 }
253
254
255 /// spillVirtReg - This method spills the value specified by PhysReg into the
256 /// virtual register slot specified by VirtReg.  It then updates the RA data
257 /// structures to indicate the fact that PhysReg is now available.
258 ///
259 void RAFast::spillVirtReg(MachineBasicBlock &MBB,
260                            MachineBasicBlock::iterator I,
261                            unsigned VirtReg, unsigned PhysReg) {
262   assert(VirtReg && "Spilling a physical register is illegal!"
263          " Must not have appropriate kill for the register or use exists beyond"
264          " the intended one.");
265   DEBUG(dbgs() << "  Spilling register " << TRI->getName(PhysReg)
266                << " containing %reg" << VirtReg);
267
268   if (!isVirtRegModified(VirtReg)) {
269     DEBUG(dbgs() << " which has not been modified, so no store necessary!");
270     std::pair<MachineInstr*, unsigned> &LastUse = getVirtRegLastUse(VirtReg);
271     if (LastUse.first)
272       LastUse.first->getOperand(LastUse.second).setIsKill();
273   } else {
274     // Otherwise, there is a virtual register corresponding to this physical
275     // register.  We only need to spill it into its stack slot if it has been
276     // modified.
277     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
278     int FrameIndex = getStackSpaceFor(VirtReg, RC);
279     DEBUG(dbgs() << " to stack slot #" << FrameIndex);
280     // If the instruction reads the register that's spilled, (e.g. this can
281     // happen if it is a move to a physical register), then the spill
282     // instruction is not a kill.
283     bool isKill = !(I != MBB.end() && I->readsRegister(PhysReg));
284     TII->storeRegToStackSlot(MBB, I, PhysReg, isKill, FrameIndex, RC, TRI);
285     ++NumStores;   // Update statistics
286   }
287
288   getVirt2PhysRegMapSlot(VirtReg) = 0;   // VirtReg no longer available
289
290   DEBUG(dbgs() << '\n');
291   removePhysReg(PhysReg);
292 }
293
294
295 /// spillPhysReg - This method spills the specified physical register into the
296 /// virtual register slot associated with it.  If OnlyVirtRegs is set to true,
297 /// then the request is ignored if the physical register does not contain a
298 /// virtual register.
299 ///
300 void RAFast::spillPhysReg(MachineBasicBlock &MBB, MachineInstr *I,
301                            unsigned PhysReg, bool OnlyVirtRegs) {
302   if (PhysRegsUsed[PhysReg] != -1) {            // Only spill it if it's used!
303     assert(PhysRegsUsed[PhysReg] != -2 && "Non allocable reg used!");
304     if (PhysRegsUsed[PhysReg] || !OnlyVirtRegs)
305       spillVirtReg(MBB, I, PhysRegsUsed[PhysReg], PhysReg);
306     return;
307   }
308
309   // If the selected register aliases any other registers, we must make
310   // sure that one of the aliases isn't alive.
311   for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
312        *AliasSet; ++AliasSet) {
313     if (PhysRegsUsed[*AliasSet] == -1 ||     // Spill aliased register.
314         PhysRegsUsed[*AliasSet] == -2)       // If allocatable.
315       continue;
316
317     if (PhysRegsUsed[*AliasSet])
318       spillVirtReg(MBB, I, PhysRegsUsed[*AliasSet], *AliasSet);
319   }
320 }
321
322
323 /// assignVirtToPhysReg - This method updates local state so that we know
324 /// that PhysReg is the proper container for VirtReg now.  The physical
325 /// register must not be used for anything else when this is called.
326 ///
327 void RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
328   assert(PhysRegsUsed[PhysReg] == -1 && "Phys reg already assigned!");
329   // Update information to note the fact that this register was just used, and
330   // it holds VirtReg.
331   PhysRegsUsed[PhysReg] = VirtReg;
332   getVirt2PhysRegMapSlot(VirtReg) = PhysReg;
333   UsedInInstr.set(PhysReg);
334 }
335
336
337 /// isPhysRegAvailable - Return true if the specified physical register is free
338 /// and available for use.  This also includes checking to see if aliased
339 /// registers are all free...
340 ///
341 bool RAFast::isPhysRegAvailable(unsigned PhysReg) const {
342   if (PhysRegsUsed[PhysReg] != -1) return false;
343
344   // If the selected register aliases any other allocated registers, it is
345   // not free!
346   for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
347        *AliasSet; ++AliasSet)
348     if (PhysRegsUsed[*AliasSet] >= 0) // Aliased register in use?
349       return false;                    // Can't use this reg then.
350   return true;
351 }
352
353 /// isPhysRegSpillable - Return true if the specified physical register can be
354 /// spilled for use in the current instruction.
355 ///
356 bool RAFast::isPhysRegSpillable(unsigned PhysReg) const {
357   // Test that PhysReg and all aliases are either free or assigned to a VirtReg
358   // that is not used in the instruction.
359   if (PhysRegsUsed[PhysReg] != -1 &&
360       (PhysRegsUsed[PhysReg] <= 0 || UsedInInstr.test(PhysReg)))
361     return false;
362
363   for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
364        *AliasSet; ++AliasSet)
365     if (PhysRegsUsed[*AliasSet] != -1 &&
366         (PhysRegsUsed[*AliasSet] <= 0 || UsedInInstr.test(*AliasSet)))
367       return false;
368   return true;
369 }
370
371
372 /// getFreeReg - Look to see if there is a free register available in the
373 /// specified register class.  If not, return 0.
374 ///
375 unsigned RAFast::getFreeReg(const TargetRegisterClass *RC) {
376   // Get iterators defining the range of registers that are valid to allocate in
377   // this class, which also specifies the preferred allocation order.
378   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
379   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
380
381   for (; RI != RE; ++RI)
382     if (isPhysRegAvailable(*RI)) {       // Is reg unused?
383       assert(*RI != 0 && "Cannot use register!");
384       return *RI; // Found an unused register!
385     }
386   return 0;
387 }
388
389
390 /// getReg - Find a physical register to hold the specified virtual
391 /// register.  If all compatible physical registers are used, this method spills
392 /// the last used virtual register to the stack, and uses that register.
393 ///
394 unsigned RAFast::getReg(MachineBasicBlock &MBB, MachineInstr *I,
395                          unsigned VirtReg, bool NoFree) {
396   const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
397
398   // First check to see if we have a free register of the requested type...
399   unsigned PhysReg = NoFree ? 0 : getFreeReg(RC);
400
401   if (PhysReg != 0) {
402     // Assign the register.
403     assignVirtToPhysReg(VirtReg, PhysReg);
404     return PhysReg;
405   }
406
407   // If we didn't find an unused register, scavenge one now! Don't be fancy,
408   // just grab the first possible register.
409   TargetRegisterClass::iterator RI = RC->allocation_order_begin(*MF);
410   TargetRegisterClass::iterator RE = RC->allocation_order_end(*MF);
411
412   for (; RI != RE; ++RI)
413     if (isPhysRegSpillable(*RI)) {
414       PhysReg = *RI;
415       break;
416     }
417
418   assert(PhysReg && "Physical register not assigned!?!?");
419   spillPhysReg(MBB, I, PhysReg);
420   assignVirtToPhysReg(VirtReg, PhysReg);
421   return PhysReg;
422 }
423
424
425 /// reloadVirtReg - This method transforms the specified virtual
426 /// register use to refer to a physical register.  This method may do this in
427 /// one of several ways: if the register is available in a physical register
428 /// already, it uses that physical register.  If the value is not in a physical
429 /// register, and if there are physical registers available, it loads it into a
430 /// register: PhysReg if that is an available physical register, otherwise any
431 /// register.  If register pressure is high, and it is possible, it tries to
432 /// fold the load of the virtual register into the instruction itself.  It
433 /// avoids doing this if register pressure is low to improve the chance that
434 /// subsequent instructions can use the reloaded value.  This method returns
435 /// the modified instruction.
436 ///
437 MachineInstr *RAFast::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
438                                      unsigned OpNum,
439                                      SmallSet<unsigned, 4> &ReloadedRegs,
440                                      unsigned PhysReg) {
441   unsigned VirtReg = MI->getOperand(OpNum).getReg();
442
443   // If the virtual register is already available, just update the instruction
444   // and return.
445   if (unsigned PR = getVirt2PhysRegMapSlot(VirtReg)) {
446     MI->getOperand(OpNum).setReg(PR);  // Assign the input register
447     if (!MI->isDebugValue()) {
448       // Do not do these for DBG_VALUE as they can affect codegen.
449       UsedInInstr.set(PR);
450       getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
451     }
452     return MI;
453   }
454
455   // Otherwise, we need to fold it into the current instruction, or reload it.
456   // If we have registers available to hold the value, use them.
457   const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(VirtReg);
458   // If we already have a PhysReg (this happens when the instruction is a
459   // reg-to-reg copy with a PhysReg destination) use that.
460   if (!PhysReg || !TargetRegisterInfo::isPhysicalRegister(PhysReg) ||
461       !isPhysRegAvailable(PhysReg))
462     PhysReg = getFreeReg(RC);
463   int FrameIndex = getStackSpaceFor(VirtReg, RC);
464
465   if (PhysReg) {   // Register is available, allocate it!
466     assignVirtToPhysReg(VirtReg, PhysReg);
467   } else {         // No registers available.
468     // Force some poor hapless value out of the register file to
469     // make room for the new register, and reload it.
470     PhysReg = getReg(MBB, MI, VirtReg, true);
471   }
472
473   markVirtRegModified(VirtReg, false);   // Note that this reg was just reloaded
474
475   DEBUG(dbgs() << "  Reloading %reg" << VirtReg << " into "
476                << TRI->getName(PhysReg) << "\n");
477
478   // Add move instruction(s)
479   TII->loadRegFromStackSlot(MBB, MI, PhysReg, FrameIndex, RC, TRI);
480   ++NumLoads;    // Update statistics
481
482   MF->getRegInfo().setPhysRegUsed(PhysReg);
483   MI->getOperand(OpNum).setReg(PhysReg);  // Assign the input register
484   getVirtRegLastUse(VirtReg) = std::make_pair(MI, OpNum);
485
486   if (!ReloadedRegs.insert(PhysReg)) {
487     std::string msg;
488     raw_string_ostream Msg(msg);
489     Msg << "Ran out of registers during register allocation!";
490     if (MI->isInlineAsm()) {
491       Msg << "\nPlease check your inline asm statement for invalid "
492            << "constraints:\n";
493       MI->print(Msg, TM);
494     }
495     report_fatal_error(Msg.str());
496   }
497   for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
498        *SubRegs; ++SubRegs) {
499     if (ReloadedRegs.insert(*SubRegs)) continue;
500
501     std::string msg;
502     raw_string_ostream Msg(msg);
503     Msg << "Ran out of registers during register allocation!";
504     if (MI->isInlineAsm()) {
505       Msg << "\nPlease check your inline asm statement for invalid "
506            << "constraints:\n";
507       MI->print(Msg, TM);
508     }
509     report_fatal_error(Msg.str());
510   }
511
512   return MI;
513 }
514
515 /// isReadModWriteImplicitKill - True if this is an implicit kill for a
516 /// read/mod/write register, i.e. update partial register.
517 static bool isReadModWriteImplicitKill(MachineInstr *MI, unsigned Reg) {
518   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
519     MachineOperand &MO = MI->getOperand(i);
520     if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
521         MO.isDef() && !MO.isDead())
522       return true;
523   }
524   return false;
525 }
526
527 /// isReadModWriteImplicitDef - True if this is an implicit def for a
528 /// read/mod/write register, i.e. update partial register.
529 static bool isReadModWriteImplicitDef(MachineInstr *MI, unsigned Reg) {
530   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
531     MachineOperand &MO = MI->getOperand(i);
532     if (MO.isReg() && MO.getReg() == Reg && MO.isImplicit() &&
533         !MO.isDef() && MO.isKill())
534       return true;
535   }
536   return false;
537 }
538
539 void RAFast::AllocateBasicBlock(MachineBasicBlock &MBB) {
540   // loop over each instruction
541   MachineBasicBlock::iterator MII = MBB.begin();
542
543   DEBUG({
544       const BasicBlock *LBB = MBB.getBasicBlock();
545       if (LBB)
546         dbgs() << "\nStarting RegAlloc of BB: " << LBB->getName();
547     });
548
549   // Add live-in registers as active.
550   for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
551          E = MBB.livein_end(); I != E; ++I) {
552     unsigned Reg = *I;
553     MF->getRegInfo().setPhysRegUsed(Reg);
554     PhysRegsUsed[Reg] = 0;            // It is free and reserved now
555     for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
556          *SubRegs; ++SubRegs) {
557       if (PhysRegsUsed[*SubRegs] == -2) continue;
558       PhysRegsUsed[*SubRegs] = 0;  // It is free and reserved now
559       MF->getRegInfo().setPhysRegUsed(*SubRegs);
560     }
561   }
562
563   // Otherwise, sequentially allocate each instruction in the MBB.
564   while (MII != MBB.end()) {
565     MachineInstr *MI = MII++;
566     const TargetInstrDesc &TID = MI->getDesc();
567     DEBUG({
568         dbgs() << "\nStarting RegAlloc of: " << *MI;
569         dbgs() << "  Regs have values: ";
570         for (unsigned i = 0; i != TRI->getNumRegs(); ++i)
571           if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2)
572             dbgs() << "[" << TRI->getName(i)
573                    << ",%reg" << PhysRegsUsed[i] << "] ";
574         dbgs() << '\n';
575       });
576
577     // Track registers used by instruction.
578     UsedInInstr.reset();
579
580     // Determine whether this is a copy instruction.  The cases where the
581     // source or destination are phys regs are handled specially.
582     unsigned SrcCopyReg, DstCopyReg, SrcCopySubReg, DstCopySubReg;
583     unsigned SrcCopyPhysReg = 0U;
584     bool isCopy = TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
585                                    SrcCopySubReg, DstCopySubReg);
586     if (isCopy && SrcCopySubReg == 0 && DstCopySubReg == 0 &&
587         TargetRegisterInfo::isVirtualRegister(SrcCopyReg))
588       SrcCopyPhysReg = getVirt2PhysRegMapSlot(SrcCopyReg);
589
590     // Loop over the implicit uses, making sure they don't get reallocated.
591     if (TID.ImplicitUses) {
592       for (const unsigned *ImplicitUses = TID.ImplicitUses;
593            *ImplicitUses; ++ImplicitUses)
594         UsedInInstr.set(*ImplicitUses);
595     }
596
597     SmallVector<unsigned, 8> Kills;
598     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
599       MachineOperand &MO = MI->getOperand(i);
600       if (!MO.isReg() || !MO.isKill()) continue;
601
602       if (!MO.isImplicit())
603         Kills.push_back(MO.getReg());
604       else if (!isReadModWriteImplicitKill(MI, MO.getReg()))
605         // These are extra physical register kills when a sub-register
606         // is defined (def of a sub-register is a read/mod/write of the
607         // larger registers). Ignore.
608         Kills.push_back(MO.getReg());
609     }
610
611     // If any physical regs are earlyclobber, spill any value they might
612     // have in them, then mark them unallocatable.
613     // If any virtual regs are earlyclobber, allocate them now (before
614     // freeing inputs that are killed).
615     if (MI->isInlineAsm()) {
616       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
617         MachineOperand &MO = MI->getOperand(i);
618         if (!MO.isReg() || !MO.isDef() || !MO.isEarlyClobber() ||
619             !MO.getReg())
620           continue;
621
622         if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
623           unsigned DestVirtReg = MO.getReg();
624           unsigned DestPhysReg;
625
626           // If DestVirtReg already has a value, use it.
627           if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg)))
628             DestPhysReg = getReg(MBB, MI, DestVirtReg);
629           MF->getRegInfo().setPhysRegUsed(DestPhysReg);
630           markVirtRegModified(DestVirtReg);
631           getVirtRegLastUse(DestVirtReg) =
632                  std::make_pair((MachineInstr*)0, 0);
633           DEBUG(dbgs() << "  Assigning " << TRI->getName(DestPhysReg)
634                        << " to %reg" << DestVirtReg << "\n");
635           MO.setReg(DestPhysReg);  // Assign the earlyclobber register
636         } else {
637           unsigned Reg = MO.getReg();
638           if (PhysRegsUsed[Reg] == -2) continue;  // Something like ESP.
639           // These are extra physical register defs when a sub-register
640           // is defined (def of a sub-register is a read/mod/write of the
641           // larger registers). Ignore.
642           if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
643
644           MF->getRegInfo().setPhysRegUsed(Reg);
645           spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
646           PhysRegsUsed[Reg] = 0;            // It is free and reserved now
647
648           for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
649                *SubRegs; ++SubRegs) {
650             if (PhysRegsUsed[*SubRegs] == -2) continue;
651             MF->getRegInfo().setPhysRegUsed(*SubRegs);
652             PhysRegsUsed[*SubRegs] = 0;  // It is free and reserved now
653           }
654         }
655       }
656     }
657
658     // If a DBG_VALUE says something is located in a spilled register,
659     // change the DBG_VALUE to be undef, which prevents the register
660     // from being reloaded here.  Doing that would change the generated
661     // code, unless another use immediately follows this instruction.
662     if (MI->isDebugValue() &&
663         MI->getNumOperands()==3 && MI->getOperand(0).isReg()) {
664       unsigned VirtReg = MI->getOperand(0).getReg();
665       if (VirtReg && TargetRegisterInfo::isVirtualRegister(VirtReg) &&
666           !getVirt2PhysRegMapSlot(VirtReg))
667         MI->getOperand(0).setReg(0U);
668     }
669
670     // Get the used operands into registers.  This has the potential to spill
671     // incoming values if we are out of registers.  Note that we completely
672     // ignore physical register uses here.  We assume that if an explicit
673     // physical register is referenced by the instruction, that it is guaranteed
674     // to be live-in, or the input is badly hosed.
675     //
676     SmallSet<unsigned, 4> ReloadedRegs;
677     for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
678       MachineOperand &MO = MI->getOperand(i);
679       // here we are looking for only used operands (never def&use)
680       if (MO.isReg() && !MO.isDef() && MO.getReg() && !MO.isImplicit() &&
681           TargetRegisterInfo::isVirtualRegister(MO.getReg()))
682         MI = reloadVirtReg(MBB, MI, i, ReloadedRegs,
683                            isCopy ? DstCopyReg : 0);
684     }
685
686     // If this instruction is the last user of this register, kill the
687     // value, freeing the register being used, so it doesn't need to be
688     // spilled to memory.
689     //
690     for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
691       unsigned VirtReg = Kills[i];
692       unsigned PhysReg = VirtReg;
693       if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
694         // If the virtual register was never materialized into a register, it
695         // might not be in the map, but it won't hurt to zero it out anyway.
696         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
697         PhysReg = PhysRegSlot;
698         PhysRegSlot = 0;
699       } else if (PhysRegsUsed[PhysReg] == -2) {
700         // Unallocatable register dead, ignore.
701         continue;
702       } else {
703         assert((!PhysRegsUsed[PhysReg] || PhysRegsUsed[PhysReg] == -1) &&
704                "Silently clearing a virtual register?");
705       }
706
707       if (!PhysReg) continue;
708
709       DEBUG(dbgs() << "  Last use of " << TRI->getName(PhysReg)
710                    << "[%reg" << VirtReg <<"], removing it from live set\n");
711       removePhysReg(PhysReg);
712       for (const unsigned *SubRegs = TRI->getSubRegisters(PhysReg);
713            *SubRegs; ++SubRegs) {
714         if (PhysRegsUsed[*SubRegs] != -2) {
715           DEBUG(dbgs()  << "  Last use of "
716                         << TRI->getName(*SubRegs) << "[%reg" << VirtReg
717                         <<"], removing it from live set\n");
718           removePhysReg(*SubRegs);
719         }
720       }
721     }
722
723     // Track registers defined by instruction.
724     UsedInInstr.reset();
725
726     // Loop over all of the operands of the instruction, spilling registers that
727     // are defined, and marking explicit destinations in the PhysRegsUsed map.
728     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
729       MachineOperand &MO = MI->getOperand(i);
730       if (!MO.isReg() || !MO.isDef() || MO.isImplicit() || !MO.getReg() ||
731           MO.isEarlyClobber() ||
732           !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
733         continue;
734
735       unsigned Reg = MO.getReg();
736       if (PhysRegsUsed[Reg] == -2) continue;  // Something like ESP.
737       // These are extra physical register defs when a sub-register
738       // is defined (def of a sub-register is a read/mod/write of the
739       // larger registers). Ignore.
740       if (isReadModWriteImplicitDef(MI, MO.getReg())) continue;
741
742       MF->getRegInfo().setPhysRegUsed(Reg);
743       spillPhysReg(MBB, MI, Reg, true); // Spill any existing value in reg
744       PhysRegsUsed[Reg] = 0;            // It is free and reserved now
745
746       for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
747            *SubRegs; ++SubRegs) {
748         if (PhysRegsUsed[*SubRegs] == -2) continue;
749
750         MF->getRegInfo().setPhysRegUsed(*SubRegs);
751         PhysRegsUsed[*SubRegs] = 0;  // It is free and reserved now
752       }
753     }
754
755     // Loop over the implicit defs, spilling them as well.
756     if (TID.ImplicitDefs) {
757       for (const unsigned *ImplicitDefs = TID.ImplicitDefs;
758            *ImplicitDefs; ++ImplicitDefs) {
759         unsigned Reg = *ImplicitDefs;
760         if (PhysRegsUsed[Reg] != -2) {
761           spillPhysReg(MBB, MI, Reg, true);
762           PhysRegsUsed[Reg] = 0;            // It is free and reserved now
763         }
764         MF->getRegInfo().setPhysRegUsed(Reg);
765         for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
766              *SubRegs; ++SubRegs) {
767           if (PhysRegsUsed[*SubRegs] == -2) continue;
768
769           PhysRegsUsed[*SubRegs] = 0;  // It is free and reserved now
770           MF->getRegInfo().setPhysRegUsed(*SubRegs);
771         }
772       }
773     }
774
775     SmallVector<unsigned, 8> DeadDefs;
776     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
777       MachineOperand &MO = MI->getOperand(i);
778       if (MO.isReg() && MO.isDead())
779         DeadDefs.push_back(MO.getReg());
780     }
781
782     // Okay, we have allocated all of the source operands and spilled any values
783     // that would be destroyed by defs of this instruction.  Loop over the
784     // explicit defs and assign them to a register, spilling incoming values if
785     // we need to scavenge a register.
786     //
787     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
788       MachineOperand &MO = MI->getOperand(i);
789       if (!MO.isReg() || !MO.isDef() || !MO.getReg() ||
790           MO.isEarlyClobber() ||
791           !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
792         continue;
793
794       unsigned DestVirtReg = MO.getReg();
795       unsigned DestPhysReg;
796
797       // If DestVirtReg already has a value, use it.
798       if (!(DestPhysReg = getVirt2PhysRegMapSlot(DestVirtReg))) {
799         // If this is a copy try to reuse the input as the output;
800         // that will make the copy go away.
801         // If this is a copy, the source reg is a phys reg, and
802         // that reg is available, use that phys reg for DestPhysReg.
803         // If this is a copy, the source reg is a virtual reg, and
804         // the phys reg that was assigned to that virtual reg is now
805         // available, use that phys reg for DestPhysReg.  (If it's now
806         // available that means this was the last use of the source.)
807         if (isCopy &&
808             TargetRegisterInfo::isPhysicalRegister(SrcCopyReg) &&
809             isPhysRegAvailable(SrcCopyReg)) {
810           DestPhysReg = SrcCopyReg;
811           assignVirtToPhysReg(DestVirtReg, DestPhysReg);
812         } else if (isCopy &&
813             TargetRegisterInfo::isVirtualRegister(SrcCopyReg) &&
814             SrcCopyPhysReg && isPhysRegAvailable(SrcCopyPhysReg) &&
815             MF->getRegInfo().getRegClass(DestVirtReg)->
816                              contains(SrcCopyPhysReg)) {
817           DestPhysReg = SrcCopyPhysReg;
818           assignVirtToPhysReg(DestVirtReg, DestPhysReg);
819         } else
820           DestPhysReg = getReg(MBB, MI, DestVirtReg);
821       }
822       MF->getRegInfo().setPhysRegUsed(DestPhysReg);
823       markVirtRegModified(DestVirtReg);
824       getVirtRegLastUse(DestVirtReg) = std::make_pair((MachineInstr*)0, 0);
825       DEBUG(dbgs() << "  Assigning " << TRI->getName(DestPhysReg)
826                    << " to %reg" << DestVirtReg << "\n");
827       MO.setReg(DestPhysReg);  // Assign the output register
828       UsedInInstr.set(DestPhysReg);
829     }
830
831     // If this instruction defines any registers that are immediately dead,
832     // kill them now.
833     //
834     for (unsigned i = 0, e = DeadDefs.size(); i != e; ++i) {
835       unsigned VirtReg = DeadDefs[i];
836       unsigned PhysReg = VirtReg;
837       if (TargetRegisterInfo::isVirtualRegister(VirtReg)) {
838         unsigned &PhysRegSlot = getVirt2PhysRegMapSlot(VirtReg);
839         PhysReg = PhysRegSlot;
840         assert(PhysReg != 0);
841         PhysRegSlot = 0;
842       } else if (PhysRegsUsed[PhysReg] == -2) {
843         // Unallocatable register dead, ignore.
844         continue;
845       } else if (!PhysReg)
846         continue;
847
848       DEBUG(dbgs()  << "  Register " << TRI->getName(PhysReg)
849                     << " [%reg" << VirtReg
850                     << "] is never used, removing it from live set\n");
851       removePhysReg(PhysReg);
852       for (const unsigned *AliasSet = TRI->getAliasSet(PhysReg);
853            *AliasSet; ++AliasSet) {
854         if (PhysRegsUsed[*AliasSet] != -2) {
855           DEBUG(dbgs()  << "  Register " << TRI->getName(*AliasSet)
856                         << " [%reg" << *AliasSet
857                         << "] is never used, removing it from live set\n");
858           removePhysReg(*AliasSet);
859         }
860       }
861     }
862
863     // Finally, if this is a noop copy instruction, zap it.  (Except that if
864     // the copy is dead, it must be kept to avoid messing up liveness info for
865     // the register scavenger.  See pr4100.)
866     if (TII->isMoveInstr(*MI, SrcCopyReg, DstCopyReg,
867                          SrcCopySubReg, DstCopySubReg) &&
868         SrcCopyReg == DstCopyReg && DeadDefs.empty())
869       MBB.erase(MI);
870   }
871
872   MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
873
874   // Spill all physical registers holding virtual registers now.
875   for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
876     if (PhysRegsUsed[i] != -1 && PhysRegsUsed[i] != -2) {
877       if (unsigned VirtReg = PhysRegsUsed[i])
878         spillVirtReg(MBB, MI, VirtReg, i);
879       else
880         removePhysReg(i);
881     }
882 }
883
884 /// runOnMachineFunction - Register allocate the whole function
885 ///
886 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
887   DEBUG(dbgs() << "Machine Function\n");
888   MF = &Fn;
889   TM = &Fn.getTarget();
890   TRI = TM->getRegisterInfo();
891   TII = TM->getInstrInfo();
892
893   PhysRegsUsed.assign(TRI->getNumRegs(), -1);
894   UsedInInstr.resize(TRI->getNumRegs());
895
896   // At various places we want to efficiently check to see whether a register
897   // is allocatable.  To handle this, we mark all unallocatable registers as
898   // being pinned down, permanently.
899   {
900     BitVector Allocable = TRI->getAllocatableSet(Fn);
901     for (unsigned i = 0, e = Allocable.size(); i != e; ++i)
902       if (!Allocable[i])
903         PhysRegsUsed[i] = -2;  // Mark the reg unallocable.
904   }
905
906   // initialize the virtual->physical register map to have a 'null'
907   // mapping for all virtual registers
908   unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
909   StackSlotForVirtReg.grow(LastVirtReg);
910   Virt2PhysRegMap.grow(LastVirtReg);
911   Virt2LastUseMap.grow(LastVirtReg);
912   VirtRegModified.resize(LastVirtReg+1 -
913                          TargetRegisterInfo::FirstVirtualRegister);
914   UsedInMultipleBlocks.resize(LastVirtReg+1 -
915                               TargetRegisterInfo::FirstVirtualRegister);
916
917   // Loop over all of the basic blocks, eliminating virtual register references
918   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
919        MBB != MBBe; ++MBB)
920     AllocateBasicBlock(*MBB);
921
922   StackSlotForVirtReg.clear();
923   PhysRegsUsed.clear();
924   VirtRegModified.clear();
925   UsedInMultipleBlocks.clear();
926   Virt2PhysRegMap.clear();
927   Virt2LastUseMap.clear();
928   return true;
929 }
930
931 FunctionPass *llvm::createFastRegisterAllocator() {
932   return new RAFast();
933 }