If an available register falls through to a succ block, unset the last kill. Sorry...
[oota-llvm.git] / lib / CodeGen / VirtRegMap.cpp
1 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
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 file implements the VirtRegMap class.
11 //
12 // It also contains implementations of the the Spiller interface, which, given a
13 // virtual register map and a machine function, eliminates all virtual
14 // references by replacing them with physical register references - adding spill
15 // code as necessary.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "spiller"
20 #include "VirtRegMap.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/BitVector.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include <algorithm>
38 using namespace llvm;
39
40 STATISTIC(NumSpills  , "Number of register spills");
41 STATISTIC(NumPSpills , "Number of physical register spills");
42 STATISTIC(NumReMats  , "Number of re-materialization");
43 STATISTIC(NumDRM     , "Number of re-materializable defs elided");
44 STATISTIC(NumStores  , "Number of stores added");
45 STATISTIC(NumLoads   , "Number of loads added");
46 STATISTIC(NumReused  , "Number of values reused");
47 STATISTIC(NumDSE     , "Number of dead stores elided");
48 STATISTIC(NumDCE     , "Number of copies elided");
49 STATISTIC(NumDSS     , "Number of dead spill slots removed");
50 STATISTIC(NumCommutes, "Number of instructions commuted");
51 STATISTIC(NumOmitted , "Number of reloads omited");
52 STATISTIC(NumCopified, "Number of available reloads turned into copies");
53
54 namespace {
55   enum SpillerName { simple, local };
56 }
57
58 static cl::opt<SpillerName>
59 SpillerOpt("spiller",
60            cl::desc("Spiller to use: (default: local)"),
61            cl::Prefix,
62            cl::values(clEnumVal(simple, "simple spiller"),
63                       clEnumVal(local,  "local spiller"),
64                       clEnumValEnd),
65            cl::init(local));
66
67 //===----------------------------------------------------------------------===//
68 //  VirtRegMap implementation
69 //===----------------------------------------------------------------------===//
70
71 VirtRegMap::VirtRegMap(MachineFunction &mf)
72   : TII(*mf.getTarget().getInstrInfo()), MF(mf), 
73     Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT),
74     Virt2ReMatIdMap(NO_STACK_SLOT), Virt2SplitMap(0),
75     Virt2SplitKillMap(0), ReMatMap(NULL), ReMatId(MAX_STACK_SLOT+1),
76     LowSpillSlot(NO_STACK_SLOT), HighSpillSlot(NO_STACK_SLOT) {
77   SpillSlotToUsesMap.resize(8);
78   ImplicitDefed.resize(MF.getRegInfo().getLastVirtReg()+1-
79                        TargetRegisterInfo::FirstVirtualRegister);
80   grow();
81 }
82
83 void VirtRegMap::grow() {
84   unsigned LastVirtReg = MF.getRegInfo().getLastVirtReg();
85   Virt2PhysMap.grow(LastVirtReg);
86   Virt2StackSlotMap.grow(LastVirtReg);
87   Virt2ReMatIdMap.grow(LastVirtReg);
88   Virt2SplitMap.grow(LastVirtReg);
89   Virt2SplitKillMap.grow(LastVirtReg);
90   ReMatMap.grow(LastVirtReg);
91   ImplicitDefed.resize(LastVirtReg-TargetRegisterInfo::FirstVirtualRegister+1);
92 }
93
94 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
95   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
96   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
97          "attempt to assign stack slot to already spilled register");
98   const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(virtReg);
99   int SS = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
100                                                 RC->getAlignment());
101   if (LowSpillSlot == NO_STACK_SLOT)
102     LowSpillSlot = SS;
103   if (HighSpillSlot == NO_STACK_SLOT || SS > HighSpillSlot)
104     HighSpillSlot = SS;
105   unsigned Idx = SS-LowSpillSlot;
106   while (Idx >= SpillSlotToUsesMap.size())
107     SpillSlotToUsesMap.resize(SpillSlotToUsesMap.size()*2);
108   Virt2StackSlotMap[virtReg] = SS;
109   ++NumSpills;
110   return SS;
111 }
112
113 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
114   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
115   assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
116          "attempt to assign stack slot to already spilled register");
117   assert((SS >= 0 ||
118           (SS >= MF.getFrameInfo()->getObjectIndexBegin())) &&
119          "illegal fixed frame index");
120   Virt2StackSlotMap[virtReg] = SS;
121 }
122
123 int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
124   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
125   assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
126          "attempt to assign re-mat id to already spilled register");
127   Virt2ReMatIdMap[virtReg] = ReMatId;
128   return ReMatId++;
129 }
130
131 void VirtRegMap::assignVirtReMatId(unsigned virtReg, int id) {
132   assert(TargetRegisterInfo::isVirtualRegister(virtReg));
133   assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
134          "attempt to assign re-mat id to already spilled register");
135   Virt2ReMatIdMap[virtReg] = id;
136 }
137
138 int VirtRegMap::getEmergencySpillSlot(const TargetRegisterClass *RC) {
139   std::map<const TargetRegisterClass*, int>::iterator I =
140     EmergencySpillSlots.find(RC);
141   if (I != EmergencySpillSlots.end())
142     return I->second;
143   int SS = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
144                                                 RC->getAlignment());
145   if (LowSpillSlot == NO_STACK_SLOT)
146     LowSpillSlot = SS;
147   if (HighSpillSlot == NO_STACK_SLOT || SS > HighSpillSlot)
148     HighSpillSlot = SS;
149   EmergencySpillSlots[RC] = SS;
150   return SS;
151 }
152
153 void VirtRegMap::addSpillSlotUse(int FI, MachineInstr *MI) {
154   if (!MF.getFrameInfo()->isFixedObjectIndex(FI)) {
155     // If FI < LowSpillSlot, this stack reference was produced by
156     // instruction selection and is not a spill
157     if (FI >= LowSpillSlot) {
158       assert(FI >= 0 && "Spill slot index should not be negative!");
159       assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size()
160              && "Invalid spill slot");
161       SpillSlotToUsesMap[FI-LowSpillSlot].insert(MI);
162     }
163   }
164 }
165
166 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
167                             MachineInstr *NewMI, ModRef MRInfo) {
168   // Move previous memory references folded to new instruction.
169   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
170   for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
171          E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
172     MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
173     MI2VirtMap.erase(I++);
174   }
175
176   // add new memory reference
177   MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
178 }
179
180 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRInfo) {
181   MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(MI);
182   MI2VirtMap.insert(IP, std::make_pair(MI, std::make_pair(VirtReg, MRInfo)));
183 }
184
185 void VirtRegMap::RemoveMachineInstrFromMaps(MachineInstr *MI) {
186   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
187     MachineOperand &MO = MI->getOperand(i);
188     if (!MO.isFI())
189       continue;
190     int FI = MO.getIndex();
191     if (MF.getFrameInfo()->isFixedObjectIndex(FI))
192       continue;
193     // This stack reference was produced by instruction selection and
194     // is not a spill
195     if (FI < LowSpillSlot)
196       continue;
197     assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size()
198            && "Invalid spill slot");
199     SpillSlotToUsesMap[FI-LowSpillSlot].erase(MI);
200   }
201   MI2VirtMap.erase(MI);
202   SpillPt2VirtMap.erase(MI);
203   RestorePt2VirtMap.erase(MI);
204   EmergencySpillMap.erase(MI);
205 }
206
207 void VirtRegMap::print(std::ostream &OS) const {
208   const TargetRegisterInfo* TRI = MF.getTarget().getRegisterInfo();
209
210   OS << "********** REGISTER MAP **********\n";
211   for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
212          e = MF.getRegInfo().getLastVirtReg(); i <= e; ++i) {
213     if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
214       OS << "[reg" << i << " -> " << TRI->getName(Virt2PhysMap[i])
215          << "]\n";
216   }
217
218   for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
219          e = MF.getRegInfo().getLastVirtReg(); i <= e; ++i)
220     if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
221       OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
222   OS << '\n';
223 }
224
225 void VirtRegMap::dump() const {
226   print(cerr);
227 }
228
229
230 //===----------------------------------------------------------------------===//
231 // Simple Spiller Implementation
232 //===----------------------------------------------------------------------===//
233
234 Spiller::~Spiller() {}
235
236 namespace {
237   struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
238     bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
239   };
240 }
241
242 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
243   DOUT << "********** REWRITE MACHINE CODE **********\n";
244   DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
245   const TargetMachine &TM = MF.getTarget();
246   const TargetInstrInfo &TII = *TM.getInstrInfo();
247   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
248   
249
250   // LoadedRegs - Keep track of which vregs are loaded, so that we only load
251   // each vreg once (in the case where a spilled vreg is used by multiple
252   // operands).  This is always smaller than the number of operands to the
253   // current machine instr, so it should be small.
254   std::vector<unsigned> LoadedRegs;
255
256   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
257        MBBI != E; ++MBBI) {
258     DOUT << MBBI->getBasicBlock()->getName() << ":\n";
259     MachineBasicBlock &MBB = *MBBI;
260     for (MachineBasicBlock::iterator MII = MBB.begin(),
261            E = MBB.end(); MII != E; ++MII) {
262       MachineInstr &MI = *MII;
263       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
264         MachineOperand &MO = MI.getOperand(i);
265         if (MO.isReg() && MO.getReg()) {
266           if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
267             unsigned VirtReg = MO.getReg();
268             unsigned SubIdx = MO.getSubReg();
269             unsigned PhysReg = VRM.getPhys(VirtReg);
270             unsigned RReg = SubIdx ? TRI.getSubReg(PhysReg, SubIdx) : PhysReg;
271             if (!VRM.isAssignedReg(VirtReg)) {
272               int StackSlot = VRM.getStackSlot(VirtReg);
273               const TargetRegisterClass* RC =
274                 MF.getRegInfo().getRegClass(VirtReg);
275
276               if (MO.isUse() &&
277                   std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
278                   == LoadedRegs.end()) {
279                 TII.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
280                 MachineInstr *LoadMI = prior(MII);
281                 VRM.addSpillSlotUse(StackSlot, LoadMI);
282                 LoadedRegs.push_back(VirtReg);
283                 ++NumLoads;
284                 DOUT << '\t' << *LoadMI;
285               }
286
287               if (MO.isDef()) {
288                 TII.storeRegToStackSlot(MBB, next(MII), PhysReg, true,
289                                         StackSlot, RC);
290                 MachineInstr *StoreMI = next(MII);
291                 VRM.addSpillSlotUse(StackSlot, StoreMI);
292                 ++NumStores;
293               }
294             }
295             MF.getRegInfo().setPhysRegUsed(RReg);
296             MI.getOperand(i).setReg(RReg);
297           } else {
298             MF.getRegInfo().setPhysRegUsed(MO.getReg());
299           }
300         }
301       }
302
303       DOUT << '\t' << MI;
304       LoadedRegs.clear();
305     }
306   }
307   return true;
308 }
309
310 //===----------------------------------------------------------------------===//
311 //  Local Spiller Implementation
312 //===----------------------------------------------------------------------===//
313
314 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
315 /// top down, keep track of which spills slots or remat are available in each
316 /// register.
317 ///
318 /// Note that not all physregs are created equal here.  In particular, some
319 /// physregs are reloads that we are allowed to clobber or ignore at any time.
320 /// Other physregs are values that the register allocated program is using that
321 /// we cannot CHANGE, but we can read if we like.  We keep track of this on a 
322 /// per-stack-slot / remat id basis as the low bit in the value of the
323 /// SpillSlotsAvailable entries.  The predicate 'canClobberPhysReg()' checks
324 /// this bit and addAvailable sets it if.
325 namespace {
326 class VISIBILITY_HIDDEN AvailableSpills {
327   const TargetRegisterInfo *TRI;
328   const TargetInstrInfo *TII;
329
330   // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
331   // or remat'ed virtual register values that are still available, due to being
332   // loaded or stored to, but not invalidated yet.
333   std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
334     
335   // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
336   // indicating which stack slot values are currently held by a physreg.  This
337   // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
338   // physreg is modified.
339   std::multimap<unsigned, int> PhysRegsAvailable;
340   
341   void disallowClobberPhysRegOnly(unsigned PhysReg);
342
343   void ClobberPhysRegOnly(unsigned PhysReg);
344 public:
345   AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
346     : TRI(tri), TII(tii) {
347   }
348
349   /// clear - Reset the state.
350   void clear() {
351     SpillSlotsOrReMatsAvailable.clear();
352     PhysRegsAvailable.clear();
353   }
354   
355   const TargetRegisterInfo *getRegInfo() const { return TRI; }
356
357   /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
358   /// available in a  physical register, return that PhysReg, otherwise
359   /// return 0.
360   unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
361     std::map<int, unsigned>::const_iterator I =
362       SpillSlotsOrReMatsAvailable.find(Slot);
363     if (I != SpillSlotsOrReMatsAvailable.end()) {
364       return I->second >> 1;  // Remove the CanClobber bit.
365     }
366     return 0;
367   }
368
369   /// addAvailable - Mark that the specified stack slot / remat is available in
370   /// the specified physreg.  If CanClobber is true, the physreg can be modified
371   /// at any time without changing the semantics of the program.
372   void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
373     // If this stack slot is thought to be available in some other physreg, 
374     // remove its record.
375     ModifyStackSlotOrReMat(SlotOrReMat);
376     
377     PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
378     SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) | (unsigned)CanClobber;
379   
380     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
381       DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
382     else
383       DOUT << "Remembering SS#" << SlotOrReMat;
384     DOUT << " in physreg " << TRI->getName(Reg) << "\n";
385   }
386
387   /// canClobberPhysReg - Return true if the spiller is allowed to change the 
388   /// value of the specified stackslot register if it desires.  The specified
389   /// stack slot must be available in a physreg for this query to make sense.
390   bool canClobberPhysReg(int SlotOrReMat) const {
391     assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
392            "Value not available!");
393     return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
394   }
395
396   /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
397   /// stackslot register. The register is still available but is no longer
398   /// allowed to be modifed.
399   void disallowClobberPhysReg(unsigned PhysReg);
400   
401   /// ClobberPhysReg - This is called when the specified physreg changes
402   /// value.  We use this to invalidate any info about stuff that lives in
403   /// it and any of its aliases.
404   void ClobberPhysReg(unsigned PhysReg);
405
406   /// ModifyStackSlotOrReMat - This method is called when the value in a stack
407   /// slot changes.  This removes information about which register the previous
408   /// value for this slot lives in (as the previous value is dead now).
409   void ModifyStackSlotOrReMat(int SlotOrReMat);
410
411   /// AddAvailableRegsToLiveIn - Availability information is being kept coming
412   /// into the specified MBB. Add available physical registers as potential
413   /// live-in's. If they are reused in the MBB, they will be added to the
414   /// live-in set to make register scavenger and post-allocation scheduler.
415   void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
416                                 std::vector<MachineOperand*> &KillOps);
417 };
418 }
419
420 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
421 /// stackslot register. The register is still available but is no longer
422 /// allowed to be modifed.
423 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
424   std::multimap<unsigned, int>::iterator I =
425     PhysRegsAvailable.lower_bound(PhysReg);
426   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
427     int SlotOrReMat = I->second;
428     I++;
429     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
430            "Bidirectional map mismatch!");
431     SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
432     DOUT << "PhysReg " << TRI->getName(PhysReg)
433          << " copied, it is available for use but can no longer be modified\n";
434   }
435 }
436
437 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
438 /// stackslot register and its aliases. The register and its aliases may
439 /// still available but is no longer allowed to be modifed.
440 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
441   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
442     disallowClobberPhysRegOnly(*AS);
443   disallowClobberPhysRegOnly(PhysReg);
444 }
445
446 /// ClobberPhysRegOnly - This is called when the specified physreg changes
447 /// value.  We use this to invalidate any info about stuff we thing lives in it.
448 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
449   std::multimap<unsigned, int>::iterator I =
450     PhysRegsAvailable.lower_bound(PhysReg);
451   while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
452     int SlotOrReMat = I->second;
453     PhysRegsAvailable.erase(I++);
454     assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
455            "Bidirectional map mismatch!");
456     SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
457     DOUT << "PhysReg " << TRI->getName(PhysReg)
458          << " clobbered, invalidating ";
459     if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
460       DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
461     else
462       DOUT << "SS#" << SlotOrReMat << "\n";
463   }
464 }
465
466 /// ClobberPhysReg - This is called when the specified physreg changes
467 /// value.  We use this to invalidate any info about stuff we thing lives in
468 /// it and any of its aliases.
469 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
470   for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
471     ClobberPhysRegOnly(*AS);
472   ClobberPhysRegOnly(PhysReg);
473 }
474
475 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
476 /// slot changes.  This removes information about which register the previous
477 /// value for this slot lives in (as the previous value is dead now).
478 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
479   std::map<int, unsigned>::iterator It =
480     SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
481   if (It == SpillSlotsOrReMatsAvailable.end()) return;
482   unsigned Reg = It->second >> 1;
483   SpillSlotsOrReMatsAvailable.erase(It);
484   
485   // This register may hold the value of multiple stack slots, only remove this
486   // stack slot from the set of values the register contains.
487   std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
488   for (; ; ++I) {
489     assert(I != PhysRegsAvailable.end() && I->first == Reg &&
490            "Map inverse broken!");
491     if (I->second == SlotOrReMat) break;
492   }
493   PhysRegsAvailable.erase(I);
494 }
495
496 /// InvalidateKill - A MI that defines the specified register is being deleted,
497 /// invalidate the register kill information.
498 static void InvalidateKill(unsigned Reg, BitVector &RegKills,
499                            std::vector<MachineOperand*> &KillOps) {
500   if (RegKills[Reg]) {
501     KillOps[Reg]->setIsKill(false);
502     KillOps[Reg] = NULL;
503     RegKills.reset(Reg);
504   }
505 }
506
507 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
508 /// into the specified MBB. Add available physical registers as potential
509 /// live-in's. If they are reused in the MBB, they will be added to the
510 /// live-in set to make register scavenger and post-allocation scheduler.
511 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
512                                         BitVector &RegKills,
513                                         std::vector<MachineOperand*> &KillOps) {
514   std::set<unsigned> NotAvailable;
515   for (std::multimap<unsigned, int>::iterator
516          I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
517        I != E; ++I) {
518     unsigned Reg = I->first;
519     bool MakeAvail = true;
520     const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
521     // FIXME: A temporary workaround. We can't reuse available value if it's
522     // not safe to move the def of the virtual register's class. e.g.
523     // X86::RFP* register classes. Do not add it as a live-in.
524     if (!TII->isSafeToMoveRegClassDefs(RC))
525       MakeAvail = false;
526     if (MBB.isLiveIn(Reg))
527       // It's already livein somehow. Be conservative, do not make it available.
528       MakeAvail = false;
529
530     if (!MakeAvail) 
531       // This is no longer available.
532       NotAvailable.insert(Reg);
533     else {
534       MBB.addLiveIn(Reg);
535       InvalidateKill(Reg, RegKills, KillOps);
536     }
537
538     // Skip over the same register.
539     std::multimap<unsigned, int>::iterator NI = next(I);
540     while (NI != E && NI->first == Reg) {
541       ++I;
542       ++NI;
543     }
544   }
545
546   for (std::set<unsigned>::iterator I = NotAvailable.begin(),
547          E = NotAvailable.end(); I != E; ++I) {
548     ClobberPhysReg(*I);
549     for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
550        *SubRegs; ++SubRegs)
551       ClobberPhysReg(*SubRegs);
552   }
553 }
554
555 /// findSinglePredSuccessor - Return via reference a vector of machine basic
556 /// blocks each of which is a successor of the specified BB and has no other
557 /// predecessor.
558 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
559                                    SmallVectorImpl<MachineBasicBlock *> &Succs) {
560   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
561          SE = MBB->succ_end(); SI != SE; ++SI) {
562     MachineBasicBlock *SuccMBB = *SI;
563     if (SuccMBB->pred_size() == 1)
564       Succs.push_back(SuccMBB);
565   }
566 }
567
568 namespace {
569   /// LocalSpiller - This spiller does a simple pass over the machine basic
570   /// block to attempt to keep spills in registers as much as possible for
571   /// blocks that have low register pressure (the vreg may be spilled due to
572   /// register pressure in other blocks).
573   class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
574     MachineRegisterInfo *RegInfo;
575     const TargetRegisterInfo *TRI;
576     const TargetInstrInfo *TII;
577     DenseMap<MachineInstr*, unsigned> DistanceMap;
578   public:
579     bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
580       RegInfo = &MF.getRegInfo(); 
581       TRI = MF.getTarget().getRegisterInfo();
582       TII = MF.getTarget().getInstrInfo();
583       DOUT << "\n**** Local spiller rewriting function '"
584            << MF.getFunction()->getName() << "':\n";
585       DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
586               " ****\n";
587       DEBUG(MF.dump());
588
589       // Spills - Keep track of which spilled values are available in physregs
590       // so that we can choose to reuse the physregs instead of emitting
591       // reloads. This is usually refreshed per basic block.
592       AvailableSpills Spills(TRI, TII);
593
594       // Keep track of kill information.
595       BitVector RegKills(TRI->getNumRegs());
596       std::vector<MachineOperand*> KillOps;
597       KillOps.resize(TRI->getNumRegs(), NULL);
598
599       // SingleEntrySuccs - Successor blocks which have a single predecessor.
600       SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
601       SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
602
603       // Traverse the basic blocks depth first.
604       MachineBasicBlock *Entry = MF.begin();
605       SmallPtrSet<MachineBasicBlock*,16> Visited;
606       for (df_ext_iterator<MachineBasicBlock*,
607              SmallPtrSet<MachineBasicBlock*,16> >
608              DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
609            DFI != E; ++DFI) {
610         MachineBasicBlock *MBB = *DFI;
611         if (!EarlyVisited.count(MBB))
612           RewriteMBB(*MBB, VRM, Spills, RegKills, KillOps);
613
614         // If this MBB is the only predecessor of a successor. Keep the
615         // availability information and visit it next.
616         do {
617           // Keep visiting single predecessor successor as long as possible.
618           SinglePredSuccs.clear();
619           findSinglePredSuccessor(MBB, SinglePredSuccs);
620           if (SinglePredSuccs.empty())
621             MBB = 0;
622           else {
623             // FIXME: More than one successors, each of which has MBB has
624             // the only predecessor.
625             MBB = SinglePredSuccs[0];
626             if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
627               Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
628               RewriteMBB(*MBB, VRM, Spills, RegKills, KillOps);
629             }
630           }
631         } while (MBB);
632
633         // Clear the availability info.
634         Spills.clear();
635       }
636
637       DOUT << "**** Post Machine Instrs ****\n";
638       DEBUG(MF.dump());
639
640       // Mark unused spill slots.
641       MachineFrameInfo *MFI = MF.getFrameInfo();
642       int SS = VRM.getLowSpillSlot();
643       if (SS != VirtRegMap::NO_STACK_SLOT)
644         for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
645           if (!VRM.isSpillSlotUsed(SS)) {
646             MFI->RemoveStackObject(SS);
647             ++NumDSS;
648           }
649
650       return true;
651     }
652   private:
653     void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
654                           unsigned Reg, BitVector &RegKills,
655                           std::vector<MachineOperand*> &KillOps);
656     bool PrepForUnfoldOpti(MachineBasicBlock &MBB,
657                            MachineBasicBlock::iterator &MII,
658                            std::vector<MachineInstr*> &MaybeDeadStores,
659                            AvailableSpills &Spills, BitVector &RegKills,
660                            std::vector<MachineOperand*> &KillOps,
661                            VirtRegMap &VRM);
662     bool CommuteToFoldReload(MachineBasicBlock &MBB,
663                              MachineBasicBlock::iterator &MII,
664                              unsigned VirtReg, unsigned SrcReg, int SS,
665                              AvailableSpills &Spills,
666                              BitVector &RegKills,
667                              std::vector<MachineOperand*> &KillOps,
668                              const TargetRegisterInfo *TRI,
669                              VirtRegMap &VRM);
670     void SpillRegToStackSlot(MachineBasicBlock &MBB,
671                              MachineBasicBlock::iterator &MII,
672                              int Idx, unsigned PhysReg, int StackSlot,
673                              const TargetRegisterClass *RC,
674                              bool isAvailable, MachineInstr *&LastStore,
675                              AvailableSpills &Spills,
676                              SmallSet<MachineInstr*, 4> &ReMatDefs,
677                              BitVector &RegKills,
678                              std::vector<MachineOperand*> &KillOps,
679                              VirtRegMap &VRM);
680     void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
681                     AvailableSpills &Spills,
682                     BitVector &RegKills, std::vector<MachineOperand*> &KillOps);
683   };
684 }
685
686 /// InvalidateKills - MI is going to be deleted. If any of its operands are
687 /// marked kill, then invalidate the information.
688 static void InvalidateKills(MachineInstr &MI, BitVector &RegKills,
689                             std::vector<MachineOperand*> &KillOps,
690                             SmallVector<unsigned, 2> *KillRegs = NULL) {
691   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
692     MachineOperand &MO = MI.getOperand(i);
693     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
694       continue;
695     unsigned Reg = MO.getReg();
696     if (TargetRegisterInfo::isVirtualRegister(Reg))
697       continue;
698     if (KillRegs)
699       KillRegs->push_back(Reg);
700     assert(Reg < KillOps.size());
701     if (KillOps[Reg] == &MO) {
702       RegKills.reset(Reg);
703       KillOps[Reg] = NULL;
704     }
705   }
706 }
707
708 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
709 /// (since it's spill instruction is removed), mark it isDead. Also checks if
710 /// the def MI has other definition operands that are not dead. Returns it by
711 /// reference.
712 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
713                              MachineInstr &NewDef, unsigned Reg,
714                              bool &HasLiveDef) {
715   // Due to remat, it's possible this reg isn't being reused. That is,
716   // the def of this reg (by prev MI) is now dead.
717   MachineInstr *DefMI = I;
718   MachineOperand *DefOp = NULL;
719   for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
720     MachineOperand &MO = DefMI->getOperand(i);
721     if (MO.isReg() && MO.isDef()) {
722       if (MO.getReg() == Reg)
723         DefOp = &MO;
724       else if (!MO.isDead())
725         HasLiveDef = true;
726     }
727   }
728   if (!DefOp)
729     return false;
730
731   bool FoundUse = false, Done = false;
732   MachineBasicBlock::iterator E = &NewDef;
733   ++I; ++E;
734   for (; !Done && I != E; ++I) {
735     MachineInstr *NMI = I;
736     for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
737       MachineOperand &MO = NMI->getOperand(j);
738       if (!MO.isReg() || MO.getReg() != Reg)
739         continue;
740       if (MO.isUse())
741         FoundUse = true;
742       Done = true; // Stop after scanning all the operands of this MI.
743     }
744   }
745   if (!FoundUse) {
746     // Def is dead!
747     DefOp->setIsDead();
748     return true;
749   }
750   return false;
751 }
752
753 /// UpdateKills - Track and update kill info. If a MI reads a register that is
754 /// marked kill, then it must be due to register reuse. Transfer the kill info
755 /// over.
756 static void UpdateKills(MachineInstr &MI, BitVector &RegKills,
757                         std::vector<MachineOperand*> &KillOps,
758                         const TargetRegisterInfo* TRI) {
759   const TargetInstrDesc &TID = MI.getDesc();
760   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
761     MachineOperand &MO = MI.getOperand(i);
762     if (!MO.isReg() || !MO.isUse())
763       continue;
764     unsigned Reg = MO.getReg();
765     if (Reg == 0)
766       continue;
767     
768     if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
769       // That can't be right. Register is killed but not re-defined and it's
770       // being reused. Let's fix that.
771       KillOps[Reg]->setIsKill(false);
772       KillOps[Reg] = NULL;
773       RegKills.reset(Reg);
774       if (i < TID.getNumOperands() &&
775           TID.getOperandConstraint(i, TOI::TIED_TO) == -1)
776         // Unless it's a two-address operand, this is the new kill.
777         MO.setIsKill();
778     }
779     if (MO.isKill()) {
780       RegKills.set(Reg);
781       KillOps[Reg] = &MO;
782     }
783   }
784
785   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
786     const MachineOperand &MO = MI.getOperand(i);
787     if (!MO.isReg() || !MO.isDef())
788       continue;
789     unsigned Reg = MO.getReg();
790     RegKills.reset(Reg);
791     KillOps[Reg] = NULL;
792     // It also defines (or partially define) aliases.
793     for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
794       RegKills.reset(*AS);
795       KillOps[*AS] = NULL;
796     }
797   }
798 }
799
800 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
801 ///
802 static void ReMaterialize(MachineBasicBlock &MBB,
803                           MachineBasicBlock::iterator &MII,
804                           unsigned DestReg, unsigned Reg,
805                           const TargetInstrInfo *TII,
806                           const TargetRegisterInfo *TRI,
807                           VirtRegMap &VRM) {
808   TII->reMaterialize(MBB, MII, DestReg, VRM.getReMaterializedMI(Reg));
809   MachineInstr *NewMI = prior(MII);
810   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
811     MachineOperand &MO = NewMI->getOperand(i);
812     if (!MO.isReg() || MO.getReg() == 0)
813       continue;
814     unsigned VirtReg = MO.getReg();
815     if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
816       continue;
817     assert(MO.isUse());
818     unsigned SubIdx = MO.getSubReg();
819     unsigned Phys = VRM.getPhys(VirtReg);
820     assert(Phys);
821     unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
822     MO.setReg(RReg);
823   }
824   ++NumReMats;
825 }
826
827
828 // ReusedOp - For each reused operand, we keep track of a bit of information, in
829 // case we need to rollback upon processing a new operand.  See comments below.
830 namespace {
831   struct ReusedOp {
832     // The MachineInstr operand that reused an available value.
833     unsigned Operand;
834
835     // StackSlotOrReMat - The spill slot or remat id of the value being reused.
836     unsigned StackSlotOrReMat;
837
838     // PhysRegReused - The physical register the value was available in.
839     unsigned PhysRegReused;
840
841     // AssignedPhysReg - The physreg that was assigned for use by the reload.
842     unsigned AssignedPhysReg;
843     
844     // VirtReg - The virtual register itself.
845     unsigned VirtReg;
846
847     ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
848              unsigned vreg)
849       : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
850         AssignedPhysReg(apr), VirtReg(vreg) {}
851   };
852   
853   /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
854   /// is reused instead of reloaded.
855   class VISIBILITY_HIDDEN ReuseInfo {
856     MachineInstr &MI;
857     std::vector<ReusedOp> Reuses;
858     BitVector PhysRegsClobbered;
859   public:
860     ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
861       PhysRegsClobbered.resize(tri->getNumRegs());
862     }
863     
864     bool hasReuses() const {
865       return !Reuses.empty();
866     }
867     
868     /// addReuse - If we choose to reuse a virtual register that is already
869     /// available instead of reloading it, remember that we did so.
870     void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
871                   unsigned PhysRegReused, unsigned AssignedPhysReg,
872                   unsigned VirtReg) {
873       // If the reload is to the assigned register anyway, no undo will be
874       // required.
875       if (PhysRegReused == AssignedPhysReg) return;
876       
877       // Otherwise, remember this.
878       Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused, 
879                                 AssignedPhysReg, VirtReg));
880     }
881
882     void markClobbered(unsigned PhysReg) {
883       PhysRegsClobbered.set(PhysReg);
884     }
885
886     bool isClobbered(unsigned PhysReg) const {
887       return PhysRegsClobbered.test(PhysReg);
888     }
889     
890     /// GetRegForReload - We are about to emit a reload into PhysReg.  If there
891     /// is some other operand that is using the specified register, either pick
892     /// a new register to use, or evict the previous reload and use this reg. 
893     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
894                              AvailableSpills &Spills,
895                              std::vector<MachineInstr*> &MaybeDeadStores,
896                              SmallSet<unsigned, 8> &Rejected,
897                              BitVector &RegKills,
898                              std::vector<MachineOperand*> &KillOps,
899                              VirtRegMap &VRM) {
900       const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
901                                    .getInstrInfo();
902       
903       if (Reuses.empty()) return PhysReg;  // This is most often empty.
904
905       for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
906         ReusedOp &Op = Reuses[ro];
907         // If we find some other reuse that was supposed to use this register
908         // exactly for its reload, we can change this reload to use ITS reload
909         // register. That is, unless its reload register has already been
910         // considered and subsequently rejected because it has also been reused
911         // by another operand.
912         if (Op.PhysRegReused == PhysReg &&
913             Rejected.count(Op.AssignedPhysReg) == 0) {
914           // Yup, use the reload register that we didn't use before.
915           unsigned NewReg = Op.AssignedPhysReg;
916           Rejected.insert(PhysReg);
917           return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
918                                  RegKills, KillOps, VRM);
919         } else {
920           // Otherwise, we might also have a problem if a previously reused
921           // value aliases the new register.  If so, codegen the previous reload
922           // and use this one.          
923           unsigned PRRU = Op.PhysRegReused;
924           const TargetRegisterInfo *TRI = Spills.getRegInfo();
925           if (TRI->areAliases(PRRU, PhysReg)) {
926             // Okay, we found out that an alias of a reused register
927             // was used.  This isn't good because it means we have
928             // to undo a previous reuse.
929             MachineBasicBlock *MBB = MI->getParent();
930             const TargetRegisterClass *AliasRC =
931               MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
932
933             // Copy Op out of the vector and remove it, we're going to insert an
934             // explicit load for it.
935             ReusedOp NewOp = Op;
936             Reuses.erase(Reuses.begin()+ro);
937
938             // Ok, we're going to try to reload the assigned physreg into the
939             // slot that we were supposed to in the first place.  However, that
940             // register could hold a reuse.  Check to see if it conflicts or
941             // would prefer us to use a different register.
942             unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
943                                                   MI, Spills, MaybeDeadStores,
944                                               Rejected, RegKills, KillOps, VRM);
945             
946             MachineBasicBlock::iterator MII = MI;
947             if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
948               ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
949             } else {
950               TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
951                                         NewOp.StackSlotOrReMat, AliasRC);
952               MachineInstr *LoadMI = prior(MII);
953               VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
954               // Any stores to this stack slot are not dead anymore.
955               MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;            
956               ++NumLoads;
957             }
958             Spills.ClobberPhysReg(NewPhysReg);
959             Spills.ClobberPhysReg(NewOp.PhysRegReused);
960
961             unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
962             unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
963             MI->getOperand(NewOp.Operand).setReg(RReg);
964             
965             Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
966             --MII;
967             UpdateKills(*MII, RegKills, KillOps, TRI);
968             DOUT << '\t' << *MII;
969             
970             DOUT << "Reuse undone!\n";
971             --NumReused;
972             
973             // Finally, PhysReg is now available, go ahead and use it.
974             return PhysReg;
975           }
976         }
977       }
978       return PhysReg;
979     }
980
981     /// GetRegForReload - Helper for the above GetRegForReload(). Add a
982     /// 'Rejected' set to remember which registers have been considered and
983     /// rejected for the reload. This avoids infinite looping in case like
984     /// this:
985     /// t1 := op t2, t3
986     /// t2 <- assigned r0 for use by the reload but ended up reuse r1
987     /// t3 <- assigned r1 for use by the reload but ended up reuse r0
988     /// t1 <- desires r1
989     ///       sees r1 is taken by t2, tries t2's reload register r0
990     ///       sees r0 is taken by t3, tries t3's reload register r1
991     ///       sees r1 is taken by t2, tries t2's reload register r0 ...
992     unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
993                              AvailableSpills &Spills,
994                              std::vector<MachineInstr*> &MaybeDeadStores,
995                              BitVector &RegKills,
996                              std::vector<MachineOperand*> &KillOps,
997                              VirtRegMap &VRM) {
998       SmallSet<unsigned, 8> Rejected;
999       return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
1000                              RegKills, KillOps, VRM);
1001     }
1002   };
1003 }
1004
1005 /// PrepForUnfoldOpti - Turn a store folding instruction into a load folding
1006 /// instruction. e.g.
1007 ///     xorl  %edi, %eax
1008 ///     movl  %eax, -32(%ebp)
1009 ///     movl  -36(%ebp), %eax
1010 ///     orl   %eax, -32(%ebp)
1011 /// ==>
1012 ///     xorl  %edi, %eax
1013 ///     orl   -36(%ebp), %eax
1014 ///     mov   %eax, -32(%ebp)
1015 /// This enables unfolding optimization for a subsequent instruction which will
1016 /// also eliminate the newly introduced store instruction.
1017 bool LocalSpiller::PrepForUnfoldOpti(MachineBasicBlock &MBB,
1018                                     MachineBasicBlock::iterator &MII,
1019                                     std::vector<MachineInstr*> &MaybeDeadStores,
1020                                     AvailableSpills &Spills,
1021                                     BitVector &RegKills,
1022                                     std::vector<MachineOperand*> &KillOps,
1023                                     VirtRegMap &VRM) {
1024   MachineFunction &MF = *MBB.getParent();
1025   MachineInstr &MI = *MII;
1026   unsigned UnfoldedOpc = 0;
1027   unsigned UnfoldPR = 0;
1028   unsigned UnfoldVR = 0;
1029   int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1030   VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1031   for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1032     // Only transform a MI that folds a single register.
1033     if (UnfoldedOpc)
1034       return false;
1035     UnfoldVR = I->second.first;
1036     VirtRegMap::ModRef MR = I->second.second;
1037     // MI2VirtMap be can updated which invalidate the iterator.
1038     // Increment the iterator first.
1039     ++I; 
1040     if (VRM.isAssignedReg(UnfoldVR))
1041       continue;
1042     // If this reference is not a use, any previous store is now dead.
1043     // Otherwise, the store to this stack slot is not dead anymore.
1044     FoldedSS = VRM.getStackSlot(UnfoldVR);
1045     MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1046     if (DeadStore && (MR & VirtRegMap::isModRef)) {
1047       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1048       if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1049         continue;
1050       UnfoldPR = PhysReg;
1051       UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1052                                                     false, true);
1053     }
1054   }
1055
1056   if (!UnfoldedOpc)
1057     return false;
1058
1059   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1060     MachineOperand &MO = MI.getOperand(i);
1061     if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1062       continue;
1063     unsigned VirtReg = MO.getReg();
1064     if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1065       continue;
1066     if (VRM.isAssignedReg(VirtReg)) {
1067       unsigned PhysReg = VRM.getPhys(VirtReg);
1068       if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1069         return false;
1070     } else if (VRM.isReMaterialized(VirtReg))
1071       continue;
1072     int SS = VRM.getStackSlot(VirtReg);
1073     unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1074     if (PhysReg) {
1075       if (TRI->regsOverlap(PhysReg, UnfoldPR))
1076         return false;
1077       continue;
1078     }
1079     if (VRM.hasPhys(VirtReg)) {
1080       PhysReg = VRM.getPhys(VirtReg);
1081       if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1082         continue;
1083     }
1084
1085     // Ok, we'll need to reload the value into a register which makes
1086     // it impossible to perform the store unfolding optimization later.
1087     // Let's see if it is possible to fold the load if the store is
1088     // unfolded. This allows us to perform the store unfolding
1089     // optimization.
1090     SmallVector<MachineInstr*, 4> NewMIs;
1091     if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1092       assert(NewMIs.size() == 1);
1093       MachineInstr *NewMI = NewMIs.back();
1094       NewMIs.clear();
1095       int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1096       assert(Idx != -1);
1097       SmallVector<unsigned, 1> Ops;
1098       Ops.push_back(Idx);
1099       MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1100       if (FoldedMI) {
1101         VRM.addSpillSlotUse(SS, FoldedMI);
1102         if (!VRM.hasPhys(UnfoldVR))
1103           VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1104         VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1105         MII = MBB.insert(MII, FoldedMI);
1106         InvalidateKills(MI, RegKills, KillOps);
1107         VRM.RemoveMachineInstrFromMaps(&MI);
1108         MBB.erase(&MI);
1109         MF.DeleteMachineInstr(NewMI);
1110         return true;
1111       }
1112       MF.DeleteMachineInstr(NewMI);
1113     }
1114   }
1115   return false;
1116 }
1117
1118 /// CommuteToFoldReload -
1119 /// Look for
1120 /// r1 = load fi#1
1121 /// r1 = op r1, r2<kill>
1122 /// store r1, fi#1
1123 ///
1124 /// If op is commutable and r2 is killed, then we can xform these to
1125 /// r2 = op r2, fi#1
1126 /// store r2, fi#1
1127 bool LocalSpiller::CommuteToFoldReload(MachineBasicBlock &MBB,
1128                                     MachineBasicBlock::iterator &MII,
1129                                     unsigned VirtReg, unsigned SrcReg, int SS,
1130                                     AvailableSpills &Spills,
1131                                     BitVector &RegKills,
1132                                     std::vector<MachineOperand*> &KillOps,
1133                                     const TargetRegisterInfo *TRI,
1134                                     VirtRegMap &VRM) {
1135   if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1136     return false;
1137
1138   MachineFunction &MF = *MBB.getParent();
1139   MachineInstr &MI = *MII;
1140   MachineBasicBlock::iterator DefMII = prior(MII);
1141   MachineInstr *DefMI = DefMII;
1142   const TargetInstrDesc &TID = DefMI->getDesc();
1143   unsigned NewDstIdx;
1144   if (DefMII != MBB.begin() &&
1145       TID.isCommutable() &&
1146       TII->CommuteChangesDestination(DefMI, NewDstIdx)) {
1147     MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1148     unsigned NewReg = NewDstMO.getReg();
1149     if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1150       return false;
1151     MachineInstr *ReloadMI = prior(DefMII);
1152     int FrameIdx;
1153     unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1154     if (DestReg != SrcReg || FrameIdx != SS)
1155       return false;
1156     int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1157     if (UseIdx == -1)
1158       return false;
1159     int DefIdx = TID.getOperandConstraint(UseIdx, TOI::TIED_TO);
1160     if (DefIdx == -1)
1161       return false;
1162     assert(DefMI->getOperand(DefIdx).isReg() &&
1163            DefMI->getOperand(DefIdx).getReg() == SrcReg);
1164
1165     // Now commute def instruction.
1166     MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1167     if (!CommutedMI)
1168       return false;
1169     SmallVector<unsigned, 1> Ops;
1170     Ops.push_back(NewDstIdx);
1171     MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1172     // Not needed since foldMemoryOperand returns new MI.
1173     MF.DeleteMachineInstr(CommutedMI);
1174     if (!FoldedMI)
1175       return false;
1176
1177     VRM.addSpillSlotUse(SS, FoldedMI);
1178     VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1179     // Insert new def MI and spill MI.
1180     const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
1181     TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1182     MII = prior(MII);
1183     MachineInstr *StoreMI = MII;
1184     VRM.addSpillSlotUse(SS, StoreMI);
1185     VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1186     MII = MBB.insert(MII, FoldedMI);  // Update MII to backtrack.
1187
1188     // Delete all 3 old instructions.
1189     InvalidateKills(*ReloadMI, RegKills, KillOps);
1190     VRM.RemoveMachineInstrFromMaps(ReloadMI);
1191     MBB.erase(ReloadMI);
1192     InvalidateKills(*DefMI, RegKills, KillOps);
1193     VRM.RemoveMachineInstrFromMaps(DefMI);
1194     MBB.erase(DefMI);
1195     InvalidateKills(MI, RegKills, KillOps);
1196     VRM.RemoveMachineInstrFromMaps(&MI);
1197     MBB.erase(&MI);
1198
1199     // If NewReg was previously holding value of some SS, it's now clobbered.
1200     // This has to be done now because it's a physical register. When this
1201     // instruction is re-visited, it's ignored.
1202     Spills.ClobberPhysReg(NewReg);
1203
1204     ++NumCommutes;
1205     return true;
1206   }
1207
1208   return false;
1209 }
1210
1211 /// findSuperReg - Find the SubReg's super-register of given register class
1212 /// where its SubIdx sub-register is SubReg.
1213 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
1214                              unsigned SubIdx, const TargetRegisterInfo *TRI) {
1215   for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
1216        I != E; ++I) {
1217     unsigned Reg = *I;
1218     if (TRI->getSubReg(Reg, SubIdx) == SubReg)
1219       return Reg;
1220   }
1221   return 0;
1222 }
1223
1224 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1225 /// the last store to the same slot is now dead. If so, remove the last store.
1226 void LocalSpiller::SpillRegToStackSlot(MachineBasicBlock &MBB,
1227                                   MachineBasicBlock::iterator &MII,
1228                                   int Idx, unsigned PhysReg, int StackSlot,
1229                                   const TargetRegisterClass *RC,
1230                                   bool isAvailable, MachineInstr *&LastStore,
1231                                   AvailableSpills &Spills,
1232                                   SmallSet<MachineInstr*, 4> &ReMatDefs,
1233                                   BitVector &RegKills,
1234                                   std::vector<MachineOperand*> &KillOps,
1235                                   VirtRegMap &VRM) {
1236   TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1237   MachineInstr *StoreMI = next(MII);
1238   VRM.addSpillSlotUse(StackSlot, StoreMI);
1239   DOUT << "Store:\t" << *StoreMI;
1240
1241   // If there is a dead store to this stack slot, nuke it now.
1242   if (LastStore) {
1243     DOUT << "Removed dead store:\t" << *LastStore;
1244     ++NumDSE;
1245     SmallVector<unsigned, 2> KillRegs;
1246     InvalidateKills(*LastStore, RegKills, KillOps, &KillRegs);
1247     MachineBasicBlock::iterator PrevMII = LastStore;
1248     bool CheckDef = PrevMII != MBB.begin();
1249     if (CheckDef)
1250       --PrevMII;
1251     VRM.RemoveMachineInstrFromMaps(LastStore);
1252     MBB.erase(LastStore);
1253     if (CheckDef) {
1254       // Look at defs of killed registers on the store. Mark the defs
1255       // as dead since the store has been deleted and they aren't
1256       // being reused.
1257       for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1258         bool HasOtherDef = false;
1259         if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1260           MachineInstr *DeadDef = PrevMII;
1261           if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1262             // FIXME: This assumes a remat def does not have side
1263             // effects.
1264             VRM.RemoveMachineInstrFromMaps(DeadDef);
1265             MBB.erase(DeadDef);
1266             ++NumDRM;
1267           }
1268         }
1269       }
1270     }
1271   }
1272
1273   LastStore = next(MII);
1274
1275   // If the stack slot value was previously available in some other
1276   // register, change it now.  Otherwise, make the register available,
1277   // in PhysReg.
1278   Spills.ModifyStackSlotOrReMat(StackSlot);
1279   Spills.ClobberPhysReg(PhysReg);
1280   Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1281   ++NumStores;
1282 }
1283
1284 /// TransferDeadness - A identity copy definition is dead and it's being
1285 /// removed. Find the last def or use and mark it as dead / kill.
1286 void LocalSpiller::TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1287                                     unsigned Reg, BitVector &RegKills,
1288                                     std::vector<MachineOperand*> &KillOps) {
1289   int LastUDDist = -1;
1290   MachineInstr *LastUDMI = NULL;
1291   for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1292          RE = RegInfo->reg_end(); RI != RE; ++RI) {
1293     MachineInstr *UDMI = &*RI;
1294     if (UDMI->getParent() != MBB)
1295       continue;
1296     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1297     if (DI == DistanceMap.end() || DI->second > CurDist)
1298       continue;
1299     if ((int)DI->second < LastUDDist)
1300       continue;
1301     LastUDDist = DI->second;
1302     LastUDMI = UDMI;
1303   }
1304
1305   if (LastUDMI) {
1306     const TargetInstrDesc &TID = LastUDMI->getDesc();
1307     MachineOperand *LastUD = NULL;
1308     for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1309       MachineOperand &MO = LastUDMI->getOperand(i);
1310       if (!MO.isReg() || MO.getReg() != Reg)
1311         continue;
1312       if (!LastUD || (LastUD->isUse() && MO.isDef()))
1313         LastUD = &MO;
1314       if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1)
1315         return;
1316     }
1317     if (LastUD->isDef())
1318       LastUD->setIsDead();
1319     else {
1320       LastUD->setIsKill();
1321       RegKills.set(Reg);
1322       KillOps[Reg] = LastUD;
1323     }
1324   }
1325 }
1326
1327 /// rewriteMBB - Keep track of which spills are available even after the
1328 /// register allocator is done with them.  If possible, avid reloading vregs.
1329 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1330                               AvailableSpills &Spills, BitVector &RegKills,
1331                               std::vector<MachineOperand*> &KillOps) {
1332   DOUT << "\n**** Local spiller rewriting MBB '"
1333        << MBB.getBasicBlock()->getName() << ":\n";
1334
1335   MachineFunction &MF = *MBB.getParent();
1336   
1337   // MaybeDeadStores - When we need to write a value back into a stack slot,
1338   // keep track of the inserted store.  If the stack slot value is never read
1339   // (because the value was used from some available register, for example), and
1340   // subsequently stored to, the original store is dead.  This map keeps track
1341   // of inserted stores that are not used.  If we see a subsequent store to the
1342   // same stack slot, the original store is deleted.
1343   std::vector<MachineInstr*> MaybeDeadStores;
1344   MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1345
1346   // ReMatDefs - These are rematerializable def MIs which are not deleted.
1347   SmallSet<MachineInstr*, 4> ReMatDefs;
1348
1349   // Clear kill info.
1350   RegKills.reset();
1351   KillOps.clear();
1352   KillOps.resize(TRI->getNumRegs(), NULL);
1353
1354   unsigned Dist = 0;
1355   DistanceMap.clear();
1356   for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1357        MII != E; ) {
1358     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
1359
1360     VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1361     bool Erased = false;
1362     bool BackTracked = false;
1363     if (PrepForUnfoldOpti(MBB, MII,
1364                           MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1365       NextMII = next(MII);
1366
1367     MachineInstr &MI = *MII;
1368     const TargetInstrDesc &TID = MI.getDesc();
1369
1370     if (VRM.hasEmergencySpills(&MI)) {
1371       // Spill physical register(s) in the rare case the allocator has run out
1372       // of registers to allocate.
1373       SmallSet<int, 4> UsedSS;
1374       std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1375       for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1376         unsigned PhysReg = EmSpills[i];
1377         const TargetRegisterClass *RC =
1378           TRI->getPhysicalRegisterRegClass(PhysReg);
1379         assert(RC && "Unable to determine register class!");
1380         int SS = VRM.getEmergencySpillSlot(RC);
1381         if (UsedSS.count(SS))
1382           assert(0 && "Need to spill more than one physical registers!");
1383         UsedSS.insert(SS);
1384         TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1385         MachineInstr *StoreMI = prior(MII);
1386         VRM.addSpillSlotUse(SS, StoreMI);
1387         TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1388         MachineInstr *LoadMI = next(MII);
1389         VRM.addSpillSlotUse(SS, LoadMI);
1390         ++NumPSpills;
1391       }
1392       NextMII = next(MII);
1393     }
1394
1395     // Insert restores here if asked to.
1396     if (VRM.isRestorePt(&MI)) {
1397       std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1398       for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1399         unsigned VirtReg = RestoreRegs[e-i-1];  // Reverse order.
1400         if (!VRM.getPreSplitReg(VirtReg))
1401           continue; // Split interval spilled again.
1402         unsigned Phys = VRM.getPhys(VirtReg);
1403         RegInfo->setPhysRegUsed(Phys);
1404
1405         // Check if the value being restored if available. If so, it must be
1406         // from a predecessor BB that fallthrough into this BB. We do not
1407         // expect:
1408         // BB1:
1409         // r1 = load fi#1
1410         // ...
1411         //    = r1<kill>
1412         // ... # r1 not clobbered
1413         // ...
1414         //    = load fi#1
1415         bool DoReMat = VRM.isReMaterialized(VirtReg);
1416         int SSorRMId = DoReMat
1417           ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1418         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1419         unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1420         if (InReg == Phys) {
1421           // If the value is already available in the expected register, save
1422           // a reload / remat.
1423           if (SSorRMId)
1424             DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1425           else
1426             DOUT << "Reusing SS#" << SSorRMId;
1427           DOUT << " from physreg "
1428                << TRI->getName(InReg) << " for vreg"
1429                << VirtReg <<" instead of reloading into physreg "
1430                << TRI->getName(Phys) << "\n";
1431           ++NumOmitted;
1432           continue;
1433         } else if (InReg && InReg != Phys) {
1434           if (SSorRMId)
1435             DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1436           else
1437             DOUT << "Reusing SS#" << SSorRMId;
1438           DOUT << " from physreg "
1439                << TRI->getName(InReg) << " for vreg"
1440                << VirtReg <<" by copying it into physreg "
1441                << TRI->getName(Phys) << "\n";
1442
1443           // If the reloaded / remat value is available in another register,
1444           // copy it to the desired register.
1445           TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1446
1447           // This invalidates Phys.
1448           Spills.ClobberPhysReg(Phys);
1449           // Remember it's available.
1450           Spills.addAvailable(SSorRMId, Phys);
1451
1452           // Mark is killed.
1453           MachineInstr *CopyMI = prior(MII);
1454           MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1455           KillOpnd->setIsKill();
1456           UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1457
1458           DOUT << '\t' << *CopyMI;
1459           ++NumCopified;
1460           continue;
1461         }
1462
1463         if (VRM.isReMaterialized(VirtReg)) {
1464           ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1465         } else {
1466           const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1467           TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1468           MachineInstr *LoadMI = prior(MII);
1469           VRM.addSpillSlotUse(SSorRMId, LoadMI);
1470           ++NumLoads;
1471         }
1472
1473         // This invalidates Phys.
1474         Spills.ClobberPhysReg(Phys);
1475         // Remember it's available.
1476         Spills.addAvailable(SSorRMId, Phys);
1477
1478         UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1479         DOUT << '\t' << *prior(MII);
1480       }
1481     }
1482
1483     // Insert spills here if asked to.
1484     if (VRM.isSpillPt(&MI)) {
1485       std::vector<std::pair<unsigned,bool> > &SpillRegs =
1486         VRM.getSpillPtSpills(&MI);
1487       for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1488         unsigned VirtReg = SpillRegs[i].first;
1489         bool isKill = SpillRegs[i].second;
1490         if (!VRM.getPreSplitReg(VirtReg))
1491           continue; // Split interval spilled again.
1492         const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1493         unsigned Phys = VRM.getPhys(VirtReg);
1494         int StackSlot = VRM.getStackSlot(VirtReg);
1495         TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1496         MachineInstr *StoreMI = next(MII);
1497         VRM.addSpillSlotUse(StackSlot, StoreMI);
1498         DOUT << "Store:\t" << *StoreMI;
1499         VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1500       }
1501       NextMII = next(MII);
1502     }
1503
1504     /// ReusedOperands - Keep track of operand reuse in case we need to undo
1505     /// reuse.
1506     ReuseInfo ReusedOperands(MI, TRI);
1507     SmallVector<unsigned, 4> VirtUseOps;
1508     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1509       MachineOperand &MO = MI.getOperand(i);
1510       if (!MO.isReg() || MO.getReg() == 0)
1511         continue;   // Ignore non-register operands.
1512       
1513       unsigned VirtReg = MO.getReg();
1514       if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1515         // Ignore physregs for spilling, but remember that it is used by this
1516         // function.
1517         RegInfo->setPhysRegUsed(VirtReg);
1518         continue;
1519       }
1520
1521       // We want to process implicit virtual register uses first.
1522       if (MO.isImplicit())
1523         // If the virtual register is implicitly defined, emit a implicit_def
1524         // before so scavenger knows it's "defined".
1525         VirtUseOps.insert(VirtUseOps.begin(), i);
1526       else
1527         VirtUseOps.push_back(i);
1528     }
1529
1530     // Process all of the spilled uses and all non spilled reg references.
1531     SmallVector<int, 2> PotentialDeadStoreSlots;
1532     for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1533       unsigned i = VirtUseOps[j];
1534       MachineOperand &MO = MI.getOperand(i);
1535       unsigned VirtReg = MO.getReg();
1536       assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1537              "Not a virtual register?");
1538
1539       unsigned SubIdx = MO.getSubReg();
1540       if (VRM.isAssignedReg(VirtReg)) {
1541         // This virtual register was assigned a physreg!
1542         unsigned Phys = VRM.getPhys(VirtReg);
1543         RegInfo->setPhysRegUsed(Phys);
1544         if (MO.isDef())
1545           ReusedOperands.markClobbered(Phys);
1546         unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1547         MI.getOperand(i).setReg(RReg);
1548         if (VRM.isImplicitlyDefined(VirtReg))
1549           BuildMI(MBB, &MI, MI.getDebugLoc(),
1550                   TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1551         continue;
1552       }
1553       
1554       // This virtual register is now known to be a spilled value.
1555       if (!MO.isUse())
1556         continue;  // Handle defs in the loop below (handle use&def here though)
1557
1558       bool DoReMat = VRM.isReMaterialized(VirtReg);
1559       int SSorRMId = DoReMat
1560         ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1561       int ReuseSlot = SSorRMId;
1562
1563       // Check to see if this stack slot is available.
1564       unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1565
1566       // If this is a sub-register use, make sure the reuse register is in the
1567       // right register class. For example, for x86 not all of the 32-bit
1568       // registers have accessible sub-registers.
1569       // Similarly so for EXTRACT_SUBREG. Consider this:
1570       // EDI = op
1571       // MOV32_mr fi#1, EDI
1572       // ...
1573       //       = EXTRACT_SUBREG fi#1
1574       // fi#1 is available in EDI, but it cannot be reused because it's not in
1575       // the right register file.
1576       if (PhysReg &&
1577           (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1578         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1579         if (!RC->contains(PhysReg))
1580           PhysReg = 0;
1581       }
1582
1583       if (PhysReg) {
1584         // This spilled operand might be part of a two-address operand.  If this
1585         // is the case, then changing it will necessarily require changing the 
1586         // def part of the instruction as well.  However, in some cases, we
1587         // aren't allowed to modify the reused register.  If none of these cases
1588         // apply, reuse it.
1589         bool CanReuse = true;
1590         int ti = TID.getOperandConstraint(i, TOI::TIED_TO);
1591         if (ti != -1 &&
1592             MI.getOperand(ti).isReg() &&
1593             MI.getOperand(ti).getReg() == VirtReg) {
1594           // Okay, we have a two address operand.  We can reuse this physreg as
1595           // long as we are allowed to clobber the value and there isn't an
1596           // earlier def that has already clobbered the physreg.
1597           CanReuse = Spills.canClobberPhysReg(ReuseSlot) &&
1598             !ReusedOperands.isClobbered(PhysReg);
1599         }
1600         
1601         if (CanReuse) {
1602           // If this stack slot value is already available, reuse it!
1603           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1604             DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1605           else
1606             DOUT << "Reusing SS#" << ReuseSlot;
1607           DOUT << " from physreg "
1608                << TRI->getName(PhysReg) << " for vreg"
1609                << VirtReg <<" instead of reloading into physreg "
1610                << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1611           unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1612           MI.getOperand(i).setReg(RReg);
1613
1614           // The only technical detail we have is that we don't know that
1615           // PhysReg won't be clobbered by a reloaded stack slot that occurs
1616           // later in the instruction.  In particular, consider 'op V1, V2'.
1617           // If V1 is available in physreg R0, we would choose to reuse it
1618           // here, instead of reloading it into the register the allocator
1619           // indicated (say R1).  However, V2 might have to be reloaded
1620           // later, and it might indicate that it needs to live in R0.  When
1621           // this occurs, we need to have information available that
1622           // indicates it is safe to use R1 for the reload instead of R0.
1623           //
1624           // To further complicate matters, we might conflict with an alias,
1625           // or R0 and R1 might not be compatible with each other.  In this
1626           // case, we actually insert a reload for V1 in R1, ensuring that
1627           // we can get at R0 or its alias.
1628           ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1629                                   VRM.getPhys(VirtReg), VirtReg);
1630           if (ti != -1)
1631             // Only mark it clobbered if this is a use&def operand.
1632             ReusedOperands.markClobbered(PhysReg);
1633           ++NumReused;
1634
1635           if (MI.getOperand(i).isKill() &&
1636               ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1637
1638             // The store of this spilled value is potentially dead, but we
1639             // won't know for certain until we've confirmed that the re-use
1640             // above is valid, which means waiting until the other operands
1641             // are processed. For now we just track the spill slot, we'll
1642             // remove it after the other operands are processed if valid.
1643
1644             PotentialDeadStoreSlots.push_back(ReuseSlot);
1645           }
1646
1647           continue;
1648         }  // CanReuse
1649         
1650         // Otherwise we have a situation where we have a two-address instruction
1651         // whose mod/ref operand needs to be reloaded.  This reload is already
1652         // available in some register "PhysReg", but if we used PhysReg as the
1653         // operand to our 2-addr instruction, the instruction would modify
1654         // PhysReg.  This isn't cool if something later uses PhysReg and expects
1655         // to get its initial value.
1656         //
1657         // To avoid this problem, and to avoid doing a load right after a store,
1658         // we emit a copy from PhysReg into the designated register for this
1659         // operand.
1660         unsigned DesignatedReg = VRM.getPhys(VirtReg);
1661         assert(DesignatedReg && "Must map virtreg to physreg!");
1662
1663         // Note that, if we reused a register for a previous operand, the
1664         // register we want to reload into might not actually be
1665         // available.  If this occurs, use the register indicated by the
1666         // reuser.
1667         if (ReusedOperands.hasReuses())
1668           DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI, 
1669                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1670         
1671         // If the mapped designated register is actually the physreg we have
1672         // incoming, we don't need to inserted a dead copy.
1673         if (DesignatedReg == PhysReg) {
1674           // If this stack slot value is already available, reuse it!
1675           if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1676             DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1677           else
1678             DOUT << "Reusing SS#" << ReuseSlot;
1679           DOUT << " from physreg " << TRI->getName(PhysReg)
1680                << " for vreg" << VirtReg
1681                << " instead of reloading into same physreg.\n";
1682           unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1683           MI.getOperand(i).setReg(RReg);
1684           ReusedOperands.markClobbered(RReg);
1685           ++NumReused;
1686           continue;
1687         }
1688         
1689         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1690         RegInfo->setPhysRegUsed(DesignatedReg);
1691         ReusedOperands.markClobbered(DesignatedReg);
1692         TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1693
1694         MachineInstr *CopyMI = prior(MII);
1695         UpdateKills(*CopyMI, RegKills, KillOps, TRI);
1696
1697         // This invalidates DesignatedReg.
1698         Spills.ClobberPhysReg(DesignatedReg);
1699         
1700         Spills.addAvailable(ReuseSlot, DesignatedReg);
1701         unsigned RReg =
1702           SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1703         MI.getOperand(i).setReg(RReg);
1704         DOUT << '\t' << *prior(MII);
1705         ++NumReused;
1706         continue;
1707       } // if (PhysReg)
1708       
1709       // Otherwise, reload it and remember that we have it.
1710       PhysReg = VRM.getPhys(VirtReg);
1711       assert(PhysReg && "Must map virtreg to physreg!");
1712
1713       // Note that, if we reused a register for a previous operand, the
1714       // register we want to reload into might not actually be
1715       // available.  If this occurs, use the register indicated by the
1716       // reuser.
1717       if (ReusedOperands.hasReuses())
1718         PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
1719                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1720       
1721       RegInfo->setPhysRegUsed(PhysReg);
1722       ReusedOperands.markClobbered(PhysReg);
1723       if (DoReMat) {
1724         ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1725       } else {
1726         const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1727         TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1728         MachineInstr *LoadMI = prior(MII);
1729         VRM.addSpillSlotUse(SSorRMId, LoadMI);
1730         ++NumLoads;
1731       }
1732       // This invalidates PhysReg.
1733       Spills.ClobberPhysReg(PhysReg);
1734
1735       // Any stores to this stack slot are not dead anymore.
1736       if (!DoReMat)
1737         MaybeDeadStores[SSorRMId] = NULL;
1738       Spills.addAvailable(SSorRMId, PhysReg);
1739       // Assumes this is the last use. IsKill will be unset if reg is reused
1740       // unless it's a two-address operand.
1741       if (TID.getOperandConstraint(i, TOI::TIED_TO) == -1)
1742         MI.getOperand(i).setIsKill();
1743       unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1744       MI.getOperand(i).setReg(RReg);
1745       UpdateKills(*prior(MII), RegKills, KillOps, TRI);
1746       DOUT << '\t' << *prior(MII);
1747     }
1748
1749     // Ok - now we can remove stores that have been confirmed dead.
1750     for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1751       // This was the last use and the spilled value is still available
1752       // for reuse. That means the spill was unnecessary!
1753       int PDSSlot = PotentialDeadStoreSlots[j];
1754       MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1755       if (DeadStore) {
1756         DOUT << "Removed dead store:\t" << *DeadStore;
1757         InvalidateKills(*DeadStore, RegKills, KillOps);
1758         VRM.RemoveMachineInstrFromMaps(DeadStore);
1759         MBB.erase(DeadStore);
1760         MaybeDeadStores[PDSSlot] = NULL;
1761         ++NumDSE;
1762       }
1763     }
1764
1765
1766     DOUT << '\t' << MI;
1767
1768
1769     // If we have folded references to memory operands, make sure we clear all
1770     // physical registers that may contain the value of the spilled virtual
1771     // register
1772     SmallSet<int, 2> FoldedSS;
1773     for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1774       unsigned VirtReg = I->second.first;
1775       VirtRegMap::ModRef MR = I->second.second;
1776       DOUT << "Folded vreg: " << VirtReg << "  MR: " << MR;
1777
1778       // MI2VirtMap be can updated which invalidate the iterator.
1779       // Increment the iterator first.
1780       ++I;
1781       int SS = VRM.getStackSlot(VirtReg);
1782       if (SS == VirtRegMap::NO_STACK_SLOT)
1783         continue;
1784       FoldedSS.insert(SS);
1785       DOUT << " - StackSlot: " << SS << "\n";
1786       
1787       // If this folded instruction is just a use, check to see if it's a
1788       // straight load from the virt reg slot.
1789       if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1790         int FrameIdx;
1791         unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1792         if (DestReg && FrameIdx == SS) {
1793           // If this spill slot is available, turn it into a copy (or nothing)
1794           // instead of leaving it as a load!
1795           if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1796             DOUT << "Promoted Load To Copy: " << MI;
1797             if (DestReg != InReg) {
1798               const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1799               TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1800               MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1801               unsigned SubIdx = DefMO->getSubReg();
1802               // Revisit the copy so we make sure to notice the effects of the
1803               // operation on the destreg (either needing to RA it if it's 
1804               // virtual or needing to clobber any values if it's physical).
1805               NextMII = &MI;
1806               --NextMII;  // backtrack to the copy.
1807               // Propagate the sub-register index over.
1808               if (SubIdx) {
1809                 DefMO = NextMII->findRegisterDefOperand(DestReg);
1810                 DefMO->setSubReg(SubIdx);
1811               }
1812
1813               // Mark is killed.
1814               MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1815               KillOpnd->setIsKill();
1816
1817               BackTracked = true;
1818             } else {
1819               DOUT << "Removing now-noop copy: " << MI;
1820               // Unset last kill since it's being reused.
1821               InvalidateKill(InReg, RegKills, KillOps);
1822             }
1823
1824             InvalidateKills(MI, RegKills, KillOps);
1825             VRM.RemoveMachineInstrFromMaps(&MI);
1826             MBB.erase(&MI);
1827             Erased = true;
1828             goto ProcessNextInst;
1829           }
1830         } else {
1831           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1832           SmallVector<MachineInstr*, 4> NewMIs;
1833           if (PhysReg &&
1834               TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1835             MBB.insert(MII, NewMIs[0]);
1836             InvalidateKills(MI, RegKills, KillOps);
1837             VRM.RemoveMachineInstrFromMaps(&MI);
1838             MBB.erase(&MI);
1839             Erased = true;
1840             --NextMII;  // backtrack to the unfolded instruction.
1841             BackTracked = true;
1842             goto ProcessNextInst;
1843           }
1844         }
1845       }
1846
1847       // If this reference is not a use, any previous store is now dead.
1848       // Otherwise, the store to this stack slot is not dead anymore.
1849       MachineInstr* DeadStore = MaybeDeadStores[SS];
1850       if (DeadStore) {
1851         bool isDead = !(MR & VirtRegMap::isRef);
1852         MachineInstr *NewStore = NULL;
1853         if (MR & VirtRegMap::isModRef) {
1854           unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1855           SmallVector<MachineInstr*, 4> NewMIs;
1856           // We can reuse this physreg as long as we are allowed to clobber
1857           // the value and there isn't an earlier def that has already clobbered
1858           // the physreg.
1859           if (PhysReg &&
1860               !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1861             MachineOperand *KillOpnd =
1862               DeadStore->findRegisterUseOperand(PhysReg, true);
1863             // Note, if the store is storing a sub-register, it's possible the
1864             // super-register is needed below.
1865             if (KillOpnd && !KillOpnd->getSubReg() &&
1866                 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1867              MBB.insert(MII, NewMIs[0]);
1868               NewStore = NewMIs[1];
1869               MBB.insert(MII, NewStore);
1870               VRM.addSpillSlotUse(SS, NewStore);
1871               InvalidateKills(MI, RegKills, KillOps);
1872               VRM.RemoveMachineInstrFromMaps(&MI);
1873               MBB.erase(&MI);
1874               Erased = true;
1875               --NextMII;
1876               --NextMII;  // backtrack to the unfolded instruction.
1877               BackTracked = true;
1878               isDead = true;
1879             }
1880           }
1881         }
1882
1883         if (isDead) {  // Previous store is dead.
1884           // If we get here, the store is dead, nuke it now.
1885           DOUT << "Removed dead store:\t" << *DeadStore;
1886           InvalidateKills(*DeadStore, RegKills, KillOps);
1887           VRM.RemoveMachineInstrFromMaps(DeadStore);
1888           MBB.erase(DeadStore);
1889           if (!NewStore)
1890             ++NumDSE;
1891         }
1892
1893         MaybeDeadStores[SS] = NULL;
1894         if (NewStore) {
1895           // Treat this store as a spill merged into a copy. That makes the
1896           // stack slot value available.
1897           VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1898           goto ProcessNextInst;
1899         }
1900       }
1901
1902       // If the spill slot value is available, and this is a new definition of
1903       // the value, the value is not available anymore.
1904       if (MR & VirtRegMap::isMod) {
1905         // Notice that the value in this stack slot has been modified.
1906         Spills.ModifyStackSlotOrReMat(SS);
1907         
1908         // If this is *just* a mod of the value, check to see if this is just a
1909         // store to the spill slot (i.e. the spill got merged into the copy). If
1910         // so, realize that the vreg is available now, and add the store to the
1911         // MaybeDeadStore info.
1912         int StackSlot;
1913         if (!(MR & VirtRegMap::isRef)) {
1914           if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1915             assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1916                    "Src hasn't been allocated yet?");
1917
1918             if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
1919                                     Spills, RegKills, KillOps, TRI, VRM)) {
1920               NextMII = next(MII);
1921               BackTracked = true;
1922               goto ProcessNextInst;
1923             }
1924
1925             // Okay, this is certainly a store of SrcReg to [StackSlot].  Mark
1926             // this as a potentially dead store in case there is a subsequent
1927             // store into the stack slot without a read from it.
1928             MaybeDeadStores[StackSlot] = &MI;
1929
1930             // If the stack slot value was previously available in some other
1931             // register, change it now.  Otherwise, make the register
1932             // available in PhysReg.
1933             Spills.addAvailable(StackSlot, SrcReg, false/*!clobber*/);
1934           }
1935         }
1936       }
1937     }
1938
1939     // Process all of the spilled defs.
1940     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1941       MachineOperand &MO = MI.getOperand(i);
1942       if (!(MO.isReg() && MO.getReg() && MO.isDef()))
1943         continue;
1944
1945       unsigned VirtReg = MO.getReg();
1946       if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
1947         // Check to see if this is a noop copy.  If so, eliminate the
1948         // instruction before considering the dest reg to be changed.
1949         unsigned Src, Dst, SrcSR, DstSR;
1950         if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
1951           ++NumDCE;
1952           DOUT << "Removing now-noop copy: " << MI;
1953           SmallVector<unsigned, 2> KillRegs;
1954           InvalidateKills(MI, RegKills, KillOps, &KillRegs);
1955           if (MO.isDead() && !KillRegs.empty()) {
1956             // Source register or an implicit super/sub-register use is killed.
1957             assert(KillRegs[0] == Dst ||
1958                    TRI->isSubRegister(KillRegs[0], Dst) ||
1959                    TRI->isSuperRegister(KillRegs[0], Dst));
1960             // Last def is now dead.
1961             TransferDeadness(&MBB, Dist, Src, RegKills, KillOps);
1962           }
1963           VRM.RemoveMachineInstrFromMaps(&MI);
1964           MBB.erase(&MI);
1965           Erased = true;
1966           Spills.disallowClobberPhysReg(VirtReg);
1967           goto ProcessNextInst;
1968         }
1969           
1970         // If it's not a no-op copy, it clobbers the value in the destreg.
1971         Spills.ClobberPhysReg(VirtReg);
1972         ReusedOperands.markClobbered(VirtReg);
1973  
1974         // Check to see if this instruction is a load from a stack slot into
1975         // a register.  If so, this provides the stack slot value in the reg.
1976         int FrameIdx;
1977         if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1978           assert(DestReg == VirtReg && "Unknown load situation!");
1979
1980           // If it is a folded reference, then it's not safe to clobber.
1981           bool Folded = FoldedSS.count(FrameIdx);
1982           // Otherwise, if it wasn't available, remember that it is now!
1983           Spills.addAvailable(FrameIdx, DestReg, !Folded);
1984           goto ProcessNextInst;
1985         }
1986             
1987         continue;
1988       }
1989
1990       unsigned SubIdx = MO.getSubReg();
1991       bool DoReMat = VRM.isReMaterialized(VirtReg);
1992       if (DoReMat)
1993         ReMatDefs.insert(&MI);
1994
1995       // The only vregs left are stack slot definitions.
1996       int StackSlot = VRM.getStackSlot(VirtReg);
1997       const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1998
1999       // If this def is part of a two-address operand, make sure to execute
2000       // the store from the correct physical register.
2001       unsigned PhysReg;
2002       int TiedOp = MI.getDesc().findTiedToSrcOperand(i);
2003       if (TiedOp != -1) {
2004         PhysReg = MI.getOperand(TiedOp).getReg();
2005         if (SubIdx) {
2006           unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2007           assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2008                  "Can't find corresponding super-register!");
2009           PhysReg = SuperReg;
2010         }
2011       } else {
2012         PhysReg = VRM.getPhys(VirtReg);
2013         if (ReusedOperands.isClobbered(PhysReg)) {
2014           // Another def has taken the assigned physreg. It must have been a
2015           // use&def which got it due to reuse. Undo the reuse!
2016           PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI, 
2017                                Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2018         }
2019       }
2020
2021       assert(PhysReg && "VR not assigned a physical register?");
2022       RegInfo->setPhysRegUsed(PhysReg);
2023       unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2024       ReusedOperands.markClobbered(RReg);
2025       MI.getOperand(i).setReg(RReg);
2026
2027       if (!MO.isDead()) {
2028         MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2029         SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2030                           LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2031         NextMII = next(MII);
2032
2033         // Check to see if this is a noop copy.  If so, eliminate the
2034         // instruction before considering the dest reg to be changed.
2035         {
2036           unsigned Src, Dst, SrcSR, DstSR;
2037           if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2038             ++NumDCE;
2039             DOUT << "Removing now-noop copy: " << MI;
2040             InvalidateKills(MI, RegKills, KillOps);
2041             VRM.RemoveMachineInstrFromMaps(&MI);
2042             MBB.erase(&MI);
2043             Erased = true;
2044             UpdateKills(*LastStore, RegKills, KillOps, TRI);
2045             goto ProcessNextInst;
2046           }
2047         }
2048       }    
2049     }
2050   ProcessNextInst:
2051     DistanceMap.insert(std::make_pair(&MI, Dist++));
2052     if (!Erased && !BackTracked) {
2053       for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2054         UpdateKills(*II, RegKills, KillOps, TRI);
2055     }
2056     MII = NextMII;
2057   }
2058
2059 }
2060
2061 llvm::Spiller* llvm::createSpiller() {
2062   switch (SpillerOpt) {
2063   default: assert(0 && "Unreachable!");
2064   case local:
2065     return new LocalSpiller();
2066   case simple:
2067     return new SimpleSpiller();
2068   }
2069 }