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