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