LLVM API Documentation

InlineSpiller.cpp
Go to the documentation of this file.
00001 //===-------- InlineSpiller.cpp - Insert spills and restores inline -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // The inline spiller modifies the machine function directly instead of
00011 // inserting spills and restores in VirtRegMap.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "regalloc"
00016 #include "Spiller.h"
00017 #include "llvm/ADT/Statistic.h"
00018 #include "llvm/ADT/TinyPtrVector.h"
00019 #include "llvm/Analysis/AliasAnalysis.h"
00020 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00021 #include "llvm/CodeGen/LiveRangeEdit.h"
00022 #include "llvm/CodeGen/LiveStackAnalysis.h"
00023 #include "llvm/CodeGen/MachineDominators.h"
00024 #include "llvm/CodeGen/MachineFrameInfo.h"
00025 #include "llvm/CodeGen/MachineFunction.h"
00026 #include "llvm/CodeGen/MachineInstrBundle.h"
00027 #include "llvm/CodeGen/MachineLoopInfo.h"
00028 #include "llvm/CodeGen/MachineRegisterInfo.h"
00029 #include "llvm/CodeGen/VirtRegMap.h"
00030 #include "llvm/Support/CommandLine.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 #include "llvm/Target/TargetInstrInfo.h"
00034 #include "llvm/Target/TargetMachine.h"
00035 
00036 using namespace llvm;
00037 
00038 STATISTIC(NumSpilledRanges,   "Number of spilled live ranges");
00039 STATISTIC(NumSnippets,        "Number of spilled snippets");
00040 STATISTIC(NumSpills,          "Number of spills inserted");
00041 STATISTIC(NumSpillsRemoved,   "Number of spills removed");
00042 STATISTIC(NumReloads,         "Number of reloads inserted");
00043 STATISTIC(NumReloadsRemoved,  "Number of reloads removed");
00044 STATISTIC(NumFolded,          "Number of folded stack accesses");
00045 STATISTIC(NumFoldedLoads,     "Number of folded loads");
00046 STATISTIC(NumRemats,          "Number of rematerialized defs for spilling");
00047 STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads");
00048 STATISTIC(NumHoists,          "Number of hoisted spills");
00049 
00050 static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
00051                                      cl::desc("Disable inline spill hoisting"));
00052 
00053 namespace {
00054 class InlineSpiller : public Spiller {
00055   MachineFunction &MF;
00056   LiveIntervals &LIS;
00057   LiveStacks &LSS;
00058   AliasAnalysis *AA;
00059   MachineDominatorTree &MDT;
00060   MachineLoopInfo &Loops;
00061   VirtRegMap &VRM;
00062   MachineFrameInfo &MFI;
00063   MachineRegisterInfo &MRI;
00064   const TargetInstrInfo &TII;
00065   const TargetRegisterInfo &TRI;
00066 
00067   // Variables that are valid during spill(), but used by multiple methods.
00068   LiveRangeEdit *Edit;
00069   LiveInterval *StackInt;
00070   int StackSlot;
00071   unsigned Original;
00072 
00073   // All registers to spill to StackSlot, including the main register.
00074   SmallVector<unsigned, 8> RegsToSpill;
00075 
00076   // All COPY instructions to/from snippets.
00077   // They are ignored since both operands refer to the same stack slot.
00078   SmallPtrSet<MachineInstr*, 8> SnippetCopies;
00079 
00080   // Values that failed to remat at some point.
00081   SmallPtrSet<VNInfo*, 8> UsedValues;
00082 
00083 public:
00084   // Information about a value that was defined by a copy from a sibling
00085   // register.
00086   struct SibValueInfo {
00087     // True when all reaching defs were reloads: No spill is necessary.
00088     bool AllDefsAreReloads;
00089 
00090     // True when value is defined by an original PHI not from splitting.
00091     bool DefByOrigPHI;
00092 
00093     // True when the COPY defining this value killed its source.
00094     bool KillsSource;
00095 
00096     // The preferred register to spill.
00097     unsigned SpillReg;
00098 
00099     // The value of SpillReg that should be spilled.
00100     VNInfo *SpillVNI;
00101 
00102     // The block where SpillVNI should be spilled. Currently, this must be the
00103     // block containing SpillVNI->def.
00104     MachineBasicBlock *SpillMBB;
00105 
00106     // A defining instruction that is not a sibling copy or a reload, or NULL.
00107     // This can be used as a template for rematerialization.
00108     MachineInstr *DefMI;
00109 
00110     // List of values that depend on this one.  These values are actually the
00111     // same, but live range splitting has placed them in different registers,
00112     // or SSA update needed to insert PHI-defs to preserve SSA form.  This is
00113     // copies of the current value and phi-kills.  Usually only phi-kills cause
00114     // more than one dependent value.
00115     TinyPtrVector<VNInfo*> Deps;
00116 
00117     SibValueInfo(unsigned Reg, VNInfo *VNI)
00118       : AllDefsAreReloads(true), DefByOrigPHI(false), KillsSource(false),
00119         SpillReg(Reg), SpillVNI(VNI), SpillMBB(0), DefMI(0) {}
00120 
00121     // Returns true when a def has been found.
00122     bool hasDef() const { return DefByOrigPHI || DefMI; }
00123   };
00124 
00125 private:
00126   // Values in RegsToSpill defined by sibling copies.
00127   typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
00128   SibValueMap SibValues;
00129 
00130   // Dead defs generated during spilling.
00131   SmallVector<MachineInstr*, 8> DeadDefs;
00132 
00133   ~InlineSpiller() {}
00134 
00135 public:
00136   InlineSpiller(MachineFunctionPass &pass,
00137                 MachineFunction &mf,
00138                 VirtRegMap &vrm)
00139     : MF(mf),
00140       LIS(pass.getAnalysis<LiveIntervals>()),
00141       LSS(pass.getAnalysis<LiveStacks>()),
00142       AA(&pass.getAnalysis<AliasAnalysis>()),
00143       MDT(pass.getAnalysis<MachineDominatorTree>()),
00144       Loops(pass.getAnalysis<MachineLoopInfo>()),
00145       VRM(vrm),
00146       MFI(*mf.getFrameInfo()),
00147       MRI(mf.getRegInfo()),
00148       TII(*mf.getTarget().getInstrInfo()),
00149       TRI(*mf.getTarget().getRegisterInfo()) {}
00150 
00151   void spill(LiveRangeEdit &);
00152 
00153 private:
00154   bool isSnippet(const LiveInterval &SnipLI);
00155   void collectRegsToSpill();
00156 
00157   bool isRegToSpill(unsigned Reg) {
00158     return std::find(RegsToSpill.begin(),
00159                      RegsToSpill.end(), Reg) != RegsToSpill.end();
00160   }
00161 
00162   bool isSibling(unsigned Reg);
00163   MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
00164   void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = 0);
00165   void analyzeSiblingValues();
00166 
00167   bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
00168   void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
00169 
00170   void markValueUsed(LiveInterval*, VNInfo*);
00171   bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
00172   void reMaterializeAll();
00173 
00174   bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
00175   bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> >,
00176                          MachineInstr *LoadMI = 0);
00177   void insertReload(LiveInterval &NewLI, SlotIndex,
00178                     MachineBasicBlock::iterator MI);
00179   void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
00180                    SlotIndex, MachineBasicBlock::iterator MI);
00181 
00182   void spillAroundUses(unsigned Reg);
00183   void spillAll();
00184 };
00185 }
00186 
00187 namespace llvm {
00188 Spiller *createInlineSpiller(MachineFunctionPass &pass,
00189                              MachineFunction &mf,
00190                              VirtRegMap &vrm) {
00191   return new InlineSpiller(pass, mf, vrm);
00192 }
00193 }
00194 
00195 //===----------------------------------------------------------------------===//
00196 //                                Snippets
00197 //===----------------------------------------------------------------------===//
00198 
00199 // When spilling a virtual register, we also spill any snippets it is connected
00200 // to. The snippets are small live ranges that only have a single real use,
00201 // leftovers from live range splitting. Spilling them enables memory operand
00202 // folding or tightens the live range around the single use.
00203 //
00204 // This minimizes register pressure and maximizes the store-to-load distance for
00205 // spill slots which can be important in tight loops.
00206 
00207 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
00208 /// otherwise return 0.
00209 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
00210   if (!MI->isFullCopy())
00211     return 0;
00212   if (MI->getOperand(0).getReg() == Reg)
00213       return MI->getOperand(1).getReg();
00214   if (MI->getOperand(1).getReg() == Reg)
00215       return MI->getOperand(0).getReg();
00216   return 0;
00217 }
00218 
00219 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
00220 /// It is assumed that SnipLI is a virtual register with the same original as
00221 /// Edit->getReg().
00222 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
00223   unsigned Reg = Edit->getReg();
00224 
00225   // A snippet is a tiny live range with only a single instruction using it
00226   // besides copies to/from Reg or spills/fills. We accept:
00227   //
00228   //   %snip = COPY %Reg / FILL fi#
00229   //   %snip = USE %snip
00230   //   %Reg = COPY %snip / SPILL %snip, fi#
00231   //
00232   if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
00233     return false;
00234 
00235   MachineInstr *UseMI = 0;
00236 
00237   // Check that all uses satisfy our criteria.
00238   for (MachineRegisterInfo::reg_nodbg_iterator
00239          RI = MRI.reg_nodbg_begin(SnipLI.reg);
00240        MachineInstr *MI = RI.skipInstruction();) {
00241 
00242     // Allow copies to/from Reg.
00243     if (isFullCopyOf(MI, Reg))
00244       continue;
00245 
00246     // Allow stack slot loads.
00247     int FI;
00248     if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
00249       continue;
00250 
00251     // Allow stack slot stores.
00252     if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
00253       continue;
00254 
00255     // Allow a single additional instruction.
00256     if (UseMI && MI != UseMI)
00257       return false;
00258     UseMI = MI;
00259   }
00260   return true;
00261 }
00262 
00263 /// collectRegsToSpill - Collect live range snippets that only have a single
00264 /// real use.
00265 void InlineSpiller::collectRegsToSpill() {
00266   unsigned Reg = Edit->getReg();
00267 
00268   // Main register always spills.
00269   RegsToSpill.assign(1, Reg);
00270   SnippetCopies.clear();
00271 
00272   // Snippets all have the same original, so there can't be any for an original
00273   // register.
00274   if (Original == Reg)
00275     return;
00276 
00277   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
00278        MachineInstr *MI = RI.skipInstruction();) {
00279     unsigned SnipReg = isFullCopyOf(MI, Reg);
00280     if (!isSibling(SnipReg))
00281       continue;
00282     LiveInterval &SnipLI = LIS.getInterval(SnipReg);
00283     if (!isSnippet(SnipLI))
00284       continue;
00285     SnippetCopies.insert(MI);
00286     if (isRegToSpill(SnipReg))
00287       continue;
00288     RegsToSpill.push_back(SnipReg);
00289     DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
00290     ++NumSnippets;
00291   }
00292 }
00293 
00294 
00295 //===----------------------------------------------------------------------===//
00296 //                            Sibling Values
00297 //===----------------------------------------------------------------------===//
00298 
00299 // After live range splitting, some values to be spilled may be defined by
00300 // copies from sibling registers. We trace the sibling copies back to the
00301 // original value if it still exists. We need it for rematerialization.
00302 //
00303 // Even when the value can't be rematerialized, we still want to determine if
00304 // the value has already been spilled, or we may want to hoist the spill from a
00305 // loop.
00306 
00307 bool InlineSpiller::isSibling(unsigned Reg) {
00308   return TargetRegisterInfo::isVirtualRegister(Reg) &&
00309            VRM.getOriginal(Reg) == Original;
00310 }
00311 
00312 #ifndef NDEBUG
00313 static raw_ostream &operator<<(raw_ostream &OS,
00314                                const InlineSpiller::SibValueInfo &SVI) {
00315   OS << "spill " << PrintReg(SVI.SpillReg) << ':'
00316      << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
00317   if (SVI.SpillMBB)
00318     OS << " in BB#" << SVI.SpillMBB->getNumber();
00319   if (SVI.AllDefsAreReloads)
00320     OS << " all-reloads";
00321   if (SVI.DefByOrigPHI)
00322     OS << " orig-phi";
00323   if (SVI.KillsSource)
00324     OS << " kill";
00325   OS << " deps[";
00326   for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i)
00327     OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def;
00328   OS << " ]";
00329   if (SVI.DefMI)
00330     OS << " def: " << *SVI.DefMI;
00331   else
00332     OS << '\n';
00333   return OS;
00334 }
00335 #endif
00336 
00337 /// propagateSiblingValue - Propagate the value in SVI to dependents if it is
00338 /// known.  Otherwise remember the dependency for later.
00339 ///
00340 /// @param SVI SibValues entry to propagate.
00341 /// @param VNI Dependent value, or NULL to propagate to all saved dependents.
00342 void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVI,
00343                                           VNInfo *VNI) {
00344   // When VNI is non-NULL, add it to SVI's deps, and only propagate to that.
00345   TinyPtrVector<VNInfo*> FirstDeps;
00346   if (VNI) {
00347     FirstDeps.push_back(VNI);
00348     SVI->second.Deps.push_back(VNI);
00349   }
00350 
00351   // Has the value been completely determined yet?  If not, defer propagation.
00352   if (!SVI->second.hasDef())
00353     return;
00354 
00355   // Work list of values to propagate.  It would be nice to use a SetVector
00356   // here, but then we would be forced to use a SmallSet.
00357   SmallVector<SibValueMap::iterator, 8> WorkList(1, SVI);
00358   SmallPtrSet<VNInfo*, 8> WorkSet;
00359 
00360   do {
00361     SVI = WorkList.pop_back_val();
00362     WorkSet.erase(SVI->first);
00363     TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps;
00364     VNI = 0;
00365 
00366     SibValueInfo &SV = SVI->second;
00367     if (!SV.SpillMBB)
00368       SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
00369 
00370     DEBUG(dbgs() << "  prop to " << Deps->size() << ": "
00371                  << SVI->first->id << '@' << SVI->first->def << ":\t" << SV);
00372 
00373     assert(SV.hasDef() && "Propagating undefined value");
00374 
00375     // Should this value be propagated as a preferred spill candidate?  We don't
00376     // propagate values of registers that are about to spill.
00377     bool PropSpill = !DisableHoisting && !isRegToSpill(SV.SpillReg);
00378     unsigned SpillDepth = ~0u;
00379 
00380     for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(),
00381          DepE = Deps->end(); DepI != DepE; ++DepI) {
00382       SibValueMap::iterator DepSVI = SibValues.find(*DepI);
00383       assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
00384       SibValueInfo &DepSV = DepSVI->second;
00385       if (!DepSV.SpillMBB)
00386         DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
00387 
00388       bool Changed = false;
00389 
00390       // Propagate defining instruction.
00391       if (!DepSV.hasDef()) {
00392         Changed = true;
00393         DepSV.DefMI = SV.DefMI;
00394         DepSV.DefByOrigPHI = SV.DefByOrigPHI;
00395       }
00396 
00397       // Propagate AllDefsAreReloads.  For PHI values, this computes an AND of
00398       // all predecessors.
00399       if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
00400         Changed = true;
00401         DepSV.AllDefsAreReloads = false;
00402       }
00403 
00404       // Propagate best spill value.
00405       if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
00406         if (SV.SpillMBB == DepSV.SpillMBB) {
00407           // DepSV is in the same block.  Hoist when dominated.
00408           if (DepSV.KillsSource && SV.SpillVNI->def < DepSV.SpillVNI->def) {
00409             // This is an alternative def earlier in the same MBB.
00410             // Hoist the spill as far as possible in SpillMBB. This can ease
00411             // register pressure:
00412             //
00413             //   x = def
00414             //   y = use x
00415             //   s = copy x
00416             //
00417             // Hoisting the spill of s to immediately after the def removes the
00418             // interference between x and y:
00419             //
00420             //   x = def
00421             //   spill x
00422             //   y = use x<kill>
00423             //
00424             // This hoist only helps when the DepSV copy kills its source.
00425             Changed = true;
00426             DepSV.SpillReg = SV.SpillReg;
00427             DepSV.SpillVNI = SV.SpillVNI;
00428             DepSV.SpillMBB = SV.SpillMBB;
00429           }
00430         } else {
00431           // DepSV is in a different block.
00432           if (SpillDepth == ~0u)
00433             SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
00434 
00435           // Also hoist spills to blocks with smaller loop depth, but make sure
00436           // that the new value dominates.  Non-phi dependents are always
00437           // dominated, phis need checking.
00438           if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
00439               (!DepSVI->first->isPHIDef() ||
00440                MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
00441             Changed = true;
00442             DepSV.SpillReg = SV.SpillReg;
00443             DepSV.SpillVNI = SV.SpillVNI;
00444             DepSV.SpillMBB = SV.SpillMBB;
00445           }
00446         }
00447       }
00448 
00449       if (!Changed)
00450         continue;
00451 
00452       // Something changed in DepSVI. Propagate to dependents.
00453       if (WorkSet.insert(DepSVI->first))
00454         WorkList.push_back(DepSVI);
00455 
00456       DEBUG(dbgs() << "  update " << DepSVI->first->id << '@'
00457             << DepSVI->first->def << " to:\t" << DepSV);
00458     }
00459   } while (!WorkList.empty());
00460 }
00461 
00462 /// traceSiblingValue - Trace a value that is about to be spilled back to the
00463 /// real defining instructions by looking through sibling copies. Always stay
00464 /// within the range of OrigVNI so the registers are known to carry the same
00465 /// value.
00466 ///
00467 /// Determine if the value is defined by all reloads, so spilling isn't
00468 /// necessary - the value is already in the stack slot.
00469 ///
00470 /// Return a defining instruction that may be a candidate for rematerialization.
00471 ///
00472 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
00473                                                VNInfo *OrigVNI) {
00474   // Check if a cached value already exists.
00475   SibValueMap::iterator SVI;
00476   bool Inserted;
00477   tie(SVI, Inserted) =
00478     SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
00479   if (!Inserted) {
00480     DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
00481                  << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
00482     return SVI->second.DefMI;
00483   }
00484 
00485   DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
00486                << UseVNI->id << '@' << UseVNI->def << '\n');
00487 
00488   // List of (Reg, VNI) that have been inserted into SibValues, but need to be
00489   // processed.
00490   SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
00491   WorkList.push_back(std::make_pair(UseReg, UseVNI));
00492 
00493   do {
00494     unsigned Reg;
00495     VNInfo *VNI;
00496     tie(Reg, VNI) = WorkList.pop_back_val();
00497     DEBUG(dbgs() << "  " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
00498                  << ":\t");
00499 
00500     // First check if this value has already been computed.
00501     SVI = SibValues.find(VNI);
00502     assert(SVI != SibValues.end() && "Missing SibValues entry");
00503 
00504     // Trace through PHI-defs created by live range splitting.
00505     if (VNI->isPHIDef()) {
00506       // Stop at original PHIs.  We don't know the value at the predecessors.
00507       if (VNI->def == OrigVNI->def) {
00508         DEBUG(dbgs() << "orig phi value\n");
00509         SVI->second.DefByOrigPHI = true;
00510         SVI->second.AllDefsAreReloads = false;
00511         propagateSiblingValue(SVI);
00512         continue;
00513       }
00514 
00515       // This is a PHI inserted by live range splitting.  We could trace the
00516       // live-out value from predecessor blocks, but that search can be very
00517       // expensive if there are many predecessors and many more PHIs as
00518       // generated by tail-dup when it sees an indirectbr.  Instead, look at
00519       // all the non-PHI defs that have the same value as OrigVNI.  They must
00520       // jointly dominate VNI->def.  This is not optimal since VNI may actually
00521       // be jointly dominated by a smaller subset of defs, so there is a change
00522       // we will miss a AllDefsAreReloads optimization.
00523 
00524       // Separate all values dominated by OrigVNI into PHIs and non-PHIs.
00525       SmallVector<VNInfo*, 8> PHIs, NonPHIs;
00526       LiveInterval &LI = LIS.getInterval(Reg);
00527       LiveInterval &OrigLI = LIS.getInterval(Original);
00528 
00529       for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end();
00530            VI != VE; ++VI) {
00531         VNInfo *VNI2 = *VI;
00532         if (VNI2->isUnused())
00533           continue;
00534         if (!OrigLI.containsOneValue() &&
00535             OrigLI.getVNInfoAt(VNI2->def) != OrigVNI)
00536           continue;
00537         if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def)
00538           PHIs.push_back(VNI2);
00539         else
00540           NonPHIs.push_back(VNI2);
00541       }
00542       DEBUG(dbgs() << "split phi value, checking " << PHIs.size()
00543                    << " phi-defs, and " << NonPHIs.size()
00544                    << " non-phi/orig defs\n");
00545 
00546       // Create entries for all the PHIs.  Don't add them to the worklist, we
00547       // are processing all of them in one go here.
00548       for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
00549         SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i])));
00550 
00551       // Add every PHI as a dependent of all the non-PHIs.
00552       for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) {
00553         VNInfo *NonPHI = NonPHIs[i];
00554         // Known value? Try an insertion.
00555         tie(SVI, Inserted) =
00556           SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI)));
00557         // Add all the PHIs as dependents of NonPHI.
00558         for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi)
00559           SVI->second.Deps.push_back(PHIs[pi]);
00560         // This is the first time we see NonPHI, add it to the worklist.
00561         if (Inserted)
00562           WorkList.push_back(std::make_pair(Reg, NonPHI));
00563         else
00564           // Propagate to all inserted PHIs, not just VNI.
00565           propagateSiblingValue(SVI);
00566       }
00567 
00568       // Next work list item.
00569       continue;
00570     }
00571 
00572     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
00573     assert(MI && "Missing def");
00574 
00575     // Trace through sibling copies.
00576     if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
00577       if (isSibling(SrcReg)) {
00578         LiveInterval &SrcLI = LIS.getInterval(SrcReg);
00579         LiveRangeQuery SrcQ(SrcLI, VNI->def);
00580         assert(SrcQ.valueIn() && "Copy from non-existing value");
00581         // Check if this COPY kills its source.
00582         SVI->second.KillsSource = SrcQ.isKill();
00583         VNInfo *SrcVNI = SrcQ.valueIn();
00584         DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
00585                      << SrcVNI->id << '@' << SrcVNI->def
00586                      << " kill=" << unsigned(SVI->second.KillsSource) << '\n');
00587         // Known sibling source value? Try an insertion.
00588         tie(SVI, Inserted) = SibValues.insert(std::make_pair(SrcVNI,
00589                                                  SibValueInfo(SrcReg, SrcVNI)));
00590         // This is the first time we see Src, add it to the worklist.
00591         if (Inserted)
00592           WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
00593         propagateSiblingValue(SVI, VNI);
00594         // Next work list item.
00595         continue;
00596       }
00597     }
00598 
00599     // Track reachable reloads.
00600     SVI->second.DefMI = MI;
00601     SVI->second.SpillMBB = MI->getParent();
00602     int FI;
00603     if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
00604       DEBUG(dbgs() << "reload\n");
00605       propagateSiblingValue(SVI);
00606       // Next work list item.
00607       continue;
00608     }
00609 
00610     // Potential remat candidate.
00611     DEBUG(dbgs() << "def " << *MI);
00612     SVI->second.AllDefsAreReloads = false;
00613     propagateSiblingValue(SVI);
00614   } while (!WorkList.empty());
00615 
00616   // Look up the value we were looking for.  We already did this lookup at the
00617   // top of the function, but SibValues may have been invalidated.
00618   SVI = SibValues.find(UseVNI);
00619   assert(SVI != SibValues.end() && "Didn't compute requested info");
00620   DEBUG(dbgs() << "  traced to:\t" << SVI->second);
00621   return SVI->second.DefMI;
00622 }
00623 
00624 /// analyzeSiblingValues - Trace values defined by sibling copies back to
00625 /// something that isn't a sibling copy.
00626 ///
00627 /// Keep track of values that may be rematerializable.
00628 void InlineSpiller::analyzeSiblingValues() {
00629   SibValues.clear();
00630 
00631   // No siblings at all?
00632   if (Edit->getReg() == Original)
00633     return;
00634 
00635   LiveInterval &OrigLI = LIS.getInterval(Original);
00636   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
00637     unsigned Reg = RegsToSpill[i];
00638     LiveInterval &LI = LIS.getInterval(Reg);
00639     for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
00640          VE = LI.vni_end(); VI != VE; ++VI) {
00641       VNInfo *VNI = *VI;
00642       if (VNI->isUnused())
00643         continue;
00644       MachineInstr *DefMI = 0;
00645       if (!VNI->isPHIDef()) {
00646        DefMI = LIS.getInstructionFromIndex(VNI->def);
00647        assert(DefMI && "No defining instruction");
00648       }
00649       // Check possible sibling copies.
00650       if (VNI->isPHIDef() || DefMI->isCopy()) {
00651         VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
00652         assert(OrigVNI && "Def outside original live range");
00653         if (OrigVNI->def != VNI->def)
00654           DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
00655       }
00656       if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) {
00657         DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
00658                      << VNI->def << " may remat from " << *DefMI);
00659       }
00660     }
00661   }
00662 }
00663 
00664 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
00665 /// a spill at a better location.
00666 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
00667   SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
00668   VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
00669   assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
00670   SibValueMap::iterator I = SibValues.find(VNI);
00671   if (I == SibValues.end())
00672     return false;
00673 
00674   const SibValueInfo &SVI = I->second;
00675 
00676   // Let the normal folding code deal with the boring case.
00677   if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
00678     return false;
00679 
00680   // SpillReg may have been deleted by remat and DCE.
00681   if (!LIS.hasInterval(SVI.SpillReg)) {
00682     DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
00683     SibValues.erase(I);
00684     return false;
00685   }
00686 
00687   LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
00688   if (!SibLI.containsValue(SVI.SpillVNI)) {
00689     DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
00690     SibValues.erase(I);
00691     return false;
00692   }
00693 
00694   // Conservatively extend the stack slot range to the range of the original
00695   // value. We may be able to do better with stack slot coloring by being more
00696   // careful here.
00697   assert(StackInt && "No stack slot assigned yet.");
00698   LiveInterval &OrigLI = LIS.getInterval(Original);
00699   VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
00700   StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
00701   DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
00702                << *StackInt << '\n');
00703 
00704   // Already spilled everywhere.
00705   if (SVI.AllDefsAreReloads) {
00706     DEBUG(dbgs() << "\tno spill needed: " << SVI);
00707     ++NumOmitReloadSpill;
00708     return true;
00709   }
00710   // We are going to spill SVI.SpillVNI immediately after its def, so clear out
00711   // any later spills of the same value.
00712   eliminateRedundantSpills(SibLI, SVI.SpillVNI);
00713 
00714   MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
00715   MachineBasicBlock::iterator MII;
00716   if (SVI.SpillVNI->isPHIDef())
00717     MII = MBB->SkipPHIsAndLabels(MBB->begin());
00718   else {
00719     MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
00720     assert(DefMI && "Defining instruction disappeared");
00721     MII = DefMI;
00722     ++MII;
00723   }
00724   // Insert spill without kill flag immediately after def.
00725   TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
00726                           MRI.getRegClass(SVI.SpillReg), &TRI);
00727   --MII; // Point to store instruction.
00728   LIS.InsertMachineInstrInMaps(MII);
00729   DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
00730 
00731   ++NumSpills;
00732   ++NumHoists;
00733   return true;
00734 }
00735 
00736 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
00737 /// redundant spills of this value in SLI.reg and sibling copies.
00738 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
00739   assert(VNI && "Missing value");
00740   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
00741   WorkList.push_back(std::make_pair(&SLI, VNI));
00742   assert(StackInt && "No stack slot assigned yet.");
00743 
00744   do {
00745     LiveInterval *LI;
00746     tie(LI, VNI) = WorkList.pop_back_val();
00747     unsigned Reg = LI->reg;
00748     DEBUG(dbgs() << "Checking redundant spills for "
00749                  << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
00750 
00751     // Regs to spill are taken care of.
00752     if (isRegToSpill(Reg))
00753       continue;
00754 
00755     // Add all of VNI's live range to StackInt.
00756     StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
00757     DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
00758 
00759     // Find all spills and copies of VNI.
00760     for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
00761          MachineInstr *MI = UI.skipInstruction();) {
00762       if (!MI->isCopy() && !MI->mayStore())
00763         continue;
00764       SlotIndex Idx = LIS.getInstructionIndex(MI);
00765       if (LI->getVNInfoAt(Idx) != VNI)
00766         continue;
00767 
00768       // Follow sibling copies down the dominator tree.
00769       if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
00770         if (isSibling(DstReg)) {
00771            LiveInterval &DstLI = LIS.getInterval(DstReg);
00772            VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
00773            assert(DstVNI && "Missing defined value");
00774            assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
00775            WorkList.push_back(std::make_pair(&DstLI, DstVNI));
00776         }
00777         continue;
00778       }
00779 
00780       // Erase spills.
00781       int FI;
00782       if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
00783         DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
00784         // eliminateDeadDefs won't normally remove stores, so switch opcode.
00785         MI->setDesc(TII.get(TargetOpcode::KILL));
00786         DeadDefs.push_back(MI);
00787         ++NumSpillsRemoved;
00788         --NumSpills;
00789       }
00790     }
00791   } while (!WorkList.empty());
00792 }
00793 
00794 
00795 //===----------------------------------------------------------------------===//
00796 //                            Rematerialization
00797 //===----------------------------------------------------------------------===//
00798 
00799 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
00800 /// instruction cannot be eliminated. See through snippet copies
00801 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
00802   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
00803   WorkList.push_back(std::make_pair(LI, VNI));
00804   do {
00805     tie(LI, VNI) = WorkList.pop_back_val();
00806     if (!UsedValues.insert(VNI))
00807       continue;
00808 
00809     if (VNI->isPHIDef()) {
00810       MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
00811       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00812              PE = MBB->pred_end(); PI != PE; ++PI) {
00813         VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI));
00814         if (PVNI)
00815           WorkList.push_back(std::make_pair(LI, PVNI));
00816       }
00817       continue;
00818     }
00819 
00820     // Follow snippet copies.
00821     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
00822     if (!SnippetCopies.count(MI))
00823       continue;
00824     LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
00825     assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
00826     VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
00827     assert(SnipVNI && "Snippet undefined before copy");
00828     WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
00829   } while (!WorkList.empty());
00830 }
00831 
00832 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
00833 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
00834                                      MachineBasicBlock::iterator MI) {
00835   SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
00836   VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
00837 
00838   if (!ParentVNI) {
00839     DEBUG(dbgs() << "\tadding <undef> flags: ");
00840     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00841       MachineOperand &MO = MI->getOperand(i);
00842       if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
00843         MO.setIsUndef();
00844     }
00845     DEBUG(dbgs() << UseIdx << '\t' << *MI);
00846     return true;
00847   }
00848 
00849   if (SnippetCopies.count(MI))
00850     return false;
00851 
00852   // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
00853   LiveRangeEdit::Remat RM(ParentVNI);
00854   SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
00855   if (SibI != SibValues.end())
00856     RM.OrigMI = SibI->second.DefMI;
00857   if (!Edit->canRematerializeAt(RM, UseIdx, false)) {
00858     markValueUsed(&VirtReg, ParentVNI);
00859     DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
00860     return false;
00861   }
00862 
00863   // If the instruction also writes VirtReg.reg, it had better not require the
00864   // same register for uses and defs.
00865   SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
00866   MIBundleOperands::VirtRegInfo RI =
00867     MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
00868   if (RI.Tied) {
00869     markValueUsed(&VirtReg, ParentVNI);
00870     DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
00871     return false;
00872   }
00873 
00874   // Before rematerializing into a register for a single instruction, try to
00875   // fold a load into the instruction. That avoids allocating a new register.
00876   if (RM.OrigMI->canFoldAsLoad() &&
00877       foldMemoryOperand(Ops, RM.OrigMI)) {
00878     Edit->markRematerialized(RM.ParentVNI);
00879     ++NumFoldedLoads;
00880     return true;
00881   }
00882 
00883   // Alocate a new register for the remat.
00884   LiveInterval &NewLI = Edit->createFrom(Original);
00885   NewLI.markNotSpillable();
00886 
00887   // Finally we can rematerialize OrigMI before MI.
00888   SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
00889                                            TRI);
00890   DEBUG(dbgs() << "\tremat:  " << DefIdx << '\t'
00891                << *LIS.getInstructionFromIndex(DefIdx));
00892 
00893   // Replace operands
00894   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00895     MachineOperand &MO = MI->getOperand(Ops[i].second);
00896     if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
00897       MO.setReg(NewLI.reg);
00898       MO.setIsKill();
00899     }
00900   }
00901   DEBUG(dbgs() << "\t        " << UseIdx << '\t' << *MI);
00902 
00903   VNInfo *DefVNI = NewLI.getNextValue(DefIdx, LIS.getVNInfoAllocator());
00904   NewLI.addRange(LiveRange(DefIdx, UseIdx.getRegSlot(), DefVNI));
00905   DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
00906   ++NumRemats;
00907   return true;
00908 }
00909 
00910 /// reMaterializeAll - Try to rematerialize as many uses as possible,
00911 /// and trim the live ranges after.
00912 void InlineSpiller::reMaterializeAll() {
00913   // analyzeSiblingValues has already tested all relevant defining instructions.
00914   if (!Edit->anyRematerializable(AA))
00915     return;
00916 
00917   UsedValues.clear();
00918 
00919   // Try to remat before all uses of snippets.
00920   bool anyRemat = false;
00921   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
00922     unsigned Reg = RegsToSpill[i];
00923     LiveInterval &LI = LIS.getInterval(Reg);
00924     for (MachineRegisterInfo::use_nodbg_iterator
00925          RI = MRI.use_nodbg_begin(Reg);
00926          MachineInstr *MI = RI.skipBundle();)
00927       anyRemat |= reMaterializeFor(LI, MI);
00928   }
00929   if (!anyRemat)
00930     return;
00931 
00932   // Remove any values that were completely rematted.
00933   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
00934     unsigned Reg = RegsToSpill[i];
00935     LiveInterval &LI = LIS.getInterval(Reg);
00936     for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
00937          I != E; ++I) {
00938       VNInfo *VNI = *I;
00939       if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
00940         continue;
00941       MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
00942       MI->addRegisterDead(Reg, &TRI);
00943       if (!MI->allDefsAreDead())
00944         continue;
00945       DEBUG(dbgs() << "All defs dead: " << *MI);
00946       DeadDefs.push_back(MI);
00947     }
00948   }
00949 
00950   // Eliminate dead code after remat. Note that some snippet copies may be
00951   // deleted here.
00952   if (DeadDefs.empty())
00953     return;
00954   DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
00955   Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
00956 
00957   // Get rid of deleted and empty intervals.
00958   unsigned ResultPos = 0;
00959   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
00960     unsigned Reg = RegsToSpill[i];
00961     if (!LIS.hasInterval(Reg))
00962       continue;
00963 
00964     LiveInterval &LI = LIS.getInterval(Reg);
00965     if (LI.empty()) {
00966       Edit->eraseVirtReg(Reg);
00967       continue;
00968     }
00969 
00970     RegsToSpill[ResultPos++] = Reg;
00971   }
00972   RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
00973   DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
00974 }
00975 
00976 
00977 //===----------------------------------------------------------------------===//
00978 //                                 Spilling
00979 //===----------------------------------------------------------------------===//
00980 
00981 /// If MI is a load or store of StackSlot, it can be removed.
00982 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
00983   int FI = 0;
00984   unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI);
00985   bool IsLoad = InstrReg;
00986   if (!IsLoad)
00987     InstrReg = TII.isStoreToStackSlot(MI, FI);
00988 
00989   // We have a stack access. Is it the right register and slot?
00990   if (InstrReg != Reg || FI != StackSlot)
00991     return false;
00992 
00993   DEBUG(dbgs() << "Coalescing stack access: " << *MI);
00994   LIS.RemoveMachineInstrFromMaps(MI);
00995   MI->eraseFromParent();
00996 
00997   if (IsLoad) {
00998     ++NumReloadsRemoved;
00999     --NumReloads;
01000   } else {
01001     ++NumSpillsRemoved;
01002     --NumSpills;
01003   }
01004 
01005   return true;
01006 }
01007 
01008 /// foldMemoryOperand - Try folding stack slot references in Ops into their
01009 /// instructions.
01010 ///
01011 /// @param Ops    Operand indices from analyzeVirtReg().
01012 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
01013 /// @return       True on success.
01014 bool InlineSpiller::
01015 foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops,
01016                   MachineInstr *LoadMI) {
01017   if (Ops.empty())
01018     return false;
01019   // Don't attempt folding in bundles.
01020   MachineInstr *MI = Ops.front().first;
01021   if (Ops.back().first != MI || MI->isBundled())
01022     return false;
01023 
01024   bool WasCopy = MI->isCopy();
01025   unsigned ImpReg = 0;
01026 
01027   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
01028   // operands.
01029   SmallVector<unsigned, 8> FoldOps;
01030   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01031     unsigned Idx = Ops[i].second;
01032     MachineOperand &MO = MI->getOperand(Idx);
01033     if (MO.isImplicit()) {
01034       ImpReg = MO.getReg();
01035       continue;
01036     }
01037     // FIXME: Teach targets to deal with subregs.
01038     if (MO.getSubReg())
01039       return false;
01040     // We cannot fold a load instruction into a def.
01041     if (LoadMI && MO.isDef())
01042       return false;
01043     // Tied use operands should not be passed to foldMemoryOperand.
01044     if (!MI->isRegTiedToDefOperand(Idx))
01045       FoldOps.push_back(Idx);
01046   }
01047 
01048   MachineInstr *FoldMI =
01049                 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
01050                        : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
01051   if (!FoldMI)
01052     return false;
01053   LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
01054   MI->eraseFromParent();
01055 
01056   // TII.foldMemoryOperand may have left some implicit operands on the
01057   // instruction.  Strip them.
01058   if (ImpReg)
01059     for (unsigned i = FoldMI->getNumOperands(); i; --i) {
01060       MachineOperand &MO = FoldMI->getOperand(i - 1);
01061       if (!MO.isReg() || !MO.isImplicit())
01062         break;
01063       if (MO.getReg() == ImpReg)
01064         FoldMI->RemoveOperand(i - 1);
01065     }
01066 
01067   DEBUG(dbgs() << "\tfolded:  " << LIS.getInstructionIndex(FoldMI) << '\t'
01068                << *FoldMI);
01069   if (!WasCopy)
01070     ++NumFolded;
01071   else if (Ops.front().second == 0)
01072     ++NumSpills;
01073   else
01074     ++NumReloads;
01075   return true;
01076 }
01077 
01078 /// insertReload - Insert a reload of NewLI.reg before MI.
01079 void InlineSpiller::insertReload(LiveInterval &NewLI,
01080                                  SlotIndex Idx,
01081                                  MachineBasicBlock::iterator MI) {
01082   MachineBasicBlock &MBB = *MI->getParent();
01083   TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
01084                            MRI.getRegClass(NewLI.reg), &TRI);
01085   --MI; // Point to load instruction.
01086   SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getRegSlot();
01087   // Some (out-of-tree) targets have EC reload instructions.
01088   if (MachineOperand *MO = MI->findRegisterDefOperand(NewLI.reg))
01089     if (MO->isEarlyClobber())
01090       LoadIdx = LoadIdx.getRegSlot(true);
01091   DEBUG(dbgs() << "\treload:  " << LoadIdx << '\t' << *MI);
01092   VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, LIS.getVNInfoAllocator());
01093   NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
01094   ++NumReloads;
01095 }
01096 
01097 /// insertSpill - Insert a spill of NewLI.reg after MI.
01098 void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
01099                                 SlotIndex Idx, MachineBasicBlock::iterator MI) {
01100   MachineBasicBlock &MBB = *MI->getParent();
01101   TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
01102                           MRI.getRegClass(NewLI.reg), &TRI);
01103   --MI; // Point to store instruction.
01104   SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getRegSlot();
01105   DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
01106   VNInfo *StoreVNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
01107   NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
01108   ++NumSpills;
01109 }
01110 
01111 /// spillAroundUses - insert spill code around each use of Reg.
01112 void InlineSpiller::spillAroundUses(unsigned Reg) {
01113   DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
01114   LiveInterval &OldLI = LIS.getInterval(Reg);
01115 
01116   // Iterate over instructions using Reg.
01117   for (MachineRegisterInfo::reg_iterator RegI = MRI.reg_begin(Reg);
01118        MachineInstr *MI = RegI.skipBundle();) {
01119 
01120     // Debug values are not allowed to affect codegen.
01121     if (MI->isDebugValue()) {
01122       // Modify DBG_VALUE now that the value is in a spill slot.
01123       uint64_t Offset = MI->getOperand(1).getImm();
01124       const MDNode *MDPtr = MI->getOperand(2).getMetadata();
01125       DebugLoc DL = MI->getDebugLoc();
01126       if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
01127                                                            Offset, MDPtr, DL)) {
01128         DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
01129         MachineBasicBlock *MBB = MI->getParent();
01130         MBB->insert(MBB->erase(MI), NewDV);
01131       } else {
01132         DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
01133         MI->eraseFromParent();
01134       }
01135       continue;
01136     }
01137 
01138     // Ignore copies to/from snippets. We'll delete them.
01139     if (SnippetCopies.count(MI))
01140       continue;
01141 
01142     // Stack slot accesses may coalesce away.
01143     if (coalesceStackAccess(MI, Reg))
01144       continue;
01145 
01146     // Analyze instruction.
01147     SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
01148     MIBundleOperands::VirtRegInfo RI =
01149       MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops);
01150 
01151     // Find the slot index where this instruction reads and writes OldLI.
01152     // This is usually the def slot, except for tied early clobbers.
01153     SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
01154     if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
01155       if (SlotIndex::isSameInstr(Idx, VNI->def))
01156         Idx = VNI->def;
01157 
01158     // Check for a sibling copy.
01159     unsigned SibReg = isFullCopyOf(MI, Reg);
01160     if (SibReg && isSibling(SibReg)) {
01161       // This may actually be a copy between snippets.
01162       if (isRegToSpill(SibReg)) {
01163         DEBUG(dbgs() << "Found new snippet copy: " << *MI);
01164         SnippetCopies.insert(MI);
01165         continue;
01166       }
01167       if (RI.Writes) {
01168         // Hoist the spill of a sib-reg copy.
01169         if (hoistSpill(OldLI, MI)) {
01170           // This COPY is now dead, the value is already in the stack slot.
01171           MI->getOperand(0).setIsDead();
01172           DeadDefs.push_back(MI);
01173           continue;
01174         }
01175       } else {
01176         // This is a reload for a sib-reg copy. Drop spills downstream.
01177         LiveInterval &SibLI = LIS.getInterval(SibReg);
01178         eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
01179         // The COPY will fold to a reload below.
01180       }
01181     }
01182 
01183     // Attempt to fold memory ops.
01184     if (foldMemoryOperand(Ops))
01185       continue;
01186 
01187     // Allocate interval around instruction.
01188     // FIXME: Infer regclass from instruction alone.
01189     LiveInterval &NewLI = Edit->createFrom(Reg);
01190     NewLI.markNotSpillable();
01191 
01192     if (RI.Reads)
01193       insertReload(NewLI, Idx, MI);
01194 
01195     // Rewrite instruction operands.
01196     bool hasLiveDef = false;
01197     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01198       MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second);
01199       MO.setReg(NewLI.reg);
01200       if (MO.isUse()) {
01201         if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second))
01202           MO.setIsKill();
01203       } else {
01204         if (!MO.isDead())
01205           hasLiveDef = true;
01206       }
01207     }
01208     DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
01209 
01210     // FIXME: Use a second vreg if instruction has no tied ops.
01211     if (RI.Writes) {
01212       if (hasLiveDef)
01213         insertSpill(NewLI, OldLI, Idx, MI);
01214       else {
01215         // This instruction defines a dead value.  We don't need to spill it,
01216         // but do create a live range for the dead value.
01217         VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
01218         NewLI.addRange(LiveRange(Idx, Idx.getDeadSlot(), VNI));
01219       }
01220     }
01221 
01222     DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
01223   }
01224 }
01225 
01226 /// spillAll - Spill all registers remaining after rematerialization.
01227 void InlineSpiller::spillAll() {
01228   // Update LiveStacks now that we are committed to spilling.
01229   if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
01230     StackSlot = VRM.assignVirt2StackSlot(Original);
01231     StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
01232     StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
01233   } else
01234     StackInt = &LSS.getInterval(StackSlot);
01235 
01236   if (Original != Edit->getReg())
01237     VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
01238 
01239   assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
01240   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
01241     StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
01242                                    StackInt->getValNumInfo(0));
01243   DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
01244 
01245   // Spill around uses of all RegsToSpill.
01246   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
01247     spillAroundUses(RegsToSpill[i]);
01248 
01249   // Hoisted spills may cause dead code.
01250   if (!DeadDefs.empty()) {
01251     DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
01252     Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
01253   }
01254 
01255   // Finally delete the SnippetCopies.
01256   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
01257     for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(RegsToSpill[i]);
01258          MachineInstr *MI = RI.skipInstruction();) {
01259       assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
01260       // FIXME: Do this with a LiveRangeEdit callback.
01261       LIS.RemoveMachineInstrFromMaps(MI);
01262       MI->eraseFromParent();
01263     }
01264   }
01265 
01266   // Delete all spilled registers.
01267   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
01268     Edit->eraseVirtReg(RegsToSpill[i]);
01269 }
01270 
01271 void InlineSpiller::spill(LiveRangeEdit &edit) {
01272   ++NumSpilledRanges;
01273   Edit = &edit;
01274   assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
01275          && "Trying to spill a stack slot.");
01276   // Share a stack slot among all descendants of Original.
01277   Original = VRM.getOriginal(edit.getReg());
01278   StackSlot = VRM.getStackSlot(Original);
01279   StackInt = 0;
01280 
01281   DEBUG(dbgs() << "Inline spilling "
01282                << MRI.getRegClass(edit.getReg())->getName()
01283                << ':' << PrintReg(edit.getReg()) << ' ' << edit.getParent()
01284                << "\nFrom original " << LIS.getInterval(Original) << '\n');
01285   assert(edit.getParent().isSpillable() &&
01286          "Attempting to spill already spilled value.");
01287   assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
01288 
01289   collectRegsToSpill();
01290   analyzeSiblingValues();
01291   reMaterializeAll();
01292 
01293   // Remat may handle everything.
01294   if (!RegsToSpill.empty())
01295     spillAll();
01296 
01297   Edit->calculateRegClassAndHint(MF, Loops);
01298 }