xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/InlineSpiller.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
1 //===- InlineSpiller.cpp - Insert spills and restores inline --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The inline spiller modifies the machine function directly instead of
10 // inserting spills and restores in VirtRegMap.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SplitKit.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/LiveInterval.h"
26 #include "llvm/CodeGen/LiveIntervalCalc.h"
27 #include "llvm/CodeGen/LiveIntervals.h"
28 #include "llvm/CodeGen/LiveRangeEdit.h"
29 #include "llvm/CodeGen/LiveStacks.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineInstrBundle.h"
38 #include "llvm/CodeGen/MachineLoopInfo.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/SlotIndexes.h"
42 #include "llvm/CodeGen/Spiller.h"
43 #include "llvm/CodeGen/StackMaps.h"
44 #include "llvm/CodeGen/TargetInstrInfo.h"
45 #include "llvm/CodeGen/TargetOpcodes.h"
46 #include "llvm/CodeGen/TargetRegisterInfo.h"
47 #include "llvm/CodeGen/TargetSubtargetInfo.h"
48 #include "llvm/CodeGen/VirtRegMap.h"
49 #include "llvm/Config/llvm-config.h"
50 #include "llvm/Support/BlockFrequency.h"
51 #include "llvm/Support/BranchProbability.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <cassert>
58 #include <iterator>
59 #include <tuple>
60 #include <utility>
61 #include <vector>
62 
63 using namespace llvm;
64 
65 #define DEBUG_TYPE "regalloc"
66 
67 STATISTIC(NumSpilledRanges,   "Number of spilled live ranges");
68 STATISTIC(NumSnippets,        "Number of spilled snippets");
69 STATISTIC(NumSpills,          "Number of spills inserted");
70 STATISTIC(NumSpillsRemoved,   "Number of spills removed");
71 STATISTIC(NumReloads,         "Number of reloads inserted");
72 STATISTIC(NumReloadsRemoved,  "Number of reloads removed");
73 STATISTIC(NumFolded,          "Number of folded stack accesses");
74 STATISTIC(NumFoldedLoads,     "Number of folded loads");
75 STATISTIC(NumRemats,          "Number of rematerialized defs for spilling");
76 
77 static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
78                                      cl::desc("Disable inline spill hoisting"));
79 static cl::opt<bool>
80 RestrictStatepointRemat("restrict-statepoint-remat",
81                        cl::init(false), cl::Hidden,
82                        cl::desc("Restrict remat for statepoint operands"));
83 
84 namespace {
85 
86 class HoistSpillHelper : private LiveRangeEdit::Delegate {
87   MachineFunction &MF;
88   LiveIntervals &LIS;
89   LiveStacks &LSS;
90   AliasAnalysis *AA;
91   MachineDominatorTree &MDT;
92   MachineLoopInfo &Loops;
93   VirtRegMap &VRM;
94   MachineRegisterInfo &MRI;
95   const TargetInstrInfo &TII;
96   const TargetRegisterInfo &TRI;
97   const MachineBlockFrequencyInfo &MBFI;
98 
99   InsertPointAnalysis IPA;
100 
101   // Map from StackSlot to the LiveInterval of the original register.
102   // Note the LiveInterval of the original register may have been deleted
103   // after it is spilled. We keep a copy here to track the range where
104   // spills can be moved.
105   DenseMap<int, std::unique_ptr<LiveInterval>> StackSlotToOrigLI;
106 
107   // Map from pair of (StackSlot and Original VNI) to a set of spills which
108   // have the same stackslot and have equal values defined by Original VNI.
109   // These spills are mergeable and are hoist candiates.
110   using MergeableSpillsMap =
111       MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
112   MergeableSpillsMap MergeableSpills;
113 
114   /// This is the map from original register to a set containing all its
115   /// siblings. To hoist a spill to another BB, we need to find out a live
116   /// sibling there and use it as the source of the new spill.
117   DenseMap<Register, SmallSetVector<Register, 16>> Virt2SiblingsMap;
118 
119   bool isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
120                      MachineBasicBlock &BB, Register &LiveReg);
121 
122   void rmRedundantSpills(
123       SmallPtrSet<MachineInstr *, 16> &Spills,
124       SmallVectorImpl<MachineInstr *> &SpillsToRm,
125       DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
126 
127   void getVisitOrders(
128       MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
129       SmallVectorImpl<MachineDomTreeNode *> &Orders,
130       SmallVectorImpl<MachineInstr *> &SpillsToRm,
131       DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
132       DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
133 
134   void runHoistSpills(LiveInterval &OrigLI, VNInfo &OrigVNI,
135                       SmallPtrSet<MachineInstr *, 16> &Spills,
136                       SmallVectorImpl<MachineInstr *> &SpillsToRm,
137                       DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns);
138 
139 public:
140   HoistSpillHelper(MachineFunctionPass &pass, MachineFunction &mf,
141                    VirtRegMap &vrm)
142       : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
143         LSS(pass.getAnalysis<LiveStacks>()),
144         AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
145         MDT(pass.getAnalysis<MachineDominatorTree>()),
146         Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
147         MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
148         TRI(*mf.getSubtarget().getRegisterInfo()),
149         MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
150         IPA(LIS, mf.getNumBlockIDs()) {}
151 
152   void addToMergeableSpills(MachineInstr &Spill, int StackSlot,
153                             unsigned Original);
154   bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
155   void hoistAllSpills();
156   void LRE_DidCloneVirtReg(Register, Register) override;
157 };
158 
159 class InlineSpiller : public Spiller {
160   MachineFunction &MF;
161   LiveIntervals &LIS;
162   LiveStacks &LSS;
163   AliasAnalysis *AA;
164   MachineDominatorTree &MDT;
165   MachineLoopInfo &Loops;
166   VirtRegMap &VRM;
167   MachineRegisterInfo &MRI;
168   const TargetInstrInfo &TII;
169   const TargetRegisterInfo &TRI;
170   const MachineBlockFrequencyInfo &MBFI;
171 
172   // Variables that are valid during spill(), but used by multiple methods.
173   LiveRangeEdit *Edit;
174   LiveInterval *StackInt;
175   int StackSlot;
176   Register Original;
177 
178   // All registers to spill to StackSlot, including the main register.
179   SmallVector<Register, 8> RegsToSpill;
180 
181   // All COPY instructions to/from snippets.
182   // They are ignored since both operands refer to the same stack slot.
183   SmallPtrSet<MachineInstr*, 8> SnippetCopies;
184 
185   // Values that failed to remat at some point.
186   SmallPtrSet<VNInfo*, 8> UsedValues;
187 
188   // Dead defs generated during spilling.
189   SmallVector<MachineInstr*, 8> DeadDefs;
190 
191   // Object records spills information and does the hoisting.
192   HoistSpillHelper HSpiller;
193 
194   // Live range weight calculator.
195   VirtRegAuxInfo &VRAI;
196 
197   ~InlineSpiller() override = default;
198 
199 public:
200   InlineSpiller(MachineFunctionPass &Pass, MachineFunction &MF, VirtRegMap &VRM,
201                 VirtRegAuxInfo &VRAI)
202       : MF(MF), LIS(Pass.getAnalysis<LiveIntervals>()),
203         LSS(Pass.getAnalysis<LiveStacks>()),
204         AA(&Pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
205         MDT(Pass.getAnalysis<MachineDominatorTree>()),
206         Loops(Pass.getAnalysis<MachineLoopInfo>()), VRM(VRM),
207         MRI(MF.getRegInfo()), TII(*MF.getSubtarget().getInstrInfo()),
208         TRI(*MF.getSubtarget().getRegisterInfo()),
209         MBFI(Pass.getAnalysis<MachineBlockFrequencyInfo>()),
210         HSpiller(Pass, MF, VRM), VRAI(VRAI) {}
211 
212   void spill(LiveRangeEdit &) override;
213   void postOptimization() override;
214 
215 private:
216   bool isSnippet(const LiveInterval &SnipLI);
217   void collectRegsToSpill();
218 
219   bool isRegToSpill(Register Reg) { return is_contained(RegsToSpill, Reg); }
220 
221   bool isSibling(Register Reg);
222   bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
223   void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
224 
225   void markValueUsed(LiveInterval*, VNInfo*);
226   bool canGuaranteeAssignmentAfterRemat(Register VReg, MachineInstr &MI);
227   bool reMaterializeFor(LiveInterval &, MachineInstr &MI);
228   void reMaterializeAll();
229 
230   bool coalesceStackAccess(MachineInstr *MI, Register Reg);
231   bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
232                          MachineInstr *LoadMI = nullptr);
233   void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
234   void insertSpill(Register VReg, bool isKill, MachineBasicBlock::iterator MI);
235 
236   void spillAroundUses(Register Reg);
237   void spillAll();
238 };
239 
240 } // end anonymous namespace
241 
242 Spiller::~Spiller() = default;
243 
244 void Spiller::anchor() {}
245 
246 Spiller *llvm::createInlineSpiller(MachineFunctionPass &Pass,
247                                    MachineFunction &MF, VirtRegMap &VRM,
248                                    VirtRegAuxInfo &VRAI) {
249   return new InlineSpiller(Pass, MF, VRM, VRAI);
250 }
251 
252 //===----------------------------------------------------------------------===//
253 //                                Snippets
254 //===----------------------------------------------------------------------===//
255 
256 // When spilling a virtual register, we also spill any snippets it is connected
257 // to. The snippets are small live ranges that only have a single real use,
258 // leftovers from live range splitting. Spilling them enables memory operand
259 // folding or tightens the live range around the single use.
260 //
261 // This minimizes register pressure and maximizes the store-to-load distance for
262 // spill slots which can be important in tight loops.
263 
264 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
265 /// otherwise return 0.
266 static Register isFullCopyOf(const MachineInstr &MI, Register Reg) {
267   if (!MI.isFullCopy())
268     return Register();
269   if (MI.getOperand(0).getReg() == Reg)
270     return MI.getOperand(1).getReg();
271   if (MI.getOperand(1).getReg() == Reg)
272     return MI.getOperand(0).getReg();
273   return Register();
274 }
275 
276 static void getVDefInterval(const MachineInstr &MI, LiveIntervals &LIS) {
277   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
278     const MachineOperand &MO = MI.getOperand(I);
279     if (MO.isReg() && MO.isDef() && Register::isVirtualRegister(MO.getReg()))
280       LIS.getInterval(MO.getReg());
281   }
282 }
283 
284 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
285 /// It is assumed that SnipLI is a virtual register with the same original as
286 /// Edit->getReg().
287 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
288   Register Reg = Edit->getReg();
289 
290   // A snippet is a tiny live range with only a single instruction using it
291   // besides copies to/from Reg or spills/fills. We accept:
292   //
293   //   %snip = COPY %Reg / FILL fi#
294   //   %snip = USE %snip
295   //   %Reg = COPY %snip / SPILL %snip, fi#
296   //
297   if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
298     return false;
299 
300   MachineInstr *UseMI = nullptr;
301 
302   // Check that all uses satisfy our criteria.
303   for (MachineRegisterInfo::reg_instr_nodbg_iterator
304            RI = MRI.reg_instr_nodbg_begin(SnipLI.reg()),
305            E = MRI.reg_instr_nodbg_end();
306        RI != E;) {
307     MachineInstr &MI = *RI++;
308 
309     // Allow copies to/from Reg.
310     if (isFullCopyOf(MI, Reg))
311       continue;
312 
313     // Allow stack slot loads.
314     int FI;
315     if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
316       continue;
317 
318     // Allow stack slot stores.
319     if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
320       continue;
321 
322     // Allow a single additional instruction.
323     if (UseMI && &MI != UseMI)
324       return false;
325     UseMI = &MI;
326   }
327   return true;
328 }
329 
330 /// collectRegsToSpill - Collect live range snippets that only have a single
331 /// real use.
332 void InlineSpiller::collectRegsToSpill() {
333   Register Reg = Edit->getReg();
334 
335   // Main register always spills.
336   RegsToSpill.assign(1, Reg);
337   SnippetCopies.clear();
338 
339   // Snippets all have the same original, so there can't be any for an original
340   // register.
341   if (Original == Reg)
342     return;
343 
344   for (MachineInstr &MI :
345        llvm::make_early_inc_range(MRI.reg_instructions(Reg))) {
346     Register SnipReg = isFullCopyOf(MI, Reg);
347     if (!isSibling(SnipReg))
348       continue;
349     LiveInterval &SnipLI = LIS.getInterval(SnipReg);
350     if (!isSnippet(SnipLI))
351       continue;
352     SnippetCopies.insert(&MI);
353     if (isRegToSpill(SnipReg))
354       continue;
355     RegsToSpill.push_back(SnipReg);
356     LLVM_DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
357     ++NumSnippets;
358   }
359 }
360 
361 bool InlineSpiller::isSibling(Register Reg) {
362   return Reg.isVirtual() && VRM.getOriginal(Reg) == Original;
363 }
364 
365 /// It is beneficial to spill to earlier place in the same BB in case
366 /// as follows:
367 /// There is an alternative def earlier in the same MBB.
368 /// Hoist the spill as far as possible in SpillMBB. This can ease
369 /// register pressure:
370 ///
371 ///   x = def
372 ///   y = use x
373 ///   s = copy x
374 ///
375 /// Hoisting the spill of s to immediately after the def removes the
376 /// interference between x and y:
377 ///
378 ///   x = def
379 ///   spill x
380 ///   y = use killed x
381 ///
382 /// This hoist only helps when the copy kills its source.
383 ///
384 bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
385                                        MachineInstr &CopyMI) {
386   SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
387 #ifndef NDEBUG
388   VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
389   assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
390 #endif
391 
392   Register SrcReg = CopyMI.getOperand(1).getReg();
393   LiveInterval &SrcLI = LIS.getInterval(SrcReg);
394   VNInfo *SrcVNI = SrcLI.getVNInfoAt(Idx);
395   LiveQueryResult SrcQ = SrcLI.Query(Idx);
396   MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(SrcVNI->def);
397   if (DefMBB != CopyMI.getParent() || !SrcQ.isKill())
398     return false;
399 
400   // Conservatively extend the stack slot range to the range of the original
401   // value. We may be able to do better with stack slot coloring by being more
402   // careful here.
403   assert(StackInt && "No stack slot assigned yet.");
404   LiveInterval &OrigLI = LIS.getInterval(Original);
405   VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
406   StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
407   LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
408                     << *StackInt << '\n');
409 
410   // We are going to spill SrcVNI immediately after its def, so clear out
411   // any later spills of the same value.
412   eliminateRedundantSpills(SrcLI, SrcVNI);
413 
414   MachineBasicBlock *MBB = LIS.getMBBFromIndex(SrcVNI->def);
415   MachineBasicBlock::iterator MII;
416   if (SrcVNI->isPHIDef())
417     MII = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
418   else {
419     MachineInstr *DefMI = LIS.getInstructionFromIndex(SrcVNI->def);
420     assert(DefMI && "Defining instruction disappeared");
421     MII = DefMI;
422     ++MII;
423   }
424   MachineInstrSpan MIS(MII, MBB);
425   // Insert spill without kill flag immediately after def.
426   TII.storeRegToStackSlot(*MBB, MII, SrcReg, false, StackSlot,
427                           MRI.getRegClass(SrcReg), &TRI);
428   LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MII);
429   for (const MachineInstr &MI : make_range(MIS.begin(), MII))
430     getVDefInterval(MI, LIS);
431   --MII; // Point to store instruction.
432   LLVM_DEBUG(dbgs() << "\thoisted: " << SrcVNI->def << '\t' << *MII);
433 
434   // If there is only 1 store instruction is required for spill, add it
435   // to mergeable list. In X86 AMX, 2 intructions are required to store.
436   // We disable the merge for this case.
437   if (MIS.begin() == MII)
438     HSpiller.addToMergeableSpills(*MII, StackSlot, Original);
439   ++NumSpills;
440   return true;
441 }
442 
443 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
444 /// redundant spills of this value in SLI.reg and sibling copies.
445 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
446   assert(VNI && "Missing value");
447   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
448   WorkList.push_back(std::make_pair(&SLI, VNI));
449   assert(StackInt && "No stack slot assigned yet.");
450 
451   do {
452     LiveInterval *LI;
453     std::tie(LI, VNI) = WorkList.pop_back_val();
454     Register Reg = LI->reg();
455     LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
456                       << VNI->def << " in " << *LI << '\n');
457 
458     // Regs to spill are taken care of.
459     if (isRegToSpill(Reg))
460       continue;
461 
462     // Add all of VNI's live range to StackInt.
463     StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
464     LLVM_DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
465 
466     // Find all spills and copies of VNI.
467     for (MachineInstr &MI :
468          llvm::make_early_inc_range(MRI.use_nodbg_instructions(Reg))) {
469       if (!MI.isCopy() && !MI.mayStore())
470         continue;
471       SlotIndex Idx = LIS.getInstructionIndex(MI);
472       if (LI->getVNInfoAt(Idx) != VNI)
473         continue;
474 
475       // Follow sibling copies down the dominator tree.
476       if (Register DstReg = isFullCopyOf(MI, Reg)) {
477         if (isSibling(DstReg)) {
478            LiveInterval &DstLI = LIS.getInterval(DstReg);
479            VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
480            assert(DstVNI && "Missing defined value");
481            assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
482            WorkList.push_back(std::make_pair(&DstLI, DstVNI));
483         }
484         continue;
485       }
486 
487       // Erase spills.
488       int FI;
489       if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
490         LLVM_DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << MI);
491         // eliminateDeadDefs won't normally remove stores, so switch opcode.
492         MI.setDesc(TII.get(TargetOpcode::KILL));
493         DeadDefs.push_back(&MI);
494         ++NumSpillsRemoved;
495         if (HSpiller.rmFromMergeableSpills(MI, StackSlot))
496           --NumSpills;
497       }
498     }
499   } while (!WorkList.empty());
500 }
501 
502 //===----------------------------------------------------------------------===//
503 //                            Rematerialization
504 //===----------------------------------------------------------------------===//
505 
506 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
507 /// instruction cannot be eliminated. See through snippet copies
508 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
509   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
510   WorkList.push_back(std::make_pair(LI, VNI));
511   do {
512     std::tie(LI, VNI) = WorkList.pop_back_val();
513     if (!UsedValues.insert(VNI).second)
514       continue;
515 
516     if (VNI->isPHIDef()) {
517       MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
518       for (MachineBasicBlock *P : MBB->predecessors()) {
519         VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(P));
520         if (PVNI)
521           WorkList.push_back(std::make_pair(LI, PVNI));
522       }
523       continue;
524     }
525 
526     // Follow snippet copies.
527     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
528     if (!SnippetCopies.count(MI))
529       continue;
530     LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
531     assert(isRegToSpill(SnipLI.reg()) && "Unexpected register in copy");
532     VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
533     assert(SnipVNI && "Snippet undefined before copy");
534     WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
535   } while (!WorkList.empty());
536 }
537 
538 bool InlineSpiller::canGuaranteeAssignmentAfterRemat(Register VReg,
539                                                      MachineInstr &MI) {
540   if (!RestrictStatepointRemat)
541     return true;
542   // Here's a quick explanation of the problem we're trying to handle here:
543   // * There are some pseudo instructions with more vreg uses than there are
544   //   physical registers on the machine.
545   // * This is normally handled by spilling the vreg, and folding the reload
546   //   into the user instruction.  (Thus decreasing the number of used vregs
547   //   until the remainder can be assigned to physregs.)
548   // * However, since we may try to spill vregs in any order, we can end up
549   //   trying to spill each operand to the instruction, and then rematting it
550   //   instead.  When that happens, the new live intervals (for the remats) are
551   //   expected to be trivially assignable (i.e. RS_Done).  However, since we
552   //   may have more remats than physregs, we're guaranteed to fail to assign
553   //   one.
554   // At the moment, we only handle this for STATEPOINTs since they're the only
555   // pseudo op where we've seen this.  If we start seeing other instructions
556   // with the same problem, we need to revisit this.
557   if (MI.getOpcode() != TargetOpcode::STATEPOINT)
558     return true;
559   // For STATEPOINTs we allow re-materialization for fixed arguments only hoping
560   // that number of physical registers is enough to cover all fixed arguments.
561   // If it is not true we need to revisit it.
562   for (unsigned Idx = StatepointOpers(&MI).getVarIdx(),
563                 EndIdx = MI.getNumOperands();
564        Idx < EndIdx; ++Idx) {
565     MachineOperand &MO = MI.getOperand(Idx);
566     if (MO.isReg() && MO.getReg() == VReg)
567       return false;
568   }
569   return true;
570 }
571 
572 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
573 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, MachineInstr &MI) {
574   // Analyze instruction
575   SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
576   VirtRegInfo RI = AnalyzeVirtRegInBundle(MI, VirtReg.reg(), &Ops);
577 
578   if (!RI.Reads)
579     return false;
580 
581   SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
582   VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
583 
584   if (!ParentVNI) {
585     LLVM_DEBUG(dbgs() << "\tadding <undef> flags: ");
586     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
587       MachineOperand &MO = MI.getOperand(i);
588       if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg())
589         MO.setIsUndef();
590     }
591     LLVM_DEBUG(dbgs() << UseIdx << '\t' << MI);
592     return true;
593   }
594 
595   if (SnippetCopies.count(&MI))
596     return false;
597 
598   LiveInterval &OrigLI = LIS.getInterval(Original);
599   VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
600   LiveRangeEdit::Remat RM(ParentVNI);
601   RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def);
602 
603   if (!Edit->canRematerializeAt(RM, OrigVNI, UseIdx, false)) {
604     markValueUsed(&VirtReg, ParentVNI);
605     LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
606     return false;
607   }
608 
609   // If the instruction also writes VirtReg.reg, it had better not require the
610   // same register for uses and defs.
611   if (RI.Tied) {
612     markValueUsed(&VirtReg, ParentVNI);
613     LLVM_DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << MI);
614     return false;
615   }
616 
617   // Before rematerializing into a register for a single instruction, try to
618   // fold a load into the instruction. That avoids allocating a new register.
619   if (RM.OrigMI->canFoldAsLoad() &&
620       foldMemoryOperand(Ops, RM.OrigMI)) {
621     Edit->markRematerialized(RM.ParentVNI);
622     ++NumFoldedLoads;
623     return true;
624   }
625 
626   // If we can't guarantee that we'll be able to actually assign the new vreg,
627   // we can't remat.
628   if (!canGuaranteeAssignmentAfterRemat(VirtReg.reg(), MI)) {
629     markValueUsed(&VirtReg, ParentVNI);
630     LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
631     return false;
632   }
633 
634   // Allocate a new register for the remat.
635   Register NewVReg = Edit->createFrom(Original);
636 
637   // Finally we can rematerialize OrigMI before MI.
638   SlotIndex DefIdx =
639       Edit->rematerializeAt(*MI.getParent(), MI, NewVReg, RM, TRI);
640 
641   // We take the DebugLoc from MI, since OrigMI may be attributed to a
642   // different source location.
643   auto *NewMI = LIS.getInstructionFromIndex(DefIdx);
644   NewMI->setDebugLoc(MI.getDebugLoc());
645 
646   (void)DefIdx;
647   LLVM_DEBUG(dbgs() << "\tremat:  " << DefIdx << '\t'
648                     << *LIS.getInstructionFromIndex(DefIdx));
649 
650   // Replace operands
651   for (const auto &OpPair : Ops) {
652     MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
653     if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg()) {
654       MO.setReg(NewVReg);
655       MO.setIsKill();
656     }
657   }
658   LLVM_DEBUG(dbgs() << "\t        " << UseIdx << '\t' << MI << '\n');
659 
660   ++NumRemats;
661   return true;
662 }
663 
664 /// reMaterializeAll - Try to rematerialize as many uses as possible,
665 /// and trim the live ranges after.
666 void InlineSpiller::reMaterializeAll() {
667   if (!Edit->anyRematerializable(AA))
668     return;
669 
670   UsedValues.clear();
671 
672   // Try to remat before all uses of snippets.
673   bool anyRemat = false;
674   for (Register Reg : RegsToSpill) {
675     LiveInterval &LI = LIS.getInterval(Reg);
676     for (MachineInstr &MI : llvm::make_early_inc_range(MRI.reg_bundles(Reg))) {
677       // Debug values are not allowed to affect codegen.
678       if (MI.isDebugValue())
679         continue;
680 
681       assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "
682              "instruction that isn't a DBG_VALUE");
683 
684       anyRemat |= reMaterializeFor(LI, MI);
685     }
686   }
687   if (!anyRemat)
688     return;
689 
690   // Remove any values that were completely rematted.
691   for (Register Reg : RegsToSpill) {
692     LiveInterval &LI = LIS.getInterval(Reg);
693     for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
694          I != E; ++I) {
695       VNInfo *VNI = *I;
696       if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
697         continue;
698       MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
699       MI->addRegisterDead(Reg, &TRI);
700       if (!MI->allDefsAreDead())
701         continue;
702       LLVM_DEBUG(dbgs() << "All defs dead: " << *MI);
703       DeadDefs.push_back(MI);
704     }
705   }
706 
707   // Eliminate dead code after remat. Note that some snippet copies may be
708   // deleted here.
709   if (DeadDefs.empty())
710     return;
711   LLVM_DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
712   Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
713 
714   // LiveRangeEdit::eliminateDeadDef is used to remove dead define instructions
715   // after rematerialization.  To remove a VNI for a vreg from its LiveInterval,
716   // LiveIntervals::removeVRegDefAt is used. However, after non-PHI VNIs are all
717   // removed, PHI VNI are still left in the LiveInterval.
718   // So to get rid of unused reg, we need to check whether it has non-dbg
719   // reference instead of whether it has non-empty interval.
720   unsigned ResultPos = 0;
721   for (Register Reg : RegsToSpill) {
722     if (MRI.reg_nodbg_empty(Reg)) {
723       Edit->eraseVirtReg(Reg);
724       continue;
725     }
726 
727     assert(LIS.hasInterval(Reg) &&
728            (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&
729            "Empty and not used live-range?!");
730 
731     RegsToSpill[ResultPos++] = Reg;
732   }
733   RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
734   LLVM_DEBUG(dbgs() << RegsToSpill.size()
735                     << " registers to spill after remat.\n");
736 }
737 
738 //===----------------------------------------------------------------------===//
739 //                                 Spilling
740 //===----------------------------------------------------------------------===//
741 
742 /// If MI is a load or store of StackSlot, it can be removed.
743 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
744   int FI = 0;
745   Register InstrReg = TII.isLoadFromStackSlot(*MI, FI);
746   bool IsLoad = InstrReg;
747   if (!IsLoad)
748     InstrReg = TII.isStoreToStackSlot(*MI, FI);
749 
750   // We have a stack access. Is it the right register and slot?
751   if (InstrReg != Reg || FI != StackSlot)
752     return false;
753 
754   if (!IsLoad)
755     HSpiller.rmFromMergeableSpills(*MI, StackSlot);
756 
757   LLVM_DEBUG(dbgs() << "Coalescing stack access: " << *MI);
758   LIS.RemoveMachineInstrFromMaps(*MI);
759   MI->eraseFromParent();
760 
761   if (IsLoad) {
762     ++NumReloadsRemoved;
763     --NumReloads;
764   } else {
765     ++NumSpillsRemoved;
766     --NumSpills;
767   }
768 
769   return true;
770 }
771 
772 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
773 LLVM_DUMP_METHOD
774 // Dump the range of instructions from B to E with their slot indexes.
775 static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
776                                                MachineBasicBlock::iterator E,
777                                                LiveIntervals const &LIS,
778                                                const char *const header,
779                                                Register VReg = Register()) {
780   char NextLine = '\n';
781   char SlotIndent = '\t';
782 
783   if (std::next(B) == E) {
784     NextLine = ' ';
785     SlotIndent = ' ';
786   }
787 
788   dbgs() << '\t' << header << ": " << NextLine;
789 
790   for (MachineBasicBlock::iterator I = B; I != E; ++I) {
791     SlotIndex Idx = LIS.getInstructionIndex(*I).getRegSlot();
792 
793     // If a register was passed in and this instruction has it as a
794     // destination that is marked as an early clobber, print the
795     // early-clobber slot index.
796     if (VReg) {
797       MachineOperand *MO = I->findRegisterDefOperand(VReg);
798       if (MO && MO->isEarlyClobber())
799         Idx = Idx.getRegSlot(true);
800     }
801 
802     dbgs() << SlotIndent << Idx << '\t' << *I;
803   }
804 }
805 #endif
806 
807 /// foldMemoryOperand - Try folding stack slot references in Ops into their
808 /// instructions.
809 ///
810 /// @param Ops    Operand indices from AnalyzeVirtRegInBundle().
811 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
812 /// @return       True on success.
813 bool InlineSpiller::
814 foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>> Ops,
815                   MachineInstr *LoadMI) {
816   if (Ops.empty())
817     return false;
818   // Don't attempt folding in bundles.
819   MachineInstr *MI = Ops.front().first;
820   if (Ops.back().first != MI || MI->isBundled())
821     return false;
822 
823   bool WasCopy = MI->isCopy();
824   Register ImpReg;
825 
826   // TII::foldMemoryOperand will do what we need here for statepoint
827   // (fold load into use and remove corresponding def). We will replace
828   // uses of removed def with loads (spillAroundUses).
829   // For that to work we need to untie def and use to pass it through
830   // foldMemoryOperand and signal foldPatchpoint that it is allowed to
831   // fold them.
832   bool UntieRegs = MI->getOpcode() == TargetOpcode::STATEPOINT;
833 
834   // Spill subregs if the target allows it.
835   // We always want to spill subregs for stackmap/patchpoint pseudos.
836   bool SpillSubRegs = TII.isSubregFoldable() ||
837                       MI->getOpcode() == TargetOpcode::STATEPOINT ||
838                       MI->getOpcode() == TargetOpcode::PATCHPOINT ||
839                       MI->getOpcode() == TargetOpcode::STACKMAP;
840 
841   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
842   // operands.
843   SmallVector<unsigned, 8> FoldOps;
844   for (const auto &OpPair : Ops) {
845     unsigned Idx = OpPair.second;
846     assert(MI == OpPair.first && "Instruction conflict during operand folding");
847     MachineOperand &MO = MI->getOperand(Idx);
848     if (MO.isImplicit()) {
849       ImpReg = MO.getReg();
850       continue;
851     }
852 
853     if (!SpillSubRegs && MO.getSubReg())
854       return false;
855     // We cannot fold a load instruction into a def.
856     if (LoadMI && MO.isDef())
857       return false;
858     // Tied use operands should not be passed to foldMemoryOperand.
859     if (UntieRegs || !MI->isRegTiedToDefOperand(Idx))
860       FoldOps.push_back(Idx);
861   }
862 
863   // If we only have implicit uses, we won't be able to fold that.
864   // Moreover, TargetInstrInfo::foldMemoryOperand will assert if we try!
865   if (FoldOps.empty())
866     return false;
867 
868   MachineInstrSpan MIS(MI, MI->getParent());
869 
870   SmallVector<std::pair<unsigned, unsigned> > TiedOps;
871   if (UntieRegs)
872     for (unsigned Idx : FoldOps) {
873       MachineOperand &MO = MI->getOperand(Idx);
874       if (!MO.isTied())
875         continue;
876       unsigned Tied = MI->findTiedOperandIdx(Idx);
877       if (MO.isUse())
878         TiedOps.emplace_back(Tied, Idx);
879       else {
880         assert(MO.isDef() && "Tied to not use and def?");
881         TiedOps.emplace_back(Idx, Tied);
882       }
883       MI->untieRegOperand(Idx);
884     }
885 
886   MachineInstr *FoldMI =
887       LoadMI ? TII.foldMemoryOperand(*MI, FoldOps, *LoadMI, &LIS)
888              : TII.foldMemoryOperand(*MI, FoldOps, StackSlot, &LIS, &VRM);
889   if (!FoldMI) {
890     // Re-tie operands.
891     for (auto Tied : TiedOps)
892       MI->tieOperands(Tied.first, Tied.second);
893     return false;
894   }
895 
896   // Remove LIS for any dead defs in the original MI not in FoldMI.
897   for (MIBundleOperands MO(*MI); MO.isValid(); ++MO) {
898     if (!MO->isReg())
899       continue;
900     Register Reg = MO->getReg();
901     if (!Reg || Register::isVirtualRegister(Reg) || MRI.isReserved(Reg)) {
902       continue;
903     }
904     // Skip non-Defs, including undef uses and internal reads.
905     if (MO->isUse())
906       continue;
907     PhysRegInfo RI = AnalyzePhysRegInBundle(*FoldMI, Reg, &TRI);
908     if (RI.FullyDefined)
909       continue;
910     // FoldMI does not define this physreg. Remove the LI segment.
911     assert(MO->isDead() && "Cannot fold physreg def");
912     SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
913     LIS.removePhysRegDefAt(Reg.asMCReg(), Idx);
914   }
915 
916   int FI;
917   if (TII.isStoreToStackSlot(*MI, FI) &&
918       HSpiller.rmFromMergeableSpills(*MI, FI))
919     --NumSpills;
920   LIS.ReplaceMachineInstrInMaps(*MI, *FoldMI);
921   // Update the call site info.
922   if (MI->isCandidateForCallSiteEntry())
923     MI->getMF()->moveCallSiteInfo(MI, FoldMI);
924 
925   // If we've folded a store into an instruction labelled with debug-info,
926   // record a substitution from the old operand to the memory operand. Handle
927   // the simple common case where operand 0 is the one being folded, plus when
928   // the destination operand is also a tied def. More values could be
929   // substituted / preserved with more analysis.
930   if (MI->peekDebugInstrNum() && Ops[0].second == 0) {
931     // Helper lambda.
932     auto MakeSubstitution = [this,FoldMI,MI,&Ops]() {
933       // Substitute old operand zero to the new instructions memory operand.
934       unsigned OldOperandNum = Ops[0].second;
935       unsigned NewNum = FoldMI->getDebugInstrNum();
936       unsigned OldNum = MI->getDebugInstrNum();
937       MF.makeDebugValueSubstitution({OldNum, OldOperandNum},
938                          {NewNum, MachineFunction::DebugOperandMemNumber});
939     };
940 
941     const MachineOperand &Op0 = MI->getOperand(Ops[0].second);
942     if (Ops.size() == 1 && Op0.isDef()) {
943       MakeSubstitution();
944     } else if (Ops.size() == 2 && Op0.isDef() && MI->getOperand(1).isTied() &&
945                Op0.getReg() == MI->getOperand(1).getReg()) {
946       MakeSubstitution();
947     }
948   } else if (MI->peekDebugInstrNum()) {
949     // This is a debug-labelled instruction, but the operand being folded isn't
950     // at operand zero. Most likely this means it's a load being folded in.
951     // Substitute any register defs from operand zero up to the one being
952     // folded -- past that point, we don't know what the new operand indexes
953     // will be.
954     MF.substituteDebugValuesForInst(*MI, *FoldMI, Ops[0].second);
955   }
956 
957   MI->eraseFromParent();
958 
959   // Insert any new instructions other than FoldMI into the LIS maps.
960   assert(!MIS.empty() && "Unexpected empty span of instructions!");
961   for (MachineInstr &MI : MIS)
962     if (&MI != FoldMI)
963       LIS.InsertMachineInstrInMaps(MI);
964 
965   // TII.foldMemoryOperand may have left some implicit operands on the
966   // instruction.  Strip them.
967   if (ImpReg)
968     for (unsigned i = FoldMI->getNumOperands(); i; --i) {
969       MachineOperand &MO = FoldMI->getOperand(i - 1);
970       if (!MO.isReg() || !MO.isImplicit())
971         break;
972       if (MO.getReg() == ImpReg)
973         FoldMI->RemoveOperand(i - 1);
974     }
975 
976   LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
977                                                 "folded"));
978 
979   if (!WasCopy)
980     ++NumFolded;
981   else if (Ops.front().second == 0) {
982     ++NumSpills;
983     // If there is only 1 store instruction is required for spill, add it
984     // to mergeable list. In X86 AMX, 2 intructions are required to store.
985     // We disable the merge for this case.
986     if (std::distance(MIS.begin(), MIS.end()) <= 1)
987       HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original);
988   } else
989     ++NumReloads;
990   return true;
991 }
992 
993 void InlineSpiller::insertReload(Register NewVReg,
994                                  SlotIndex Idx,
995                                  MachineBasicBlock::iterator MI) {
996   MachineBasicBlock &MBB = *MI->getParent();
997 
998   MachineInstrSpan MIS(MI, &MBB);
999   TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
1000                            MRI.getRegClass(NewVReg), &TRI);
1001 
1002   LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
1003 
1004   LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
1005                                                 NewVReg));
1006   ++NumReloads;
1007 }
1008 
1009 /// Check if \p Def fully defines a VReg with an undefined value.
1010 /// If that's the case, that means the value of VReg is actually
1011 /// not relevant.
1012 static bool isRealSpill(const MachineInstr &Def) {
1013   if (!Def.isImplicitDef())
1014     return true;
1015   assert(Def.getNumOperands() == 1 &&
1016          "Implicit def with more than one definition");
1017   // We can say that the VReg defined by Def is undef, only if it is
1018   // fully defined by Def. Otherwise, some of the lanes may not be
1019   // undef and the value of the VReg matters.
1020   return Def.getOperand(0).getSubReg();
1021 }
1022 
1023 /// insertSpill - Insert a spill of NewVReg after MI.
1024 void InlineSpiller::insertSpill(Register NewVReg, bool isKill,
1025                                  MachineBasicBlock::iterator MI) {
1026   // Spill are not terminators, so inserting spills after terminators will
1027   // violate invariants in MachineVerifier.
1028   assert(!MI->isTerminator() && "Inserting a spill after a terminator");
1029   MachineBasicBlock &MBB = *MI->getParent();
1030 
1031   MachineInstrSpan MIS(MI, &MBB);
1032   MachineBasicBlock::iterator SpillBefore = std::next(MI);
1033   bool IsRealSpill = isRealSpill(*MI);
1034 
1035   if (IsRealSpill)
1036     TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, isKill, StackSlot,
1037                             MRI.getRegClass(NewVReg), &TRI);
1038   else
1039     // Don't spill undef value.
1040     // Anything works for undef, in particular keeping the memory
1041     // uninitialized is a viable option and it saves code size and
1042     // run time.
1043     BuildMI(MBB, SpillBefore, MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
1044         .addReg(NewVReg, getKillRegState(isKill));
1045 
1046   MachineBasicBlock::iterator Spill = std::next(MI);
1047   LIS.InsertMachineInstrRangeInMaps(Spill, MIS.end());
1048   for (const MachineInstr &MI : make_range(Spill, MIS.end()))
1049     getVDefInterval(MI, LIS);
1050 
1051   LLVM_DEBUG(
1052       dumpMachineInstrRangeWithSlotIndex(Spill, MIS.end(), LIS, "spill"));
1053   ++NumSpills;
1054   // If there is only 1 store instruction is required for spill, add it
1055   // to mergeable list. In X86 AMX, 2 intructions are required to store.
1056   // We disable the merge for this case.
1057   if (IsRealSpill && std::distance(Spill, MIS.end()) <= 1)
1058     HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
1059 }
1060 
1061 /// spillAroundUses - insert spill code around each use of Reg.
1062 void InlineSpiller::spillAroundUses(Register Reg) {
1063   LLVM_DEBUG(dbgs() << "spillAroundUses " << printReg(Reg) << '\n');
1064   LiveInterval &OldLI = LIS.getInterval(Reg);
1065 
1066   // Iterate over instructions using Reg.
1067   for (MachineInstr &MI : llvm::make_early_inc_range(MRI.reg_bundles(Reg))) {
1068     // Debug values are not allowed to affect codegen.
1069     if (MI.isDebugValue()) {
1070       // Modify DBG_VALUE now that the value is in a spill slot.
1071       MachineBasicBlock *MBB = MI.getParent();
1072       LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:\t" << MI);
1073       buildDbgValueForSpill(*MBB, &MI, MI, StackSlot, Reg);
1074       MBB->erase(MI);
1075       continue;
1076     }
1077 
1078     assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "
1079            "instruction that isn't a DBG_VALUE");
1080 
1081     // Ignore copies to/from snippets. We'll delete them.
1082     if (SnippetCopies.count(&MI))
1083       continue;
1084 
1085     // Stack slot accesses may coalesce away.
1086     if (coalesceStackAccess(&MI, Reg))
1087       continue;
1088 
1089     // Analyze instruction.
1090     SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
1091     VirtRegInfo RI = AnalyzeVirtRegInBundle(MI, Reg, &Ops);
1092 
1093     // Find the slot index where this instruction reads and writes OldLI.
1094     // This is usually the def slot, except for tied early clobbers.
1095     SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1096     if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1097       if (SlotIndex::isSameInstr(Idx, VNI->def))
1098         Idx = VNI->def;
1099 
1100     // Check for a sibling copy.
1101     Register SibReg = isFullCopyOf(MI, Reg);
1102     if (SibReg && isSibling(SibReg)) {
1103       // This may actually be a copy between snippets.
1104       if (isRegToSpill(SibReg)) {
1105         LLVM_DEBUG(dbgs() << "Found new snippet copy: " << MI);
1106         SnippetCopies.insert(&MI);
1107         continue;
1108       }
1109       if (RI.Writes) {
1110         if (hoistSpillInsideBB(OldLI, MI)) {
1111           // This COPY is now dead, the value is already in the stack slot.
1112           MI.getOperand(0).setIsDead();
1113           DeadDefs.push_back(&MI);
1114           continue;
1115         }
1116       } else {
1117         // This is a reload for a sib-reg copy. Drop spills downstream.
1118         LiveInterval &SibLI = LIS.getInterval(SibReg);
1119         eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1120         // The COPY will fold to a reload below.
1121       }
1122     }
1123 
1124     // Attempt to fold memory ops.
1125     if (foldMemoryOperand(Ops))
1126       continue;
1127 
1128     // Create a new virtual register for spill/fill.
1129     // FIXME: Infer regclass from instruction alone.
1130     Register NewVReg = Edit->createFrom(Reg);
1131 
1132     if (RI.Reads)
1133       insertReload(NewVReg, Idx, &MI);
1134 
1135     // Rewrite instruction operands.
1136     bool hasLiveDef = false;
1137     for (const auto &OpPair : Ops) {
1138       MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
1139       MO.setReg(NewVReg);
1140       if (MO.isUse()) {
1141         if (!OpPair.first->isRegTiedToDefOperand(OpPair.second))
1142           MO.setIsKill();
1143       } else {
1144         if (!MO.isDead())
1145           hasLiveDef = true;
1146       }
1147     }
1148     LLVM_DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << MI << '\n');
1149 
1150     // FIXME: Use a second vreg if instruction has no tied ops.
1151     if (RI.Writes)
1152       if (hasLiveDef)
1153         insertSpill(NewVReg, true, &MI);
1154   }
1155 }
1156 
1157 /// spillAll - Spill all registers remaining after rematerialization.
1158 void InlineSpiller::spillAll() {
1159   // Update LiveStacks now that we are committed to spilling.
1160   if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1161     StackSlot = VRM.assignVirt2StackSlot(Original);
1162     StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1163     StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1164   } else
1165     StackInt = &LSS.getInterval(StackSlot);
1166 
1167   if (Original != Edit->getReg())
1168     VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1169 
1170   assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1171   for (Register Reg : RegsToSpill)
1172     StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
1173                                      StackInt->getValNumInfo(0));
1174   LLVM_DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1175 
1176   // Spill around uses of all RegsToSpill.
1177   for (Register Reg : RegsToSpill)
1178     spillAroundUses(Reg);
1179 
1180   // Hoisted spills may cause dead code.
1181   if (!DeadDefs.empty()) {
1182     LLVM_DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1183     Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
1184   }
1185 
1186   // Finally delete the SnippetCopies.
1187   for (Register Reg : RegsToSpill) {
1188     for (MachineInstr &MI :
1189          llvm::make_early_inc_range(MRI.reg_instructions(Reg))) {
1190       assert(SnippetCopies.count(&MI) && "Remaining use wasn't a snippet copy");
1191       // FIXME: Do this with a LiveRangeEdit callback.
1192       LIS.RemoveMachineInstrFromMaps(MI);
1193       MI.eraseFromParent();
1194     }
1195   }
1196 
1197   // Delete all spilled registers.
1198   for (Register Reg : RegsToSpill)
1199     Edit->eraseVirtReg(Reg);
1200 }
1201 
1202 void InlineSpiller::spill(LiveRangeEdit &edit) {
1203   ++NumSpilledRanges;
1204   Edit = &edit;
1205   assert(!Register::isStackSlot(edit.getReg()) &&
1206          "Trying to spill a stack slot.");
1207   // Share a stack slot among all descendants of Original.
1208   Original = VRM.getOriginal(edit.getReg());
1209   StackSlot = VRM.getStackSlot(Original);
1210   StackInt = nullptr;
1211 
1212   LLVM_DEBUG(dbgs() << "Inline spilling "
1213                     << TRI.getRegClassName(MRI.getRegClass(edit.getReg()))
1214                     << ':' << edit.getParent() << "\nFrom original "
1215                     << printReg(Original) << '\n');
1216   assert(edit.getParent().isSpillable() &&
1217          "Attempting to spill already spilled value.");
1218   assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1219 
1220   collectRegsToSpill();
1221   reMaterializeAll();
1222 
1223   // Remat may handle everything.
1224   if (!RegsToSpill.empty())
1225     spillAll();
1226 
1227   Edit->calculateRegClassAndHint(MF, VRAI);
1228 }
1229 
1230 /// Optimizations after all the reg selections and spills are done.
1231 void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
1232 
1233 /// When a spill is inserted, add the spill to MergeableSpills map.
1234 void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
1235                                             unsigned Original) {
1236   BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
1237   LiveInterval &OrigLI = LIS.getInterval(Original);
1238   // save a copy of LiveInterval in StackSlotToOrigLI because the original
1239   // LiveInterval may be cleared after all its references are spilled.
1240   if (StackSlotToOrigLI.find(StackSlot) == StackSlotToOrigLI.end()) {
1241     auto LI = std::make_unique<LiveInterval>(OrigLI.reg(), OrigLI.weight());
1242     LI->assign(OrigLI, Allocator);
1243     StackSlotToOrigLI[StackSlot] = std::move(LI);
1244   }
1245   SlotIndex Idx = LIS.getInstructionIndex(Spill);
1246   VNInfo *OrigVNI = StackSlotToOrigLI[StackSlot]->getVNInfoAt(Idx.getRegSlot());
1247   std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1248   MergeableSpills[MIdx].insert(&Spill);
1249 }
1250 
1251 /// When a spill is removed, remove the spill from MergeableSpills map.
1252 /// Return true if the spill is removed successfully.
1253 bool HoistSpillHelper::rmFromMergeableSpills(MachineInstr &Spill,
1254                                              int StackSlot) {
1255   auto It = StackSlotToOrigLI.find(StackSlot);
1256   if (It == StackSlotToOrigLI.end())
1257     return false;
1258   SlotIndex Idx = LIS.getInstructionIndex(Spill);
1259   VNInfo *OrigVNI = It->second->getVNInfoAt(Idx.getRegSlot());
1260   std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1261   return MergeableSpills[MIdx].erase(&Spill);
1262 }
1263 
1264 /// Check BB to see if it is a possible target BB to place a hoisted spill,
1265 /// i.e., there should be a living sibling of OrigReg at the insert point.
1266 bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
1267                                      MachineBasicBlock &BB, Register &LiveReg) {
1268   SlotIndex Idx = IPA.getLastInsertPoint(OrigLI, BB);
1269   // The original def could be after the last insert point in the root block,
1270   // we can't hoist to here.
1271   if (Idx < OrigVNI.def) {
1272     // TODO: We could be better here. If LI is not alive in landing pad
1273     // we could hoist spill after LIP.
1274     LLVM_DEBUG(dbgs() << "can't spill in root block - def after LIP\n");
1275     return false;
1276   }
1277   Register OrigReg = OrigLI.reg();
1278   SmallSetVector<Register, 16> &Siblings = Virt2SiblingsMap[OrigReg];
1279   assert(OrigLI.getVNInfoAt(Idx) == &OrigVNI && "Unexpected VNI");
1280 
1281   for (const Register &SibReg : Siblings) {
1282     LiveInterval &LI = LIS.getInterval(SibReg);
1283     VNInfo *VNI = LI.getVNInfoAt(Idx);
1284     if (VNI) {
1285       LiveReg = SibReg;
1286       return true;
1287     }
1288   }
1289   return false;
1290 }
1291 
1292 /// Remove redundant spills in the same BB. Save those redundant spills in
1293 /// SpillsToRm, and save the spill to keep and its BB in SpillBBToSpill map.
1294 void HoistSpillHelper::rmRedundantSpills(
1295     SmallPtrSet<MachineInstr *, 16> &Spills,
1296     SmallVectorImpl<MachineInstr *> &SpillsToRm,
1297     DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
1298   // For each spill saw, check SpillBBToSpill[] and see if its BB already has
1299   // another spill inside. If a BB contains more than one spill, only keep the
1300   // earlier spill with smaller SlotIndex.
1301   for (const auto CurrentSpill : Spills) {
1302     MachineBasicBlock *Block = CurrentSpill->getParent();
1303     MachineDomTreeNode *Node = MDT.getBase().getNode(Block);
1304     MachineInstr *PrevSpill = SpillBBToSpill[Node];
1305     if (PrevSpill) {
1306       SlotIndex PIdx = LIS.getInstructionIndex(*PrevSpill);
1307       SlotIndex CIdx = LIS.getInstructionIndex(*CurrentSpill);
1308       MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill;
1309       MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill;
1310       SpillsToRm.push_back(SpillToRm);
1311       SpillBBToSpill[MDT.getBase().getNode(Block)] = SpillToKeep;
1312     } else {
1313       SpillBBToSpill[MDT.getBase().getNode(Block)] = CurrentSpill;
1314     }
1315   }
1316   for (const auto SpillToRm : SpillsToRm)
1317     Spills.erase(SpillToRm);
1318 }
1319 
1320 /// Starting from \p Root find a top-down traversal order of the dominator
1321 /// tree to visit all basic blocks containing the elements of \p Spills.
1322 /// Redundant spills will be found and put into \p SpillsToRm at the same
1323 /// time. \p SpillBBToSpill will be populated as part of the process and
1324 /// maps a basic block to the first store occurring in the basic block.
1325 /// \post SpillsToRm.union(Spills\@post) == Spills\@pre
1326 void HoistSpillHelper::getVisitOrders(
1327     MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
1328     SmallVectorImpl<MachineDomTreeNode *> &Orders,
1329     SmallVectorImpl<MachineInstr *> &SpillsToRm,
1330     DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
1331     DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
1332   // The set contains all the possible BB nodes to which we may hoist
1333   // original spills.
1334   SmallPtrSet<MachineDomTreeNode *, 8> WorkSet;
1335   // Save the BB nodes on the path from the first BB node containing
1336   // non-redundant spill to the Root node.
1337   SmallPtrSet<MachineDomTreeNode *, 8> NodesOnPath;
1338   // All the spills to be hoisted must originate from a single def instruction
1339   // to the OrigReg. It means the def instruction should dominate all the spills
1340   // to be hoisted. We choose the BB where the def instruction is located as
1341   // the Root.
1342   MachineDomTreeNode *RootIDomNode = MDT[Root]->getIDom();
1343   // For every node on the dominator tree with spill, walk up on the dominator
1344   // tree towards the Root node until it is reached. If there is other node
1345   // containing spill in the middle of the path, the previous spill saw will
1346   // be redundant and the node containing it will be removed. All the nodes on
1347   // the path starting from the first node with non-redundant spill to the Root
1348   // node will be added to the WorkSet, which will contain all the possible
1349   // locations where spills may be hoisted to after the loop below is done.
1350   for (const auto Spill : Spills) {
1351     MachineBasicBlock *Block = Spill->getParent();
1352     MachineDomTreeNode *Node = MDT[Block];
1353     MachineInstr *SpillToRm = nullptr;
1354     while (Node != RootIDomNode) {
1355       // If Node dominates Block, and it already contains a spill, the spill in
1356       // Block will be redundant.
1357       if (Node != MDT[Block] && SpillBBToSpill[Node]) {
1358         SpillToRm = SpillBBToSpill[MDT[Block]];
1359         break;
1360         /// If we see the Node already in WorkSet, the path from the Node to
1361         /// the Root node must already be traversed by another spill.
1362         /// Then no need to repeat.
1363       } else if (WorkSet.count(Node)) {
1364         break;
1365       } else {
1366         NodesOnPath.insert(Node);
1367       }
1368       Node = Node->getIDom();
1369     }
1370     if (SpillToRm) {
1371       SpillsToRm.push_back(SpillToRm);
1372     } else {
1373       // Add a BB containing the original spills to SpillsToKeep -- i.e.,
1374       // set the initial status before hoisting start. The value of BBs
1375       // containing original spills is set to 0, in order to descriminate
1376       // with BBs containing hoisted spills which will be inserted to
1377       // SpillsToKeep later during hoisting.
1378       SpillsToKeep[MDT[Block]] = 0;
1379       WorkSet.insert(NodesOnPath.begin(), NodesOnPath.end());
1380     }
1381     NodesOnPath.clear();
1382   }
1383 
1384   // Sort the nodes in WorkSet in top-down order and save the nodes
1385   // in Orders. Orders will be used for hoisting in runHoistSpills.
1386   unsigned idx = 0;
1387   Orders.push_back(MDT.getBase().getNode(Root));
1388   do {
1389     MachineDomTreeNode *Node = Orders[idx++];
1390     for (MachineDomTreeNode *Child : Node->children()) {
1391       if (WorkSet.count(Child))
1392         Orders.push_back(Child);
1393     }
1394   } while (idx != Orders.size());
1395   assert(Orders.size() == WorkSet.size() &&
1396          "Orders have different size with WorkSet");
1397 
1398 #ifndef NDEBUG
1399   LLVM_DEBUG(dbgs() << "Orders size is " << Orders.size() << "\n");
1400   SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
1401   for (; RIt != Orders.rend(); RIt++)
1402     LLVM_DEBUG(dbgs() << "BB" << (*RIt)->getBlock()->getNumber() << ",");
1403   LLVM_DEBUG(dbgs() << "\n");
1404 #endif
1405 }
1406 
1407 /// Try to hoist spills according to BB hotness. The spills to removed will
1408 /// be saved in \p SpillsToRm. The spills to be inserted will be saved in
1409 /// \p SpillsToIns.
1410 void HoistSpillHelper::runHoistSpills(
1411     LiveInterval &OrigLI, VNInfo &OrigVNI,
1412     SmallPtrSet<MachineInstr *, 16> &Spills,
1413     SmallVectorImpl<MachineInstr *> &SpillsToRm,
1414     DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns) {
1415   // Visit order of dominator tree nodes.
1416   SmallVector<MachineDomTreeNode *, 32> Orders;
1417   // SpillsToKeep contains all the nodes where spills are to be inserted
1418   // during hoisting. If the spill to be inserted is an original spill
1419   // (not a hoisted one), the value of the map entry is 0. If the spill
1420   // is a hoisted spill, the value of the map entry is the VReg to be used
1421   // as the source of the spill.
1422   DenseMap<MachineDomTreeNode *, unsigned> SpillsToKeep;
1423   // Map from BB to the first spill inside of it.
1424   DenseMap<MachineDomTreeNode *, MachineInstr *> SpillBBToSpill;
1425 
1426   rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill);
1427 
1428   MachineBasicBlock *Root = LIS.getMBBFromIndex(OrigVNI.def);
1429   getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep,
1430                  SpillBBToSpill);
1431 
1432   // SpillsInSubTreeMap keeps the map from a dom tree node to a pair of
1433   // nodes set and the cost of all the spills inside those nodes.
1434   // The nodes set are the locations where spills are to be inserted
1435   // in the subtree of current node.
1436   using NodesCostPair =
1437       std::pair<SmallPtrSet<MachineDomTreeNode *, 16>, BlockFrequency>;
1438   DenseMap<MachineDomTreeNode *, NodesCostPair> SpillsInSubTreeMap;
1439 
1440   // Iterate Orders set in reverse order, which will be a bottom-up order
1441   // in the dominator tree. Once we visit a dom tree node, we know its
1442   // children have already been visited and the spill locations in the
1443   // subtrees of all the children have been determined.
1444   SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
1445   for (; RIt != Orders.rend(); RIt++) {
1446     MachineBasicBlock *Block = (*RIt)->getBlock();
1447 
1448     // If Block contains an original spill, simply continue.
1449     if (SpillsToKeep.find(*RIt) != SpillsToKeep.end() && !SpillsToKeep[*RIt]) {
1450       SpillsInSubTreeMap[*RIt].first.insert(*RIt);
1451       // SpillsInSubTreeMap[*RIt].second contains the cost of spill.
1452       SpillsInSubTreeMap[*RIt].second = MBFI.getBlockFreq(Block);
1453       continue;
1454     }
1455 
1456     // Collect spills in subtree of current node (*RIt) to
1457     // SpillsInSubTreeMap[*RIt].first.
1458     for (MachineDomTreeNode *Child : (*RIt)->children()) {
1459       if (SpillsInSubTreeMap.find(Child) == SpillsInSubTreeMap.end())
1460         continue;
1461       // The stmt "SpillsInSubTree = SpillsInSubTreeMap[*RIt].first" below
1462       // should be placed before getting the begin and end iterators of
1463       // SpillsInSubTreeMap[Child].first, or else the iterators may be
1464       // invalidated when SpillsInSubTreeMap[*RIt] is seen the first time
1465       // and the map grows and then the original buckets in the map are moved.
1466       SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
1467           SpillsInSubTreeMap[*RIt].first;
1468       BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
1469       SubTreeCost += SpillsInSubTreeMap[Child].second;
1470       auto BI = SpillsInSubTreeMap[Child].first.begin();
1471       auto EI = SpillsInSubTreeMap[Child].first.end();
1472       SpillsInSubTree.insert(BI, EI);
1473       SpillsInSubTreeMap.erase(Child);
1474     }
1475 
1476     SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
1477           SpillsInSubTreeMap[*RIt].first;
1478     BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
1479     // No spills in subtree, simply continue.
1480     if (SpillsInSubTree.empty())
1481       continue;
1482 
1483     // Check whether Block is a possible candidate to insert spill.
1484     Register LiveReg;
1485     if (!isSpillCandBB(OrigLI, OrigVNI, *Block, LiveReg))
1486       continue;
1487 
1488     // If there are multiple spills that could be merged, bias a little
1489     // to hoist the spill.
1490     BranchProbability MarginProb = (SpillsInSubTree.size() > 1)
1491                                        ? BranchProbability(9, 10)
1492                                        : BranchProbability(1, 1);
1493     if (SubTreeCost > MBFI.getBlockFreq(Block) * MarginProb) {
1494       // Hoist: Move spills to current Block.
1495       for (const auto SpillBB : SpillsInSubTree) {
1496         // When SpillBB is a BB contains original spill, insert the spill
1497         // to SpillsToRm.
1498         if (SpillsToKeep.find(SpillBB) != SpillsToKeep.end() &&
1499             !SpillsToKeep[SpillBB]) {
1500           MachineInstr *SpillToRm = SpillBBToSpill[SpillBB];
1501           SpillsToRm.push_back(SpillToRm);
1502         }
1503         // SpillBB will not contain spill anymore, remove it from SpillsToKeep.
1504         SpillsToKeep.erase(SpillBB);
1505       }
1506       // Current Block is the BB containing the new hoisted spill. Add it to
1507       // SpillsToKeep. LiveReg is the source of the new spill.
1508       SpillsToKeep[*RIt] = LiveReg;
1509       LLVM_DEBUG({
1510         dbgs() << "spills in BB: ";
1511         for (const auto Rspill : SpillsInSubTree)
1512           dbgs() << Rspill->getBlock()->getNumber() << " ";
1513         dbgs() << "were promoted to BB" << (*RIt)->getBlock()->getNumber()
1514                << "\n";
1515       });
1516       SpillsInSubTree.clear();
1517       SpillsInSubTree.insert(*RIt);
1518       SubTreeCost = MBFI.getBlockFreq(Block);
1519     }
1520   }
1521   // For spills in SpillsToKeep with LiveReg set (i.e., not original spill),
1522   // save them to SpillsToIns.
1523   for (const auto &Ent : SpillsToKeep) {
1524     if (Ent.second)
1525       SpillsToIns[Ent.first->getBlock()] = Ent.second;
1526   }
1527 }
1528 
1529 /// For spills with equal values, remove redundant spills and hoist those left
1530 /// to less hot spots.
1531 ///
1532 /// Spills with equal values will be collected into the same set in
1533 /// MergeableSpills when spill is inserted. These equal spills are originated
1534 /// from the same defining instruction and are dominated by the instruction.
1535 /// Before hoisting all the equal spills, redundant spills inside in the same
1536 /// BB are first marked to be deleted. Then starting from the spills left, walk
1537 /// up on the dominator tree towards the Root node where the define instruction
1538 /// is located, mark the dominated spills to be deleted along the way and
1539 /// collect the BB nodes on the path from non-dominated spills to the define
1540 /// instruction into a WorkSet. The nodes in WorkSet are the candidate places
1541 /// where we are considering to hoist the spills. We iterate the WorkSet in
1542 /// bottom-up order, and for each node, we will decide whether to hoist spills
1543 /// inside its subtree to that node. In this way, we can get benefit locally
1544 /// even if hoisting all the equal spills to one cold place is impossible.
1545 void HoistSpillHelper::hoistAllSpills() {
1546   SmallVector<Register, 4> NewVRegs;
1547   LiveRangeEdit Edit(nullptr, NewVRegs, MF, LIS, &VRM, this);
1548 
1549   for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
1550     Register Reg = Register::index2VirtReg(i);
1551     Register Original = VRM.getPreSplitReg(Reg);
1552     if (!MRI.def_empty(Reg))
1553       Virt2SiblingsMap[Original].insert(Reg);
1554   }
1555 
1556   // Each entry in MergeableSpills contains a spill set with equal values.
1557   for (auto &Ent : MergeableSpills) {
1558     int Slot = Ent.first.first;
1559     LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
1560     VNInfo *OrigVNI = Ent.first.second;
1561     SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
1562     if (Ent.second.empty())
1563       continue;
1564 
1565     LLVM_DEBUG({
1566       dbgs() << "\nFor Slot" << Slot << " and VN" << OrigVNI->id << ":\n"
1567              << "Equal spills in BB: ";
1568       for (const auto spill : EqValSpills)
1569         dbgs() << spill->getParent()->getNumber() << " ";
1570       dbgs() << "\n";
1571     });
1572 
1573     // SpillsToRm is the spill set to be removed from EqValSpills.
1574     SmallVector<MachineInstr *, 16> SpillsToRm;
1575     // SpillsToIns is the spill set to be newly inserted after hoisting.
1576     DenseMap<MachineBasicBlock *, unsigned> SpillsToIns;
1577 
1578     runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns);
1579 
1580     LLVM_DEBUG({
1581       dbgs() << "Finally inserted spills in BB: ";
1582       for (const auto &Ispill : SpillsToIns)
1583         dbgs() << Ispill.first->getNumber() << " ";
1584       dbgs() << "\nFinally removed spills in BB: ";
1585       for (const auto Rspill : SpillsToRm)
1586         dbgs() << Rspill->getParent()->getNumber() << " ";
1587       dbgs() << "\n";
1588     });
1589 
1590     // Stack live range update.
1591     LiveInterval &StackIntvl = LSS.getInterval(Slot);
1592     if (!SpillsToIns.empty() || !SpillsToRm.empty())
1593       StackIntvl.MergeValueInAsValue(OrigLI, OrigVNI,
1594                                      StackIntvl.getValNumInfo(0));
1595 
1596     // Insert hoisted spills.
1597     for (auto const &Insert : SpillsToIns) {
1598       MachineBasicBlock *BB = Insert.first;
1599       Register LiveReg = Insert.second;
1600       MachineBasicBlock::iterator MII = IPA.getLastInsertPointIter(OrigLI, *BB);
1601       MachineInstrSpan MIS(MII, BB);
1602       TII.storeRegToStackSlot(*BB, MII, LiveReg, false, Slot,
1603                               MRI.getRegClass(LiveReg), &TRI);
1604       LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MII);
1605       for (const MachineInstr &MI : make_range(MIS.begin(), MII))
1606         getVDefInterval(MI, LIS);
1607       ++NumSpills;
1608     }
1609 
1610     // Remove redundant spills or change them to dead instructions.
1611     NumSpills -= SpillsToRm.size();
1612     for (auto const RMEnt : SpillsToRm) {
1613       RMEnt->setDesc(TII.get(TargetOpcode::KILL));
1614       for (unsigned i = RMEnt->getNumOperands(); i; --i) {
1615         MachineOperand &MO = RMEnt->getOperand(i - 1);
1616         if (MO.isReg() && MO.isImplicit() && MO.isDef() && !MO.isDead())
1617           RMEnt->RemoveOperand(i - 1);
1618       }
1619     }
1620     Edit.eliminateDeadDefs(SpillsToRm, None, AA);
1621   }
1622 }
1623 
1624 /// For VirtReg clone, the \p New register should have the same physreg or
1625 /// stackslot as the \p old register.
1626 void HoistSpillHelper::LRE_DidCloneVirtReg(Register New, Register Old) {
1627   if (VRM.hasPhys(Old))
1628     VRM.assignVirt2Phys(New, VRM.getPhys(Old));
1629   else if (VRM.getStackSlot(Old) != VirtRegMap::NO_STACK_SLOT)
1630     VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old));
1631   else
1632     llvm_unreachable("VReg should be assigned either physreg or stackslot");
1633   if (VRM.hasShape(Old))
1634     VRM.assignVirt2Shape(New, VRM.getShape(Old));
1635 }
1636