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