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