]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/InlineSpiller.cpp
Add an assertion about the integrity of the iterator.
[opencl/llvm.git] / lib / CodeGen / InlineSpiller.cpp
1 //===-------- InlineSpiller.cpp - Insert spills and restores inline -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The inline spiller modifies the machine function directly instead of
11 // inserting spills and restores in VirtRegMap.
12 //
13 //===----------------------------------------------------------------------===//
15 #include "Spiller.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/TinyPtrVector.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/LiveRangeEdit.h"
22 #include "llvm/CodeGen/LiveStackAnalysis.h"
23 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineInstrBundle.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/VirtRegMap.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
39 using namespace llvm;
41 #define DEBUG_TYPE "regalloc"
43 STATISTIC(NumSpilledRanges,   "Number of spilled live ranges");
44 STATISTIC(NumSnippets,        "Number of spilled snippets");
45 STATISTIC(NumSpills,          "Number of spills inserted");
46 STATISTIC(NumSpillsRemoved,   "Number of spills removed");
47 STATISTIC(NumReloads,         "Number of reloads inserted");
48 STATISTIC(NumReloadsRemoved,  "Number of reloads removed");
49 STATISTIC(NumFolded,          "Number of folded stack accesses");
50 STATISTIC(NumFoldedLoads,     "Number of folded loads");
51 STATISTIC(NumRemats,          "Number of rematerialized defs for spilling");
52 STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads");
53 STATISTIC(NumHoists,          "Number of hoisted spills");
55 static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
56                                      cl::desc("Disable inline spill hoisting"));
58 namespace {
59 class InlineSpiller : public Spiller {
60   MachineFunction &MF;
61   LiveIntervals &LIS;
62   LiveStacks &LSS;
63   AliasAnalysis *AA;
64   MachineDominatorTree &MDT;
65   MachineLoopInfo &Loops;
66   VirtRegMap &VRM;
67   MachineFrameInfo &MFI;
68   MachineRegisterInfo &MRI;
69   const TargetInstrInfo &TII;
70   const TargetRegisterInfo &TRI;
71   const MachineBlockFrequencyInfo &MBFI;
73   // Variables that are valid during spill(), but used by multiple methods.
74   LiveRangeEdit *Edit;
75   LiveInterval *StackInt;
76   int StackSlot;
77   unsigned Original;
79   // All registers to spill to StackSlot, including the main register.
80   SmallVector<unsigned, 8> RegsToSpill;
82   // All COPY instructions to/from snippets.
83   // They are ignored since both operands refer to the same stack slot.
84   SmallPtrSet<MachineInstr*, 8> SnippetCopies;
86   // Values that failed to remat at some point.
87   SmallPtrSet<VNInfo*, 8> UsedValues;
89 public:
90   // Information about a value that was defined by a copy from a sibling
91   // register.
92   struct SibValueInfo {
93     // True when all reaching defs were reloads: No spill is necessary.
94     bool AllDefsAreReloads;
96     // True when value is defined by an original PHI not from splitting.
97     bool DefByOrigPHI;
99     // True when the COPY defining this value killed its source.
100     bool KillsSource;
102     // The preferred register to spill.
103     unsigned SpillReg;
105     // The value of SpillReg that should be spilled.
106     VNInfo *SpillVNI;
108     // The block where SpillVNI should be spilled. Currently, this must be the
109     // block containing SpillVNI->def.
110     MachineBasicBlock *SpillMBB;
112     // A defining instruction that is not a sibling copy or a reload, or NULL.
113     // This can be used as a template for rematerialization.
114     MachineInstr *DefMI;
116     // List of values that depend on this one.  These values are actually the
117     // same, but live range splitting has placed them in different registers,
118     // or SSA update needed to insert PHI-defs to preserve SSA form.  This is
119     // copies of the current value and phi-kills.  Usually only phi-kills cause
120     // more than one dependent value.
121     TinyPtrVector<VNInfo*> Deps;
123     SibValueInfo(unsigned Reg, VNInfo *VNI)
124       : AllDefsAreReloads(true), DefByOrigPHI(false), KillsSource(false),
125         SpillReg(Reg), SpillVNI(VNI), SpillMBB(nullptr), DefMI(nullptr) {}
127     // Returns true when a def has been found.
128     bool hasDef() const { return DefByOrigPHI || DefMI; }
129   };
131 private:
132   // Values in RegsToSpill defined by sibling copies.
133   typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
134   SibValueMap SibValues;
136   // Dead defs generated during spilling.
137   SmallVector<MachineInstr*, 8> DeadDefs;
139   ~InlineSpiller() {}
141 public:
142   InlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
143       : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
144         LSS(pass.getAnalysis<LiveStacks>()),
145         AA(&pass.getAnalysis<AliasAnalysis>()),
146         MDT(pass.getAnalysis<MachineDominatorTree>()),
147         Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
148         MFI(*mf.getFrameInfo()), MRI(mf.getRegInfo()),
149         TII(*mf.getSubtarget().getInstrInfo()),
150         TRI(*mf.getSubtarget().getRegisterInfo()),
151         MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()) {}
153   void spill(LiveRangeEdit &) override;
155 private:
156   bool isSnippet(const LiveInterval &SnipLI);
157   void collectRegsToSpill();
159   bool isRegToSpill(unsigned Reg) {
160     return std::find(RegsToSpill.begin(),
161                      RegsToSpill.end(), Reg) != RegsToSpill.end();
162   }
164   bool isSibling(unsigned Reg);
165   MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
166   void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = nullptr);
167   void analyzeSiblingValues();
169   bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
170   void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
172   void markValueUsed(LiveInterval*, VNInfo*);
173   bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
174   void reMaterializeAll();
176   bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
177   bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> >,
178                          MachineInstr *LoadMI = nullptr);
179   void insertReload(unsigned VReg, SlotIndex, MachineBasicBlock::iterator MI);
180   void insertSpill(unsigned VReg, bool isKill, MachineBasicBlock::iterator MI);
182   void spillAroundUses(unsigned Reg);
183   void spillAll();
184 };
187 namespace llvm {
188 Spiller *createInlineSpiller(MachineFunctionPass &pass,
189                              MachineFunction &mf,
190                              VirtRegMap &vrm) {
191   return new InlineSpiller(pass, mf, vrm);
195 //===----------------------------------------------------------------------===//
196 //                                Snippets
197 //===----------------------------------------------------------------------===//
199 // When spilling a virtual register, we also spill any snippets it is connected
200 // to. The snippets are small live ranges that only have a single real use,
201 // leftovers from live range splitting. Spilling them enables memory operand
202 // folding or tightens the live range around the single use.
203 //
204 // This minimizes register pressure and maximizes the store-to-load distance for
205 // spill slots which can be important in tight loops.
207 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
208 /// otherwise return 0.
209 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
210   if (!MI->isFullCopy())
211     return 0;
212   if (MI->getOperand(0).getReg() == Reg)
213       return MI->getOperand(1).getReg();
214   if (MI->getOperand(1).getReg() == Reg)
215       return MI->getOperand(0).getReg();
216   return 0;
219 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
220 /// It is assumed that SnipLI is a virtual register with the same original as
221 /// Edit->getReg().
222 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
223   unsigned Reg = Edit->getReg();
225   // A snippet is a tiny live range with only a single instruction using it
226   // besides copies to/from Reg or spills/fills. We accept:
227   //
228   //   %snip = COPY %Reg / FILL fi#
229   //   %snip = USE %snip
230   //   %Reg = COPY %snip / SPILL %snip, fi#
231   //
232   if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
233     return false;
235   MachineInstr *UseMI = nullptr;
237   // Check that all uses satisfy our criteria.
238   for (MachineRegisterInfo::reg_instr_nodbg_iterator
239        RI = MRI.reg_instr_nodbg_begin(SnipLI.reg),
240        E = MRI.reg_instr_nodbg_end(); RI != E; ) {
241     MachineInstr *MI = &*(RI++);
243     // Allow copies to/from Reg.
244     if (isFullCopyOf(MI, Reg))
245       continue;
247     // Allow stack slot loads.
248     int FI;
249     if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
250       continue;
252     // Allow stack slot stores.
253     if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
254       continue;
256     // Allow a single additional instruction.
257     if (UseMI && MI != UseMI)
258       return false;
259     UseMI = MI;
260   }
261   return true;
264 /// collectRegsToSpill - Collect live range snippets that only have a single
265 /// real use.
266 void InlineSpiller::collectRegsToSpill() {
267   unsigned Reg = Edit->getReg();
269   // Main register always spills.
270   RegsToSpill.assign(1, Reg);
271   SnippetCopies.clear();
273   // Snippets all have the same original, so there can't be any for an original
274   // register.
275   if (Original == Reg)
276     return;
278   for (MachineRegisterInfo::reg_instr_iterator
279        RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) {
280     MachineInstr *MI = &*(RI++);
281     unsigned SnipReg = isFullCopyOf(MI, Reg);
282     if (!isSibling(SnipReg))
283       continue;
284     LiveInterval &SnipLI = LIS.getInterval(SnipReg);
285     if (!isSnippet(SnipLI))
286       continue;
287     SnippetCopies.insert(MI);
288     if (isRegToSpill(SnipReg))
289       continue;
290     RegsToSpill.push_back(SnipReg);
291     DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
292     ++NumSnippets;
293   }
297 //===----------------------------------------------------------------------===//
298 //                            Sibling Values
299 //===----------------------------------------------------------------------===//
301 // After live range splitting, some values to be spilled may be defined by
302 // copies from sibling registers. We trace the sibling copies back to the
303 // original value if it still exists. We need it for rematerialization.
304 //
305 // Even when the value can't be rematerialized, we still want to determine if
306 // the value has already been spilled, or we may want to hoist the spill from a
307 // loop.
309 bool InlineSpiller::isSibling(unsigned Reg) {
310   return TargetRegisterInfo::isVirtualRegister(Reg) &&
311            VRM.getOriginal(Reg) == Original;
314 #ifndef NDEBUG
315 static raw_ostream &operator<<(raw_ostream &OS,
316                                const InlineSpiller::SibValueInfo &SVI) {
317   OS << "spill " << PrintReg(SVI.SpillReg) << ':'
318      << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
319   if (SVI.SpillMBB)
320     OS << " in BB#" << SVI.SpillMBB->getNumber();
321   if (SVI.AllDefsAreReloads)
322     OS << " all-reloads";
323   if (SVI.DefByOrigPHI)
324     OS << " orig-phi";
325   if (SVI.KillsSource)
326     OS << " kill";
327   OS << " deps[";
328   for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i)
329     OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def;
330   OS << " ]";
331   if (SVI.DefMI)
332     OS << " def: " << *SVI.DefMI;
333   else
334     OS << '\n';
335   return OS;
337 #endif
339 /// propagateSiblingValue - Propagate the value in SVI to dependents if it is
340 /// known.  Otherwise remember the dependency for later.
341 ///
342 /// @param SVIIter SibValues entry to propagate.
343 /// @param VNI Dependent value, or NULL to propagate to all saved dependents.
344 void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVIIter,
345                                           VNInfo *VNI) {
346   SibValueMap::value_type *SVI = &*SVIIter;
348   // When VNI is non-NULL, add it to SVI's deps, and only propagate to that.
349   TinyPtrVector<VNInfo*> FirstDeps;
350   if (VNI) {
351     FirstDeps.push_back(VNI);
352     SVI->second.Deps.push_back(VNI);
353   }
355   // Has the value been completely determined yet?  If not, defer propagation.
356   if (!SVI->second.hasDef())
357     return;
359   // Work list of values to propagate.
360   SmallSetVector<SibValueMap::value_type *, 8> WorkList;
361   WorkList.insert(SVI);
363   do {
364     SVI = WorkList.pop_back_val();
365     TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps;
366     VNI = nullptr;
368     SibValueInfo &SV = SVI->second;
369     if (!SV.SpillMBB)
370       SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
372     DEBUG(dbgs() << "  prop to " << Deps->size() << ": "
373                  << SVI->first->id << '@' << SVI->first->def << ":\t" << SV);
375     assert(SV.hasDef() && "Propagating undefined value");
377     // Should this value be propagated as a preferred spill candidate?  We don't
378     // propagate values of registers that are about to spill.
379     bool PropSpill = !DisableHoisting && !isRegToSpill(SV.SpillReg);
380     unsigned SpillDepth = ~0u;
382     for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(),
383          DepE = Deps->end(); DepI != DepE; ++DepI) {
384       SibValueMap::iterator DepSVI = SibValues.find(*DepI);
385       assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
386       SibValueInfo &DepSV = DepSVI->second;
387       if (!DepSV.SpillMBB)
388         DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
390       bool Changed = false;
392       // Propagate defining instruction.
393       if (!DepSV.hasDef()) {
394         Changed = true;
395         DepSV.DefMI = SV.DefMI;
396         DepSV.DefByOrigPHI = SV.DefByOrigPHI;
397       }
399       // Propagate AllDefsAreReloads.  For PHI values, this computes an AND of
400       // all predecessors.
401       if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
402         Changed = true;
403         DepSV.AllDefsAreReloads = false;
404       }
406       // Propagate best spill value.
407       if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
408         if (SV.SpillMBB == DepSV.SpillMBB) {
409           // DepSV is in the same block.  Hoist when dominated.
410           if (DepSV.KillsSource && SV.SpillVNI->def < DepSV.SpillVNI->def) {
411             // This is an alternative def earlier in the same MBB.
412             // Hoist the spill as far as possible in SpillMBB. This can ease
413             // register pressure:
414             //
415             //   x = def
416             //   y = use x
417             //   s = copy x
418             //
419             // Hoisting the spill of s to immediately after the def removes the
420             // interference between x and y:
421             //
422             //   x = def
423             //   spill x
424             //   y = use x<kill>
425             //
426             // This hoist only helps when the DepSV copy kills its source.
427             Changed = true;
428             DepSV.SpillReg = SV.SpillReg;
429             DepSV.SpillVNI = SV.SpillVNI;
430             DepSV.SpillMBB = SV.SpillMBB;
431           }
432         } else {
433           // DepSV is in a different block.
434           if (SpillDepth == ~0u)
435             SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
437           // Also hoist spills to blocks with smaller loop depth, but make sure
438           // that the new value dominates.  Non-phi dependents are always
439           // dominated, phis need checking.
441           const BranchProbability MarginProb(4, 5); // 80%
442           // Hoist a spill to outer loop if there are multiple dependents (it
443           // can be beneficial if more than one dependents are hoisted) or
444           // if DepSV (the hoisting source) is hotter than SV (the hoisting
445           // destination) (we add a 80% margin to bias a little towards
446           // loop depth).
447           bool HoistCondition =
448             (MBFI.getBlockFreq(DepSV.SpillMBB) >=
449              (MBFI.getBlockFreq(SV.SpillMBB) * MarginProb)) ||
450             Deps->size() > 1;
452           if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
453               HoistCondition &&
454               (!DepSVI->first->isPHIDef() ||
455                MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
456             Changed = true;
457             DepSV.SpillReg = SV.SpillReg;
458             DepSV.SpillVNI = SV.SpillVNI;
459             DepSV.SpillMBB = SV.SpillMBB;
460           }
461         }
462       }
464       if (!Changed)
465         continue;
467       // Something changed in DepSVI. Propagate to dependents.
468       WorkList.insert(&*DepSVI);
470       DEBUG(dbgs() << "  update " << DepSVI->first->id << '@'
471             << DepSVI->first->def << " to:\t" << DepSV);
472     }
473   } while (!WorkList.empty());
476 /// traceSiblingValue - Trace a value that is about to be spilled back to the
477 /// real defining instructions by looking through sibling copies. Always stay
478 /// within the range of OrigVNI so the registers are known to carry the same
479 /// value.
480 ///
481 /// Determine if the value is defined by all reloads, so spilling isn't
482 /// necessary - the value is already in the stack slot.
483 ///
484 /// Return a defining instruction that may be a candidate for rematerialization.
485 ///
486 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
487                                                VNInfo *OrigVNI) {
488   // Check if a cached value already exists.
489   SibValueMap::iterator SVI;
490   bool Inserted;
491   std::tie(SVI, Inserted) =
492     SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
493   if (!Inserted) {
494     DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
495                  << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
496     return SVI->second.DefMI;
497   }
499   DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
500                << UseVNI->id << '@' << UseVNI->def << '\n');
502   // List of (Reg, VNI) that have been inserted into SibValues, but need to be
503   // processed.
504   SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
505   WorkList.push_back(std::make_pair(UseReg, UseVNI));
507   do {
508     unsigned Reg;
509     VNInfo *VNI;
510     std::tie(Reg, VNI) = WorkList.pop_back_val();
511     DEBUG(dbgs() << "  " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
512                  << ":\t");
514     // First check if this value has already been computed.
515     SVI = SibValues.find(VNI);
516     assert(SVI != SibValues.end() && "Missing SibValues entry");
518     // Trace through PHI-defs created by live range splitting.
519     if (VNI->isPHIDef()) {
520       // Stop at original PHIs.  We don't know the value at the predecessors.
521       if (VNI->def == OrigVNI->def) {
522         DEBUG(dbgs() << "orig phi value\n");
523         SVI->second.DefByOrigPHI = true;
524         SVI->second.AllDefsAreReloads = false;
525         propagateSiblingValue(SVI);
526         continue;
527       }
529       // This is a PHI inserted by live range splitting.  We could trace the
530       // live-out value from predecessor blocks, but that search can be very
531       // expensive if there are many predecessors and many more PHIs as
532       // generated by tail-dup when it sees an indirectbr.  Instead, look at
533       // all the non-PHI defs that have the same value as OrigVNI.  They must
534       // jointly dominate VNI->def.  This is not optimal since VNI may actually
535       // be jointly dominated by a smaller subset of defs, so there is a change
536       // we will miss a AllDefsAreReloads optimization.
538       // Separate all values dominated by OrigVNI into PHIs and non-PHIs.
539       SmallVector<VNInfo*, 8> PHIs, NonPHIs;
540       LiveInterval &LI = LIS.getInterval(Reg);
541       LiveInterval &OrigLI = LIS.getInterval(Original);
543       for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end();
544            VI != VE; ++VI) {
545         VNInfo *VNI2 = *VI;
546         if (VNI2->isUnused())
547           continue;
548         if (!OrigLI.containsOneValue() &&
549             OrigLI.getVNInfoAt(VNI2->def) != OrigVNI)
550           continue;
551         if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def)
552           PHIs.push_back(VNI2);
553         else
554           NonPHIs.push_back(VNI2);
555       }
556       DEBUG(dbgs() << "split phi value, checking " << PHIs.size()
557                    << " phi-defs, and " << NonPHIs.size()
558                    << " non-phi/orig defs\n");
560       // Create entries for all the PHIs.  Don't add them to the worklist, we
561       // are processing all of them in one go here.
562       for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
563         SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i])));
565       // Add every PHI as a dependent of all the non-PHIs.
566       for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) {
567         VNInfo *NonPHI = NonPHIs[i];
568         // Known value? Try an insertion.
569         std::tie(SVI, Inserted) =
570           SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI)));
571         // Add all the PHIs as dependents of NonPHI.
572         for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi)
573           SVI->second.Deps.push_back(PHIs[pi]);
574         // This is the first time we see NonPHI, add it to the worklist.
575         if (Inserted)
576           WorkList.push_back(std::make_pair(Reg, NonPHI));
577         else
578           // Propagate to all inserted PHIs, not just VNI.
579           propagateSiblingValue(SVI);
580       }
582       // Next work list item.
583       continue;
584     }
586     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
587     assert(MI && "Missing def");
589     // Trace through sibling copies.
590     if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
591       if (isSibling(SrcReg)) {
592         LiveInterval &SrcLI = LIS.getInterval(SrcReg);
593         LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
594         assert(SrcQ.valueIn() && "Copy from non-existing value");
595         // Check if this COPY kills its source.
596         SVI->second.KillsSource = SrcQ.isKill();
597         VNInfo *SrcVNI = SrcQ.valueIn();
598         DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
599                      << SrcVNI->id << '@' << SrcVNI->def
600                      << " kill=" << unsigned(SVI->second.KillsSource) << '\n');
601         // Known sibling source value? Try an insertion.
602         std::tie(SVI, Inserted) = SibValues.insert(
603             std::make_pair(SrcVNI, SibValueInfo(SrcReg, SrcVNI)));
604         // This is the first time we see Src, add it to the worklist.
605         if (Inserted)
606           WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
607         propagateSiblingValue(SVI, VNI);
608         // Next work list item.
609         continue;
610       }
611     }
613     // Track reachable reloads.
614     SVI->second.DefMI = MI;
615     SVI->second.SpillMBB = MI->getParent();
616     int FI;
617     if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
618       DEBUG(dbgs() << "reload\n");
619       propagateSiblingValue(SVI);
620       // Next work list item.
621       continue;
622     }
624     // Potential remat candidate.
625     DEBUG(dbgs() << "def " << *MI);
626     SVI->second.AllDefsAreReloads = false;
627     propagateSiblingValue(SVI);
628   } while (!WorkList.empty());
630   // Look up the value we were looking for.  We already did this lookup at the
631   // top of the function, but SibValues may have been invalidated.
632   SVI = SibValues.find(UseVNI);
633   assert(SVI != SibValues.end() && "Didn't compute requested info");
634   DEBUG(dbgs() << "  traced to:\t" << SVI->second);
635   return SVI->second.DefMI;
638 /// analyzeSiblingValues - Trace values defined by sibling copies back to
639 /// something that isn't a sibling copy.
640 ///
641 /// Keep track of values that may be rematerializable.
642 void InlineSpiller::analyzeSiblingValues() {
643   SibValues.clear();
645   // No siblings at all?
646   if (Edit->getReg() == Original)
647     return;
649   LiveInterval &OrigLI = LIS.getInterval(Original);
650   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
651     unsigned Reg = RegsToSpill[i];
652     LiveInterval &LI = LIS.getInterval(Reg);
653     for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
654          VE = LI.vni_end(); VI != VE; ++VI) {
655       VNInfo *VNI = *VI;
656       if (VNI->isUnused())
657         continue;
658       MachineInstr *DefMI = nullptr;
659       if (!VNI->isPHIDef()) {
660        DefMI = LIS.getInstructionFromIndex(VNI->def);
661        assert(DefMI && "No defining instruction");
662       }
663       // Check possible sibling copies.
664       if (VNI->isPHIDef() || DefMI->isCopy()) {
665         VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
666         assert(OrigVNI && "Def outside original live range");
667         if (OrigVNI->def != VNI->def)
668           DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
669       }
670       if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) {
671         DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
672                      << VNI->def << " may remat from " << *DefMI);
673       }
674     }
675   }
678 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
679 /// a spill at a better location.
680 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
681   SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
682   VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
683   assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
684   SibValueMap::iterator I = SibValues.find(VNI);
685   if (I == SibValues.end())
686     return false;
688   const SibValueInfo &SVI = I->second;
690   // Let the normal folding code deal with the boring case.
691   if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
692     return false;
694   // SpillReg may have been deleted by remat and DCE.
695   if (!LIS.hasInterval(SVI.SpillReg)) {
696     DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
697     SibValues.erase(I);
698     return false;
699   }
701   LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
702   if (!SibLI.containsValue(SVI.SpillVNI)) {
703     DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
704     SibValues.erase(I);
705     return false;
706   }
708   // Conservatively extend the stack slot range to the range of the original
709   // value. We may be able to do better with stack slot coloring by being more
710   // careful here.
711   assert(StackInt && "No stack slot assigned yet.");
712   LiveInterval &OrigLI = LIS.getInterval(Original);
713   VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
714   StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
715   DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
716                << *StackInt << '\n');
718   // Already spilled everywhere.
719   if (SVI.AllDefsAreReloads) {
720     DEBUG(dbgs() << "\tno spill needed: " << SVI);
721     ++NumOmitReloadSpill;
722     return true;
723   }
724   // We are going to spill SVI.SpillVNI immediately after its def, so clear out
725   // any later spills of the same value.
726   eliminateRedundantSpills(SibLI, SVI.SpillVNI);
728   MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
729   MachineBasicBlock::iterator MII;
730   if (SVI.SpillVNI->isPHIDef())
731     MII = MBB->SkipPHIsAndLabels(MBB->begin());
732   else {
733     MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
734     assert(DefMI && "Defining instruction disappeared");
735     MII = DefMI;
736     ++MII;
737   }
738   // Insert spill without kill flag immediately after def.
739   TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
740                           MRI.getRegClass(SVI.SpillReg), &TRI);
741   --MII; // Point to store instruction.
742   LIS.InsertMachineInstrInMaps(MII);
743   DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
745   ++NumSpills;
746   ++NumHoists;
747   return true;
750 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
751 /// redundant spills of this value in SLI.reg and sibling copies.
752 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
753   assert(VNI && "Missing value");
754   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
755   WorkList.push_back(std::make_pair(&SLI, VNI));
756   assert(StackInt && "No stack slot assigned yet.");
758   do {
759     LiveInterval *LI;
760     std::tie(LI, VNI) = WorkList.pop_back_val();
761     unsigned Reg = LI->reg;
762     DEBUG(dbgs() << "Checking redundant spills for "
763                  << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
765     // Regs to spill are taken care of.
766     if (isRegToSpill(Reg))
767       continue;
769     // Add all of VNI's live range to StackInt.
770     StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
771     DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
773     // Find all spills and copies of VNI.
774     for (MachineRegisterInfo::use_instr_nodbg_iterator
775          UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
776          UI != E; ) {
777       MachineInstr *MI = &*(UI++);
778       if (!MI->isCopy() && !MI->mayStore())
779         continue;
780       SlotIndex Idx = LIS.getInstructionIndex(MI);
781       if (LI->getVNInfoAt(Idx) != VNI)
782         continue;
784       // Follow sibling copies down the dominator tree.
785       if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
786         if (isSibling(DstReg)) {
787            LiveInterval &DstLI = LIS.getInterval(DstReg);
788            VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
789            assert(DstVNI && "Missing defined value");
790            assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
791            WorkList.push_back(std::make_pair(&DstLI, DstVNI));
792         }
793         continue;
794       }
796       // Erase spills.
797       int FI;
798       if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
799         DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
800         // eliminateDeadDefs won't normally remove stores, so switch opcode.
801         MI->setDesc(TII.get(TargetOpcode::KILL));
802         DeadDefs.push_back(MI);
803         ++NumSpillsRemoved;
804         --NumSpills;
805       }
806     }
807   } while (!WorkList.empty());
811 //===----------------------------------------------------------------------===//
812 //                            Rematerialization
813 //===----------------------------------------------------------------------===//
815 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
816 /// instruction cannot be eliminated. See through snippet copies
817 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
818   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
819   WorkList.push_back(std::make_pair(LI, VNI));
820   do {
821     std::tie(LI, VNI) = WorkList.pop_back_val();
822     if (!UsedValues.insert(VNI))
823       continue;
825     if (VNI->isPHIDef()) {
826       MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
827       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
828              PE = MBB->pred_end(); PI != PE; ++PI) {
829         VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI));
830         if (PVNI)
831           WorkList.push_back(std::make_pair(LI, PVNI));
832       }
833       continue;
834     }
836     // Follow snippet copies.
837     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
838     if (!SnippetCopies.count(MI))
839       continue;
840     LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
841     assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
842     VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
843     assert(SnipVNI && "Snippet undefined before copy");
844     WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
845   } while (!WorkList.empty());
848 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
849 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
850                                      MachineBasicBlock::iterator MI) {
852   // Analyze instruction
853   SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
854   MIBundleOperands::VirtRegInfo RI =
855     MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
857   if (!RI.Reads)
858     return false;
860   SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
861   VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
863   if (!ParentVNI) {
864     DEBUG(dbgs() << "\tadding <undef> flags: ");
865     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
866       MachineOperand &MO = MI->getOperand(i);
867       if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
868         MO.setIsUndef();
869     }
870     DEBUG(dbgs() << UseIdx << '\t' << *MI);
871     return true;
872   }
874   if (SnippetCopies.count(MI))
875     return false;
877   // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
878   LiveRangeEdit::Remat RM(ParentVNI);
879   SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
880   if (SibI != SibValues.end())
881     RM.OrigMI = SibI->second.DefMI;
882   if (!Edit->canRematerializeAt(RM, UseIdx, false)) {
883     markValueUsed(&VirtReg, ParentVNI);
884     DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
885     return false;
886   }
888   // If the instruction also writes VirtReg.reg, it had better not require the
889   // same register for uses and defs.
890   if (RI.Tied) {
891     markValueUsed(&VirtReg, ParentVNI);
892     DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
893     return false;
894   }
896   // Before rematerializing into a register for a single instruction, try to
897   // fold a load into the instruction. That avoids allocating a new register.
898   if (RM.OrigMI->canFoldAsLoad() &&
899       foldMemoryOperand(Ops, RM.OrigMI)) {
900     Edit->markRematerialized(RM.ParentVNI);
901     ++NumFoldedLoads;
902     return true;
903   }
905   // Alocate a new register for the remat.
906   unsigned NewVReg = Edit->createFrom(Original);
908   // Finally we can rematerialize OrigMI before MI.
909   SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewVReg, RM,
910                                            TRI);
911   (void)DefIdx;
912   DEBUG(dbgs() << "\tremat:  " << DefIdx << '\t'
913                << *LIS.getInstructionFromIndex(DefIdx));
915   // Replace operands
916   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
917     MachineOperand &MO = MI->getOperand(Ops[i].second);
918     if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
919       MO.setReg(NewVReg);
920       MO.setIsKill();
921     }
922   }
923   DEBUG(dbgs() << "\t        " << UseIdx << '\t' << *MI << '\n');
925   ++NumRemats;
926   return true;
929 /// reMaterializeAll - Try to rematerialize as many uses as possible,
930 /// and trim the live ranges after.
931 void InlineSpiller::reMaterializeAll() {
932   // analyzeSiblingValues has already tested all relevant defining instructions.
933   if (!Edit->anyRematerializable(AA))
934     return;
936   UsedValues.clear();
938   // Try to remat before all uses of snippets.
939   bool anyRemat = false;
940   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
941     unsigned Reg = RegsToSpill[i];
942     LiveInterval &LI = LIS.getInterval(Reg);
943     for (MachineRegisterInfo::reg_bundle_iterator
944            RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
945          RegI != E; ) {
946       MachineInstr *MI = &*(RegI++);
948       // Debug values are not allowed to affect codegen.
949       if (MI->isDebugValue())
950         continue;
952       anyRemat |= reMaterializeFor(LI, MI);
953     }
954   }
955   if (!anyRemat)
956     return;
958   // Remove any values that were completely rematted.
959   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
960     unsigned Reg = RegsToSpill[i];
961     LiveInterval &LI = LIS.getInterval(Reg);
962     for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
963          I != E; ++I) {
964       VNInfo *VNI = *I;
965       if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
966         continue;
967       MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
968       MI->addRegisterDead(Reg, &TRI);
969       if (!MI->allDefsAreDead())
970         continue;
971       DEBUG(dbgs() << "All defs dead: " << *MI);
972       DeadDefs.push_back(MI);
973     }
974   }
976   // Eliminate dead code after remat. Note that some snippet copies may be
977   // deleted here.
978   if (DeadDefs.empty())
979     return;
980   DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
981   Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
983   // Get rid of deleted and empty intervals.
984   unsigned ResultPos = 0;
985   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
986     unsigned Reg = RegsToSpill[i];
987     if (!LIS.hasInterval(Reg))
988       continue;
990     LiveInterval &LI = LIS.getInterval(Reg);
991     if (LI.empty()) {
992       Edit->eraseVirtReg(Reg);
993       continue;
994     }
996     RegsToSpill[ResultPos++] = Reg;
997   }
998   RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
999   DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
1003 //===----------------------------------------------------------------------===//
1004 //                                 Spilling
1005 //===----------------------------------------------------------------------===//
1007 /// If MI is a load or store of StackSlot, it can be removed.
1008 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
1009   int FI = 0;
1010   unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI);
1011   bool IsLoad = InstrReg;
1012   if (!IsLoad)
1013     InstrReg = TII.isStoreToStackSlot(MI, FI);
1015   // We have a stack access. Is it the right register and slot?
1016   if (InstrReg != Reg || FI != StackSlot)
1017     return false;
1019   DEBUG(dbgs() << "Coalescing stack access: " << *MI);
1020   LIS.RemoveMachineInstrFromMaps(MI);
1021   MI->eraseFromParent();
1023   if (IsLoad) {
1024     ++NumReloadsRemoved;
1025     --NumReloads;
1026   } else {
1027     ++NumSpillsRemoved;
1028     --NumSpills;
1029   }
1031   return true;
1034 #if !defined(NDEBUG)
1035 // Dump the range of instructions from B to E with their slot indexes.
1036 static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
1037                                                MachineBasicBlock::iterator E,
1038                                                LiveIntervals const &LIS,
1039                                                const char *const header,
1040                                                unsigned VReg =0) {
1041   char NextLine = '\n';
1042   char SlotIndent = '\t';
1044   if (std::next(B) == E) {
1045     NextLine = ' ';
1046     SlotIndent = ' ';
1047   }
1049   dbgs() << '\t' << header << ": " << NextLine;
1051   for (MachineBasicBlock::iterator I = B; I != E; ++I) {
1052     SlotIndex Idx = LIS.getInstructionIndex(I).getRegSlot();
1054     // If a register was passed in and this instruction has it as a
1055     // destination that is marked as an early clobber, print the
1056     // early-clobber slot index.
1057     if (VReg) {
1058       MachineOperand *MO = I->findRegisterDefOperand(VReg);
1059       if (MO && MO->isEarlyClobber())
1060         Idx = Idx.getRegSlot(true);
1061     }
1063     dbgs() << SlotIndent << Idx << '\t' << *I;
1064   }
1066 #endif
1068 /// foldMemoryOperand - Try folding stack slot references in Ops into their
1069 /// instructions.
1070 ///
1071 /// @param Ops    Operand indices from analyzeVirtReg().
1072 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
1073 /// @return       True on success.
1074 bool InlineSpiller::
1075 foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops,
1076                   MachineInstr *LoadMI) {
1077   if (Ops.empty())
1078     return false;
1079   // Don't attempt folding in bundles.
1080   MachineInstr *MI = Ops.front().first;
1081   if (Ops.back().first != MI || MI->isBundled())
1082     return false;
1084   bool WasCopy = MI->isCopy();
1085   unsigned ImpReg = 0;
1087   bool SpillSubRegs = (MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1088                        MI->getOpcode() == TargetOpcode::STACKMAP);
1090   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1091   // operands.
1092   SmallVector<unsigned, 8> FoldOps;
1093   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1094     unsigned Idx = Ops[i].second;
1095     MachineOperand &MO = MI->getOperand(Idx);
1096     if (MO.isImplicit()) {
1097       ImpReg = MO.getReg();
1098       continue;
1099     }
1100     // FIXME: Teach targets to deal with subregs.
1101     if (!SpillSubRegs && MO.getSubReg())
1102       return false;
1103     // We cannot fold a load instruction into a def.
1104     if (LoadMI && MO.isDef())
1105       return false;
1106     // Tied use operands should not be passed to foldMemoryOperand.
1107     if (!MI->isRegTiedToDefOperand(Idx))
1108       FoldOps.push_back(Idx);
1109   }
1111   MachineInstrSpan MIS(MI);
1113   MachineInstr *FoldMI =
1114                 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
1115                        : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
1116   if (!FoldMI)
1117     return false;
1119   // Remove LIS for any dead defs in the original MI not in FoldMI.
1120   for (MIBundleOperands MO(MI); MO.isValid(); ++MO) {
1121     if (!MO->isReg())
1122       continue;
1123     unsigned Reg = MO->getReg();
1124     if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) ||
1125         MRI.isReserved(Reg)) {
1126       continue;
1127     }
1128     // Skip non-Defs, including undef uses and internal reads.
1129     if (MO->isUse())
1130       continue;
1131     MIBundleOperands::PhysRegInfo RI =
1132       MIBundleOperands(FoldMI).analyzePhysReg(Reg, &TRI);
1133     if (RI.Defines)
1134       continue;
1135     // FoldMI does not define this physreg. Remove the LI segment.
1136     assert(MO->isDead() && "Cannot fold physreg def");
1137     for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) {
1138       if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) {
1139         SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1140         if (VNInfo *VNI = LR->getVNInfoAt(Idx))
1141           LR->removeValNo(VNI);
1142       }
1143     }
1144   }
1146   LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
1147   MI->eraseFromParent();
1149   // Insert any new instructions other than FoldMI into the LIS maps.
1150   assert(!MIS.empty() && "Unexpected empty span of instructions!");
1151   for (MachineBasicBlock::iterator MII = MIS.begin(), End = MIS.end();
1152        MII != End; ++MII)
1153     if (&*MII != FoldMI)
1154       LIS.InsertMachineInstrInMaps(&*MII);
1156   // TII.foldMemoryOperand may have left some implicit operands on the
1157   // instruction.  Strip them.
1158   if (ImpReg)
1159     for (unsigned i = FoldMI->getNumOperands(); i; --i) {
1160       MachineOperand &MO = FoldMI->getOperand(i - 1);
1161       if (!MO.isReg() || !MO.isImplicit())
1162         break;
1163       if (MO.getReg() == ImpReg)
1164         FoldMI->RemoveOperand(i - 1);
1165     }
1167   DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
1168                                            "folded"));
1170   if (!WasCopy)
1171     ++NumFolded;
1172   else if (Ops.front().second == 0)
1173     ++NumSpills;
1174   else
1175     ++NumReloads;
1176   return true;
1179 void InlineSpiller::insertReload(unsigned NewVReg,
1180                                  SlotIndex Idx,
1181                                  MachineBasicBlock::iterator MI) {
1182   MachineBasicBlock &MBB = *MI->getParent();
1184   MachineInstrSpan MIS(MI);
1185   TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
1186                            MRI.getRegClass(NewVReg), &TRI);
1188   LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
1190   DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
1191                                            NewVReg));
1192   ++NumReloads;
1195 /// insertSpill - Insert a spill of NewVReg after MI.
1196 void InlineSpiller::insertSpill(unsigned NewVReg, bool isKill,
1197                                  MachineBasicBlock::iterator MI) {
1198   MachineBasicBlock &MBB = *MI->getParent();
1200   MachineInstrSpan MIS(MI);
1201   TII.storeRegToStackSlot(MBB, std::next(MI), NewVReg, isKill, StackSlot,
1202                           MRI.getRegClass(NewVReg), &TRI);
1204   LIS.InsertMachineInstrRangeInMaps(std::next(MI), MIS.end());
1206   DEBUG(dumpMachineInstrRangeWithSlotIndex(std::next(MI), MIS.end(), LIS,
1207                                            "spill"));
1208   ++NumSpills;
1211 /// spillAroundUses - insert spill code around each use of Reg.
1212 void InlineSpiller::spillAroundUses(unsigned Reg) {
1213   DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
1214   LiveInterval &OldLI = LIS.getInterval(Reg);
1216   // Iterate over instructions using Reg.
1217   for (MachineRegisterInfo::reg_bundle_iterator
1218        RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
1219        RegI != E; ) {
1220     MachineInstr *MI = &*(RegI++);
1222     // Debug values are not allowed to affect codegen.
1223     if (MI->isDebugValue()) {
1224       // Modify DBG_VALUE now that the value is in a spill slot.
1225       bool IsIndirect = MI->isIndirectDebugValue();
1226       uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
1227       const MDNode *Var = MI->getDebugVariable();
1228       const MDNode *Expr = MI->getDebugExpression();
1229       DebugLoc DL = MI->getDebugLoc();
1230       DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1231       MachineBasicBlock *MBB = MI->getParent();
1232       BuildMI(*MBB, MBB->erase(MI), DL, TII.get(TargetOpcode::DBG_VALUE))
1233           .addFrameIndex(StackSlot)
1234           .addImm(Offset)
1235           .addMetadata(Var)
1236           .addMetadata(Expr);
1237       continue;
1238     }
1240     // Ignore copies to/from snippets. We'll delete them.
1241     if (SnippetCopies.count(MI))
1242       continue;
1244     // Stack slot accesses may coalesce away.
1245     if (coalesceStackAccess(MI, Reg))
1246       continue;
1248     // Analyze instruction.
1249     SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
1250     MIBundleOperands::VirtRegInfo RI =
1251       MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops);
1253     // Find the slot index where this instruction reads and writes OldLI.
1254     // This is usually the def slot, except for tied early clobbers.
1255     SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1256     if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1257       if (SlotIndex::isSameInstr(Idx, VNI->def))
1258         Idx = VNI->def;
1260     // Check for a sibling copy.
1261     unsigned SibReg = isFullCopyOf(MI, Reg);
1262     if (SibReg && isSibling(SibReg)) {
1263       // This may actually be a copy between snippets.
1264       if (isRegToSpill(SibReg)) {
1265         DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1266         SnippetCopies.insert(MI);
1267         continue;
1268       }
1269       if (RI.Writes) {
1270         // Hoist the spill of a sib-reg copy.
1271         if (hoistSpill(OldLI, MI)) {
1272           // This COPY is now dead, the value is already in the stack slot.
1273           MI->getOperand(0).setIsDead();
1274           DeadDefs.push_back(MI);
1275           continue;
1276         }
1277       } else {
1278         // This is a reload for a sib-reg copy. Drop spills downstream.
1279         LiveInterval &SibLI = LIS.getInterval(SibReg);
1280         eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1281         // The COPY will fold to a reload below.
1282       }
1283     }
1285     // Attempt to fold memory ops.
1286     if (foldMemoryOperand(Ops))
1287       continue;
1289     // Create a new virtual register for spill/fill.
1290     // FIXME: Infer regclass from instruction alone.
1291     unsigned NewVReg = Edit->createFrom(Reg);
1293     if (RI.Reads)
1294       insertReload(NewVReg, Idx, MI);
1296     // Rewrite instruction operands.
1297     bool hasLiveDef = false;
1298     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1299       MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second);
1300       MO.setReg(NewVReg);
1301       if (MO.isUse()) {
1302         if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second))
1303           MO.setIsKill();
1304       } else {
1305         if (!MO.isDead())
1306           hasLiveDef = true;
1307       }
1308     }
1309     DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n');
1311     // FIXME: Use a second vreg if instruction has no tied ops.
1312     if (RI.Writes)
1313       if (hasLiveDef)
1314         insertSpill(NewVReg, true, MI);
1315   }
1318 /// spillAll - Spill all registers remaining after rematerialization.
1319 void InlineSpiller::spillAll() {
1320   // Update LiveStacks now that we are committed to spilling.
1321   if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1322     StackSlot = VRM.assignVirt2StackSlot(Original);
1323     StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1324     StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1325   } else
1326     StackInt = &LSS.getInterval(StackSlot);
1328   if (Original != Edit->getReg())
1329     VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1331   assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1332   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1333     StackInt->MergeSegmentsInAsValue(LIS.getInterval(RegsToSpill[i]),
1334                                      StackInt->getValNumInfo(0));
1335   DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1337   // Spill around uses of all RegsToSpill.
1338   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1339     spillAroundUses(RegsToSpill[i]);
1341   // Hoisted spills may cause dead code.
1342   if (!DeadDefs.empty()) {
1343     DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1344     Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
1345   }
1347   // Finally delete the SnippetCopies.
1348   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1349     for (MachineRegisterInfo::reg_instr_iterator
1350          RI = MRI.reg_instr_begin(RegsToSpill[i]), E = MRI.reg_instr_end();
1351          RI != E; ) {
1352       MachineInstr *MI = &*(RI++);
1353       assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1354       // FIXME: Do this with a LiveRangeEdit callback.
1355       LIS.RemoveMachineInstrFromMaps(MI);
1356       MI->eraseFromParent();
1357     }
1358   }
1360   // Delete all spilled registers.
1361   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1362     Edit->eraseVirtReg(RegsToSpill[i]);
1365 void InlineSpiller::spill(LiveRangeEdit &edit) {
1366   ++NumSpilledRanges;
1367   Edit = &edit;
1368   assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1369          && "Trying to spill a stack slot.");
1370   // Share a stack slot among all descendants of Original.
1371   Original = VRM.getOriginal(edit.getReg());
1372   StackSlot = VRM.getStackSlot(Original);
1373   StackInt = nullptr;
1375   DEBUG(dbgs() << "Inline spilling "
1376                << MRI.getRegClass(edit.getReg())->getName()
1377                << ':' << edit.getParent()
1378                << "\nFrom original " << PrintReg(Original) << '\n');
1379   assert(edit.getParent().isSpillable() &&
1380          "Attempting to spill already spilled value.");
1381   assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1383   collectRegsToSpill();
1384   analyzeSiblingValues();
1385   reMaterializeAll();
1387   // Remat may handle everything.
1388   if (!RegsToSpill.empty())
1389     spillAll();
1391   Edit->calculateRegClassAndHint(MF, Loops, MBFI);