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 "AllocationOrder.h"
15#include "SplitKit.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/MapVector.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
46#include "llvm/Config/llvm-config.h"
51#include "llvm/Support/Debug.h"
54#include <cassert>
55#include <iterator>
56#include <tuple>
57#include <utility>
58
59using namespace llvm;
60
61#define DEBUG_TYPE "regalloc"
62
63STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
64STATISTIC(NumSnippets, "Number of spilled snippets");
65STATISTIC(NumSpills, "Number of spills inserted");
66STATISTIC(NumSpillsRemoved, "Number of spills removed");
67STATISTIC(NumReloads, "Number of reloads inserted");
68STATISTIC(NumReloadsRemoved, "Number of reloads removed");
69STATISTIC(NumFolded, "Number of folded stack accesses");
70STATISTIC(NumFoldedLoads, "Number of folded loads");
71STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
72
73static cl::opt<bool>
74RestrictStatepointRemat("restrict-statepoint-remat",
75 cl::init(false), cl::Hidden,
76 cl::desc("Restrict remat for statepoint operands"));
77
78namespace {
79class HoistSpillHelper : private LiveRangeEdit::Delegate {
81 LiveIntervals &LIS;
82 LiveStacks &LSS;
84 VirtRegMap &VRM;
86 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 TRI(*mf.getSubtarget().getRegisterInfo()), MBFI(Analyses.MBFI),
137 Matrix(matrix), IPA(LIS, mf.getNumBlockIDs()) {}
138
139 void addToMergeableSpills(MachineInstr &Spill, int StackSlot,
140 Register Original);
141 bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
142 void hoistAllSpills();
143 void LRE_WillShrinkVirtReg(Register) override;
144 bool LRE_CanEraseVirtReg(Register) override;
145 void LRE_DidCloneVirtReg(Register, Register) override;
146
147private:
148 // Vregs unassigned from the matrix during LRE_WillShrinkVirtReg, pending
149 // re-assignment after the interval is shrunk/split.
150 DenseMap<Register, MCRegister> PendingReassignments;
151};
152
153class InlineSpiller : public Spiller {
154 MachineFunction &MF;
155 LiveIntervals &LIS;
156 LiveStacks &LSS;
157 VirtRegMap &VRM;
158 MachineRegisterInfo &MRI;
159 const TargetInstrInfo &TII;
160 const TargetRegisterInfo &TRI;
161 LiveRegMatrix *Matrix = nullptr;
162
163 // Variables that are valid during spill(), but used by multiple methods.
164 LiveRangeEdit *Edit = nullptr;
165 LiveInterval *StackInt = nullptr;
166 int StackSlot;
167 Register Original;
168 AllocationOrder *Order = nullptr;
169
170 // All registers to spill to StackSlot, including the main register.
171 SmallVector<Register, 8> RegsToSpill;
172
173 // All registers that were replaced by the spiller through some other method,
174 // e.g. rematerialization.
175 SmallVector<Register, 8> RegsReplaced;
176
177 // All COPY instructions to/from snippets.
178 // They are ignored since both operands refer to the same stack slot.
179 // For bundled copies, this will only include the first header copy.
180 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
181
182 // Values that failed to remat at some point.
183 SmallPtrSet<VNInfo*, 8> UsedValues;
184
185 // Dead defs generated during spilling.
186 SmallVector<MachineInstr*, 8> DeadDefs;
187
188 // Object records spills information and does the hoisting.
189 HoistSpillHelper HSpiller;
190
191 // Live range weight calculator.
192 VirtRegAuxInfo &VRAI;
193
194 ~InlineSpiller() override = default;
195
196public:
197 InlineSpiller(const Spiller::RequiredAnalyses &Analyses, MachineFunction &MF,
198 VirtRegMap &VRM, VirtRegAuxInfo &VRAI, LiveRegMatrix *Matrix)
199 : MF(MF), LIS(Analyses.LIS), LSS(Analyses.LSS), VRM(VRM),
200 MRI(MF.getRegInfo()), TII(*MF.getSubtarget().getInstrInfo()),
201 TRI(*MF.getSubtarget().getRegisterInfo()), Matrix(Matrix),
202 HSpiller(Analyses, MF, VRM, Matrix), VRAI(VRAI) {}
203
204 void spill(LiveRangeEdit &, AllocationOrder *Order = nullptr) override;
205 ArrayRef<Register> getSpilledRegs() override { return RegsToSpill; }
206 ArrayRef<Register> getReplacedRegs() override { return RegsReplaced; }
207 void postOptimization() override;
208
209private:
210 bool isSnippet(const LiveInterval &SnipLI);
211 void collectRegsToSpill();
212
213 bool isRegToSpill(Register Reg) { return is_contained(RegsToSpill, Reg); }
214
215 bool isSibling(Register Reg);
216 bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
217 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
218
219 void markValueUsed(LiveInterval*, VNInfo*);
220 bool canGuaranteeAssignmentAfterRemat(Register VReg, MachineInstr &MI);
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, bool isKill, 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,
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.
263 const TargetInstrInfo &TII) {
264 if (!TII.isCopyInstr(MI))
265 return Register();
266
267 const MachineOperand &DstOp = MI.getOperand(0);
268 const MachineOperand &SrcOp = MI.getOperand(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.
282 const TargetInstrInfo &TII) {
283 if (!FirstMI.isBundled())
284 return isCopyOf(FirstMI, Reg, TII);
285
286 assert(!FirstMI.isBundledWithPred() && FirstMI.isBundledWithSucc() &&
287 "expected to see first instruction in bundle");
288
289 Register SnipReg;
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(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(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(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.
358 RI = MRI.reg_bundle_nodbg_begin(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(MI, Reg, TII))
365 continue;
366
367 // Allow stack slot loads.
368 int FI;
369 if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
370 continue;
371
372 // Allow stack slot stores.
373 if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
374 continue;
375
376 if (StatepointOpers::isFoldableReg(&MI, 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(1, 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(MRI.reg_bundles(Reg))) {
403 Register SnipReg = isCopyOfBundle(MI, Reg, TII);
404 if (!isSibling(SnipReg))
405 continue;
406 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
407 if (!isSnippet(SnipLI))
408 continue;
409 SnippetCopies.insert(&MI);
410 if (isRegToSpill(SnipReg))
411 continue;
412 RegsToSpill.push_back(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(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(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(1).getReg();
450 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
451 VNInfo *SrcVNI = SrcLI.getVNInfoAt(Idx);
452 LiveQueryResult SrcQ = SrcLI.Query(Idx);
453 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(SrcVNI->def);
454 if (DefMBB != CopyMI.getParent() || !SrcQ.isKill())
455 return false;
456
457 MachineBasicBlock *MBB = DefMBB;
459 if (SrcVNI->isPHIDef())
460 MII = MBB->SkipPHIsLabelsAndDebug(MBB->begin(), SrcReg);
461 else {
462 MachineInstr *DefMI = LIS.getInstructionFromIndex(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(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)
478 : LIS.getInstructionIndex(*MII).getBaseIndex();
479 if (SrcQ.endPoint() < InsertIdx &&
480 Matrix->checkInterference(SrcQ.endPoint(), InsertIdx,
481 VRM.getPhys(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(Original);
490 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
491 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(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(SrcLI, SrcVNI);
498
499 MachineInstrSpan MIS(MII, MBB);
500 // Insert spill without kill flag immediately after def.
501 TII.storeRegToStackSlot(*MBB, MII, SrcReg, false, StackSlot,
502 MRI.getRegClass(SrcReg), Register());
503 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MII);
504 for (const MachineInstr &MI : make_range(MIS.begin(), 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(*MII).getRegSlot(true);
514 SrcLI.extendInBlock(LIS.getMBBStartIdx(MBB), 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 intructions are required to store.
519 // We disable the merge for this case.
520 if (MIS.begin() == MII)
521 HSpiller.addToMergeableSpills(*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");
531 WorkList.push_back(std::make_pair(&SLI, VNI));
532 assert(StackInt && "No stack slot assigned yet.");
533
534 do {
535 LiveInterval *LI;
536 std::tie(LI, 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(*LI, VNI, StackInt->getValNumInfo(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(MRI.use_nodbg_bundles(Reg))) {
552 if (!MI.mayStore() && !TII.isCopyInstr(MI))
553 continue;
554 SlotIndex Idx = LIS.getInstructionIndex(MI);
555 if (LI->getVNInfoAt(Idx) != VNI)
556 continue;
557
558 // Follow sibling copies down the dominator tree.
559 if (Register DstReg = isCopyOfBundle(MI, Reg, TII)) {
560 if (isSibling(DstReg)) {
561 LiveInterval &DstLI = LIS.getInterval(DstReg);
562 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
563 assert(DstVNI && "Missing defined value");
564 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
565
566 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
567 }
568 continue;
569 }
570
571 // Erase spills.
572 int FI;
573 if (Reg == TII.isStoreToStackSlot(MI, 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(TargetOpcode::KILL));
577 DeadDefs.push_back(&MI);
578 ++NumSpillsRemoved;
579 if (HSpiller.rmFromMergeableSpills(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) {
594 WorkList.push_back(std::make_pair(LI, VNI));
595 do {
596 std::tie(LI, VNI) = WorkList.pop_back_val();
597 if (!UsedValues.insert(VNI).second)
598 continue;
599
600 if (VNI->isPHIDef()) {
601 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
602 for (MachineBasicBlock *P : MBB->predecessors()) {
603 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(P));
604 if (PVNI)
605 WorkList.push_back(std::make_pair(LI, PVNI));
606 }
607 continue;
608 }
609
610 // Follow snippet copies.
611 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
612 if (!SnippetCopies.count(MI))
613 continue;
614 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
615 assert(isRegToSpill(SnipLI.reg()) && "Unexpected register in copy");
616 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
617 assert(SnipVNI && "Snippet undefined before copy");
618 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
619 } while (!WorkList.empty());
620}
621
622bool InlineSpiller::canGuaranteeAssignmentAfterRemat(Register VReg,
623 MachineInstr &MI) {
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 MachineOperand &MO = MI.getOperand(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(MI).getRegSlot(true);
663 SlotIndex PrevIdx = UseIdx.getPrevSlot();
664
665 for (MCPhysReg PhysReg : *Order) {
666 if (!Matrix->checkInterference(PrevIdx, 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
677 VirtRegInfo RI = AnalyzeVirtRegInBundle(MI, VirtReg.reg(), &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(MI).getRegSlot(true);
687 VNInfo *ParentVNI = VirtReg.getVNInfoAt(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(&MI)) {
701 LLVM_DEBUG(dbgs() << "\tskipping remat snippet copy for " << UseIdx << '\t'
702 << MI);
703 return false;
704 }
705
706 LiveInterval &OrigLI = LIS.getInterval(Original);
707 VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
708 assert(OrigVNI && "corrupted sub-interval");
709 MachineInstr *DefMI = LIS.getInstructionFromIndex(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(VirtReg.reg());
718 VNInfo *CurVNI = LI.getVNInfoAt(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(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(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(SrcReg);
741 CurVNI = SrcLI.getVNInfoBefore(CurVNI->def);
742 }
743 if (CurDef && TII.isReMaterializable(*CurDef)) {
744 DefMI = CurDef;
745 LLVM_DEBUG(dbgs() << "\tFound remat possibility through COPY chain: "
746 << *DefMI);
747 }
748 if (!DefMI) {
749 markValueUsed(&VirtReg, 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(&VirtReg, 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(&VirtReg, 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, RM.OrigMI)) {
777 Edit->markRematerialized(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(VirtReg.reg(), MI)) {
785 markValueUsed(&VirtReg, 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(Original);
792
793 // Constrain it to the register class of MI.
794 MRI.constrainRegClass(NewVReg, MRI.getRegClass(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(UseIdx))
802 UsedLanes |= SR.LaneMask;
803 }
804
805 // Finally we can rematerialize OrigMI before MI.
806 SlotIndex DefIdx = Edit->rematerializeAt(*MI.getParent(), MI, NewVReg, RM,
807 TRI, false, 0, 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(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(OpPair.second);
821 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg()) {
822 MO.setReg(NewVReg);
823 MO.setIsKill();
824 }
825 }
826 LLVM_DEBUG(dbgs() << "\t " << UseIdx << '\t' << MI << '\n');
827
828 ++NumRemats;
829 return true;
830}
831
832/// reMaterializeAll - Try to rematerialize as many uses as possible,
833/// and trim the live ranges after.
834void InlineSpiller::reMaterializeAll() {
835 UsedValues.clear();
836
837 // Try to remat before all uses of snippets.
838 bool anyRemat = false;
839 for (Register Reg : RegsToSpill) {
840 LiveInterval &LI = LIS.getInterval(Reg);
841 for (MachineInstr &MI : llvm::make_early_inc_range(MRI.reg_bundles(Reg))) {
842 // Debug values are not allowed to affect codegen.
843 if (MI.isDebugValue())
844 continue;
845
846 assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "
847 "instruction that isn't a DBG_VALUE");
848
849 anyRemat |= reMaterializeFor(LI, MI);
850 }
851 }
852 if (!anyRemat)
853 return;
854
855 // Remove any values that were completely rematted.
856 for (Register Reg : RegsToSpill) {
857 LiveInterval &LI = LIS.getInterval(Reg);
858 for (VNInfo *VNI : LI.vnis()) {
859 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
860 continue;
861 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
862 MI->addRegisterDead(Reg, &TRI);
863 if (!MI->allDefsAreDead())
864 continue;
865 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI);
866 DeadDefs.push_back(MI);
867 // If MI is a bundle header, also try removing copies inside the bundle,
868 // otherwise the verifier would complain "live range continues after dead
869 // def flag".
870 if (MI->isBundledWithSucc() && !MI->isBundledWithPred()) {
871 MachineBasicBlock::instr_iterator BeginIt = MI->getIterator(),
872 EndIt = MI->getParent()->instr_end();
873 ++BeginIt; // Skip MI that was already handled.
874
875 bool OnlyDeadCopies = true;
876 for (MachineBasicBlock::instr_iterator It = BeginIt;
877 It != EndIt && It->isBundledWithPred(); ++It) {
878
879 auto DestSrc = TII.isCopyInstr(*It);
880 bool IsCopyToDeadReg =
881 DestSrc && DestSrc->Destination->getReg() == Reg;
882 if (!IsCopyToDeadReg) {
883 OnlyDeadCopies = false;
884 break;
885 }
886 }
887 if (OnlyDeadCopies) {
888 for (MachineBasicBlock::instr_iterator It = BeginIt;
889 It != EndIt && It->isBundledWithPred(); ++It) {
890 It->addRegisterDead(Reg, &TRI);
891 LLVM_DEBUG(dbgs() << "All defs dead: " << *It);
892 DeadDefs.push_back(&*It);
893 }
894 }
895 }
896 }
897 }
898
899 // Eliminate dead code after remat. Note that some snippet copies may be
900 // deleted here.
901 if (DeadDefs.empty())
902 return;
903 LLVM_DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
904 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
905
906 // LiveRangeEdit::eliminateDeadDef is used to remove dead define instructions
907 // after rematerialization. To remove a VNI for a vreg from its LiveInterval,
908 // LiveIntervals::removeVRegDefAt is used. However, after non-PHI VNIs are all
909 // removed, PHI VNI are still left in the LiveInterval.
910 // So to get rid of unused reg, we need to check whether it has non-dbg
911 // reference instead of whether it has non-empty interval.
912 unsigned ResultPos = 0;
913 for (Register Reg : RegsToSpill) {
914 if (MRI.reg_nodbg_empty(Reg)) {
915 Edit->eraseVirtReg(Reg);
916 RegsReplaced.push_back(Reg);
917 continue;
918 }
919
920 assert(LIS.hasInterval(Reg) &&
921 (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&
922 "Empty and not used live-range?!");
923
924 RegsToSpill[ResultPos++] = Reg;
925 }
926 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
927 LLVM_DEBUG(dbgs() << RegsToSpill.size()
928 << " registers to spill after remat.\n");
929}
930
931//===----------------------------------------------------------------------===//
932// Spilling
933//===----------------------------------------------------------------------===//
934
935/// If MI is a load or store of StackSlot, it can be removed.
936bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
937 int FI = 0;
938 Register InstrReg = TII.isLoadFromStackSlot(*MI, FI);
939 bool IsLoad = InstrReg.isValid();
940 if (!IsLoad)
941 InstrReg = TII.isStoreToStackSlot(*MI, FI);
942
943 // We have a stack access. Is it the right register and slot?
944 if (InstrReg != Reg || FI != StackSlot)
945 return false;
946
947 if (!IsLoad)
948 HSpiller.rmFromMergeableSpills(*MI, StackSlot);
949
950 LLVM_DEBUG(dbgs() << "Coalescing stack access: " << *MI);
951 LIS.RemoveMachineInstrFromMaps(*MI);
952 MI->eraseFromParent();
953
954 if (IsLoad) {
955 ++NumReloadsRemoved;
956 --NumReloads;
957 } else {
958 ++NumSpillsRemoved;
959 --NumSpills;
960 }
961
962 return true;
963}
964
965#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
967// Dump the range of instructions from B to E with their slot indexes.
970 LiveIntervals const &LIS,
971 const char *const header,
972 Register VReg = Register()) {
973 char NextLine = '\n';
974 char SlotIndent = '\t';
975
976 if (std::next(B) == E) {
977 NextLine = ' ';
978 SlotIndent = ' ';
979 }
980
981 dbgs() << '\t' << header << ": " << NextLine;
982
983 for (MachineBasicBlock::iterator I = B; I != E; ++I) {
985
986 // If a register was passed in and this instruction has it as a
987 // destination that is marked as an early clobber, print the
988 // early-clobber slot index.
989 if (VReg) {
990 MachineOperand *MO = I->findRegisterDefOperand(VReg, /*TRI=*/nullptr);
991 if (MO && MO->isEarlyClobber())
992 Idx = Idx.getRegSlot(true);
993 }
994
995 dbgs() << SlotIndent << Idx << '\t' << *I;
996 }
997}
998#endif
999
1000/// foldMemoryOperand - Try folding stack slot references in Ops into their
1001/// instructions.
1002///
1003/// @param Ops Operand indices from AnalyzeVirtRegInBundle().
1004/// @param LoadMI Load instruction to use instead of stack slot when non-null.
1005/// @return True on success.
1006bool InlineSpiller::
1007foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>> Ops,
1008 MachineInstr *LoadMI) {
1009 if (Ops.empty())
1010 return false;
1011 // Don't attempt folding in bundles.
1012 MachineInstr *MI = Ops.front().first;
1013 if (Ops.back().first != MI || MI->isBundled())
1014 return false;
1015
1016 bool WasCopy = TII.isCopyInstr(*MI).has_value();
1017 Register ImpReg;
1018
1019 // TII::foldMemoryOperand will do what we need here for statepoint
1020 // (fold load into use and remove corresponding def). We will replace
1021 // uses of removed def with loads (spillAroundUses).
1022 // For that to work we need to untie def and use to pass it through
1023 // foldMemoryOperand and signal foldPatchpoint that it is allowed to
1024 // fold them.
1025 bool UntieRegs = MI->getOpcode() == TargetOpcode::STATEPOINT;
1026
1027 // Spill subregs if the target allows it.
1028 // We always want to spill subregs for stackmap/patchpoint pseudos.
1029 bool SpillSubRegs = TII.isSubregFoldable() ||
1030 MI->getOpcode() == TargetOpcode::STATEPOINT ||
1031 MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1032 MI->getOpcode() == TargetOpcode::STACKMAP;
1033
1034 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1035 // operands.
1037 for (const auto &OpPair : Ops) {
1038 unsigned Idx = OpPair.second;
1039 assert(MI == OpPair.first && "Instruction conflict during operand folding");
1040 MachineOperand &MO = MI->getOperand(Idx);
1041
1042 // No point restoring an undef read, and we'll produce an invalid live
1043 // interval.
1044 // TODO: Is this really the correct way to handle undef tied uses?
1045 if (MO.isUse() && !MO.readsReg() && !MO.isTied())
1046 continue;
1047
1048 if (MO.isImplicit()) {
1049 ImpReg = MO.getReg();
1050 continue;
1051 }
1052
1053 if (!SpillSubRegs && MO.getSubReg())
1054 return false;
1055 // We cannot fold a load instruction into a def.
1056 if (LoadMI && MO.isDef())
1057 return false;
1058 // Tied use operands should not be passed to foldMemoryOperand.
1059 if (UntieRegs || !MI->isRegTiedToDefOperand(Idx))
1060 FoldOps.push_back(Idx);
1061 }
1062
1063 // If we only have implicit uses, we won't be able to fold that.
1064 // Moreover, TargetInstrInfo::foldMemoryOperand will assert if we try!
1065 if (FoldOps.empty())
1066 return false;
1067
1068 MachineInstrSpan MIS(MI, MI->getParent());
1069
1071 if (UntieRegs)
1072 for (unsigned Idx : FoldOps) {
1073 MachineOperand &MO = MI->getOperand(Idx);
1074 if (!MO.isTied())
1075 continue;
1076 unsigned Tied = MI->findTiedOperandIdx(Idx);
1077 if (MO.isUse())
1078 TiedOps.emplace_back(Tied, Idx);
1079 else {
1080 assert(MO.isDef() && "Tied to not use and def?");
1081 TiedOps.emplace_back(Idx, Tied);
1082 }
1083 MI->untieRegOperand(Idx);
1084 }
1085
1086 MachineInstr *CopyMI = nullptr;
1087 MachineInstr *FoldMI =
1088 LoadMI
1089 ? TII.foldMemoryOperand(*MI, FoldOps, *LoadMI, CopyMI, &LIS, &VRM)
1090 : TII.foldMemoryOperand(*MI, FoldOps, StackSlot, CopyMI, &LIS, &VRM);
1091 if (!FoldMI) {
1092 // Re-tie operands.
1093 for (auto Tied : TiedOps)
1094 MI->tieOperands(Tied.first, Tied.second);
1095 return false;
1096 }
1097
1098 // Remove LIS for any dead defs in the original MI not in FoldMI.
1099 for (MIBundleOperands MO(*MI); MO.isValid(); ++MO) {
1100 if (!MO->isReg())
1101 continue;
1102 Register Reg = MO->getReg();
1103 if (!Reg || Reg.isVirtual() || MRI.isReserved(Reg)) {
1104 continue;
1105 }
1106 // Skip non-Defs, including undef uses and internal reads.
1107 if (MO->isUse())
1108 continue;
1109 PhysRegInfo RI = AnalyzePhysRegInBundle(*FoldMI, Reg, &TRI);
1110 if (RI.FullyDefined)
1111 continue;
1112 // FoldMI does not define this physreg. Remove the LI segment.
1113 assert(MO->isDead() && "Cannot fold physreg def");
1114 SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
1115 LIS.removePhysRegDefAt(Reg.asMCReg(), Idx);
1116 }
1117
1118 int FI;
1119 if (TII.isStoreToStackSlot(*MI, FI) &&
1120 HSpiller.rmFromMergeableSpills(*MI, FI))
1121 --NumSpills;
1122 SlotIndex FoldIdx = LIS.ReplaceMachineInstrInMaps(*MI, *FoldMI);
1123 if (CopyMI) {
1124 SlotIndex CopyIdx = LIS.InsertMachineInstrInMaps(*CopyMI).getRegSlot();
1125 if (!MRI.isSSA()) {
1126 Register CopyDstReg = CopyMI->getOperand(0).getReg();
1127 LiveInterval &LI = LIS.getInterval(CopyDstReg);
1128
1129 // The addSegment below extends CopyDstReg's LiveInterval with a new
1130 // segment for the copy. If CopyDstReg is already assigned in the
1131 // LiveRegMatrix, we must unassign before the modification and reassign
1132 // after, so the matrix stays consistent with the updated interval.
1133 // This can happen when the fold target creates a copy
1134 // to preserve a source operand, defining a vreg that was already
1135 // allocated to a physreg.
1136 bool NeedMatrixReassign =
1137 Matrix && CopyDstReg.isVirtual() && VRM.hasPhys(CopyDstReg);
1138 MCRegister PhysReg;
1139 if (NeedMatrixReassign) {
1140 PhysReg = VRM.getPhys(CopyDstReg);
1141 Matrix->unassign(LI);
1142 }
1143
1144 VNInfo *VNI = LI.getNextValue(CopyIdx, LIS.getVNInfoAllocator());
1145 LI.addSegment(LiveRange::Segment(CopyIdx, FoldIdx.getRegSlot(), VNI));
1146
1147 if (NeedMatrixReassign)
1148 Matrix->assign(LI, PhysReg);
1149
1150 Register OrigReg = VRM.getOriginal(CopyDstReg);
1151 if (OrigReg != CopyDstReg) {
1152 // Extend the original LI to cover the same range so that the
1153 // sub-interval invariant holds: the original must be live wherever
1154 // any of its children are live. Without this, reMaterializeFor()
1155 // can query OrigLI at an early-clobber slot that falls inside
1156 // [CopyIdx, FoldIdx) and get a null VNI, triggering an assertion.
1157 assert(LIS.hasInterval(OrigReg) && "OrigReg should have live interval");
1158 LiveInterval &OrigLI = LIS.getInterval(OrigReg);
1159 if (VNInfo *OrigVNI = OrigLI.getVNInfoAt(FoldIdx.getRegSlot()))
1160 OrigLI.addSegment(
1161 LiveRange::Segment(CopyIdx, FoldIdx.getRegSlot(), OrigVNI));
1162 }
1163 }
1164 }
1165 // Update the call info.
1166 if (MI->isCandidateForAdditionalCallInfo())
1167 MI->getMF()->moveAdditionalCallInfo(MI, FoldMI);
1168
1169 // If we've folded a store into an instruction labelled with debug-info,
1170 // record a substitution from the old operand to the memory operand. Handle
1171 // the simple common case where operand 0 is the one being folded, plus when
1172 // the destination operand is also a tied def. More values could be
1173 // substituted / preserved with more analysis.
1174 if (MI->peekDebugInstrNum() && Ops[0].second == 0) {
1175 // Helper lambda.
1176 auto MakeSubstitution = [this,FoldMI,MI,&Ops]() {
1177 // Substitute old operand zero to the new instructions memory operand.
1178 unsigned OldOperandNum = Ops[0].second;
1179 unsigned NewNum = FoldMI->getDebugInstrNum();
1180 unsigned OldNum = MI->getDebugInstrNum();
1181 MF.makeDebugValueSubstitution({OldNum, OldOperandNum},
1183 };
1184
1185 const MachineOperand &Op0 = MI->getOperand(Ops[0].second);
1186 if (Ops.size() == 1 && Op0.isDef()) {
1187 MakeSubstitution();
1188 } else if (Ops.size() == 2 && Op0.isDef() && MI->getOperand(1).isTied() &&
1189 Op0.getReg() == MI->getOperand(1).getReg()) {
1190 MakeSubstitution();
1191 }
1192 } else if (MI->peekDebugInstrNum()) {
1193 // This is a debug-labelled instruction, but the operand being folded isn't
1194 // at operand zero. Most likely this means it's a load being folded in.
1195 // Substitute any register defs from operand zero up to the one being
1196 // folded -- past that point, we don't know what the new operand indexes
1197 // will be.
1198 MF.substituteDebugValuesForInst(*MI, *FoldMI, Ops[0].second);
1199 }
1200
1201 MI->eraseFromParent();
1202
1203 // Insert any new instructions other than FoldMI into the LIS maps.
1204 assert(!MIS.empty() && "Unexpected empty span of instructions!");
1205 for (MachineInstr &MI : MIS)
1206 if (&MI != FoldMI && &MI != CopyMI)
1208
1209 if (CopyMI) {
1210 Register R = CopyMI->getOperand(1).getReg();
1211 if (R.isVirtual()) {
1212 LiveInterval &LI = LIS.getInterval(R);
1213 LIS.shrinkToUses(&LI);
1214 } else {
1215 assert(MRI.isReserved(R) && "Unexpected PhysReg in source operand!");
1216 }
1217 }
1218
1219 // TII.foldMemoryOperand may have left some implicit operands on the
1220 // instruction. Strip them.
1221 if (ImpReg)
1222 for (unsigned i = FoldMI->getNumOperands(); i; --i) {
1223 MachineOperand &MO = FoldMI->getOperand(i - 1);
1224 if (!MO.isReg() || !MO.isImplicit())
1225 break;
1226 if (MO.getReg() == ImpReg)
1227 FoldMI->removeOperand(i - 1);
1228 }
1229
1230 LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
1231 "folded"));
1232
1233 if (!WasCopy)
1234 ++NumFolded;
1235 else if (Ops.front().second == 0) {
1236 ++NumSpills;
1237 // If there is only 1 store instruction is required for spill, add it
1238 // to mergeable list. In X86 AMX, 2 intructions are required to store.
1239 // We disable the merge for this case.
1240 if (std::distance(MIS.begin(), MIS.end()) <= 1)
1241 HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original);
1242 } else
1243 ++NumReloads;
1244 return true;
1245}
1246
1247void InlineSpiller::insertReload(Register NewVReg,
1248 SlotIndex Idx,
1250 MachineBasicBlock &MBB = *MI->getParent();
1251
1252 MachineInstrSpan MIS(MI, &MBB);
1253 TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
1254 MRI.getRegClass(NewVReg), Register());
1255
1256 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
1257
1258 LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
1259 NewVReg));
1260 ++NumReloads;
1261}
1262
1263/// Check if \p Def fully defines a VReg with an undefined value.
1264/// If that's the case, that means the value of VReg is actually
1265/// not relevant.
1266static bool isRealSpill(const MachineInstr &Def) {
1267 if (!Def.isImplicitDef())
1268 return true;
1269
1270 // We can say that the VReg defined by Def is undef, only if it is
1271 // fully defined by Def. Otherwise, some of the lanes may not be
1272 // undef and the value of the VReg matters.
1273 return Def.getOperand(0).getSubReg();
1274}
1275
1276/// insertSpill - Insert a spill of NewVReg after MI.
1277void InlineSpiller::insertSpill(Register NewVReg, bool isKill,
1279 // Spill are not terminators, so inserting spills after terminators will
1280 // violate invariants in MachineVerifier.
1281 assert(!MI->isTerminator() && "Inserting a spill after a terminator");
1282 MachineBasicBlock &MBB = *MI->getParent();
1283
1284 MachineInstrSpan MIS(MI, &MBB);
1285 MachineBasicBlock::iterator SpillBefore = std::next(MI);
1286 bool IsRealSpill = isRealSpill(*MI);
1287
1288 if (IsRealSpill)
1289 TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, isKill, StackSlot,
1290 MRI.getRegClass(NewVReg), Register());
1291 else
1292 // Don't spill undef value.
1293 // Anything works for undef, in particular keeping the memory
1294 // uninitialized is a viable option and it saves code size and
1295 // run time.
1296 BuildMI(MBB, SpillBefore, MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
1297 .addReg(NewVReg, getKillRegState(isKill));
1298
1300 LIS.InsertMachineInstrRangeInMaps(Spill, MIS.end());
1301 for (const MachineInstr &MI : make_range(Spill, MIS.end()))
1302 getVDefInterval(MI, LIS);
1303
1304 LLVM_DEBUG(
1305 dumpMachineInstrRangeWithSlotIndex(Spill, MIS.end(), LIS, "spill"));
1306 ++NumSpills;
1307 // If there is only 1 store instruction is required for spill, add it
1308 // to mergeable list. In X86 AMX, 2 intructions are required to store.
1309 // We disable the merge for this case.
1310 if (IsRealSpill && std::distance(Spill, MIS.end()) <= 1)
1311 HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
1312}
1313
1314/// spillAroundUses - insert spill code around each use of Reg.
1315void InlineSpiller::spillAroundUses(Register Reg) {
1316 LLVM_DEBUG(dbgs() << "spillAroundUses " << printReg(Reg) << '\n');
1317 LiveInterval &OldLI = LIS.getInterval(Reg);
1318
1319 // Iterate over instructions using Reg.
1320 for (MachineInstr &MI : llvm::make_early_inc_range(MRI.reg_bundles(Reg))) {
1321 // Debug values are not allowed to affect codegen.
1322 if (MI.isDebugValue()) {
1323 // Modify DBG_VALUE now that the value is in a spill slot.
1324 MachineBasicBlock *MBB = MI.getParent();
1325 LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:\t" << MI);
1326 buildDbgValueForSpill(*MBB, &MI, MI, StackSlot, Reg);
1327 MBB->erase(MI);
1328 continue;
1329 }
1330
1331 assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "
1332 "instruction that isn't a DBG_VALUE");
1333
1334 // Ignore copies to/from snippets. We'll delete them.
1335 if (SnippetCopies.count(&MI))
1336 continue;
1337
1338 // Stack slot accesses may coalesce away.
1339 if (coalesceStackAccess(&MI, Reg))
1340 continue;
1341
1342 // Analyze instruction.
1345
1346 // Find the slot index where this instruction reads and writes OldLI.
1347 // This is usually the def slot, except for tied early clobbers.
1349 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1350 if (SlotIndex::isSameInstr(Idx, VNI->def))
1351 Idx = VNI->def;
1352
1353 // Check for a sibling copy.
1354 Register SibReg = isCopyOfBundle(MI, Reg, TII);
1355 if (SibReg && isSibling(SibReg)) {
1356 // This may actually be a copy between snippets.
1357 if (isRegToSpill(SibReg)) {
1358 LLVM_DEBUG(dbgs() << "Found new snippet copy: " << MI);
1359 SnippetCopies.insert(&MI);
1360 continue;
1361 }
1362 if (RI.Writes) {
1363 if (hoistSpillInsideBB(OldLI, MI)) {
1364 // This COPY is now dead, the value is already in the stack slot.
1365 MI.getOperand(0).setIsDead();
1366 DeadDefs.push_back(&MI);
1367 continue;
1368 }
1369 } else {
1370 // This is a reload for a sib-reg copy. Drop spills downstream.
1371 LiveInterval &SibLI = LIS.getInterval(SibReg);
1372 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1373 // The COPY will fold to a reload below.
1374 }
1375 }
1376
1377 // Attempt to fold memory ops.
1378 if (foldMemoryOperand(Ops))
1379 continue;
1380
1381 // Create a new virtual register for spill/fill.
1382 // FIXME: Infer regclass from instruction alone.
1383 Register NewVReg = Edit->createFrom(Reg);
1384
1385 if (RI.Reads)
1386 insertReload(NewVReg, Idx, &MI);
1387
1388 // Rewrite instruction operands.
1389 bool hasLiveDef = false;
1390 for (const auto &OpPair : Ops) {
1391 MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
1392 MO.setReg(NewVReg);
1393 if (MO.isUse()) {
1394 if (!OpPair.first->isRegTiedToDefOperand(OpPair.second))
1395 MO.setIsKill();
1396 } else {
1397 if (!MO.isDead())
1398 hasLiveDef = true;
1399 }
1400 }
1401 LLVM_DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << MI << '\n');
1402
1403 // FIXME: Use a second vreg if instruction has no tied ops.
1404 if (RI.Writes)
1405 if (hasLiveDef)
1406 insertSpill(NewVReg, true, &MI);
1407 }
1408}
1409
1410/// spillAll - Spill all registers remaining after rematerialization.
1411void InlineSpiller::spillAll() {
1412 // Update LiveStacks now that we are committed to spilling.
1413 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1414 StackSlot = VRM.assignVirt2StackSlot(Original);
1415 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1416 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1417 } else
1418 StackInt = &LSS.getInterval(StackSlot);
1419
1420 if (Original != Edit->getReg())
1421 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1422
1423 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1424 for (Register Reg : RegsToSpill)
1425 StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
1426 StackInt->getValNumInfo(0));
1427 LLVM_DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1428
1429 // Spill around uses of all RegsToSpill.
1430 for (Register Reg : RegsToSpill) {
1431 spillAroundUses(Reg);
1432 // Assign all of the spilled registers to the slot so that
1433 // LiveDebugVariables knows about these locations later on.
1434 if (VRM.getStackSlot(Reg) == VirtRegMap::NO_STACK_SLOT)
1435 VRM.assignVirt2StackSlot(Reg, StackSlot);
1436 }
1437
1438 // Hoisted spills may cause dead code.
1439 if (!DeadDefs.empty()) {
1440 LLVM_DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1441 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
1442 }
1443
1444 // Finally delete the SnippetCopies.
1445 for (Register Reg : RegsToSpill) {
1446 for (MachineInstr &MI :
1447 llvm::make_early_inc_range(MRI.reg_instructions(Reg))) {
1448 assert(SnippetCopies.count(&MI) && "Remaining use wasn't a snippet copy");
1449 // FIXME: Do this with a LiveRangeEdit callback.
1451 MI.eraseFromBundle();
1452 }
1453 }
1454
1455 // Delete all spilled registers.
1456 for (Register Reg : RegsToSpill)
1457 Edit->eraseVirtReg(Reg);
1458}
1459
1460void InlineSpiller::spill(LiveRangeEdit &edit, AllocationOrder *order) {
1461 ++NumSpilledRanges;
1462 Edit = &edit;
1463 Order = order;
1464 assert(!edit.getReg().isStack() && "Trying to spill a stack slot.");
1465 // Share a stack slot among all descendants of Original.
1466 Original = VRM.getOriginal(edit.getReg());
1467 StackSlot = VRM.getStackSlot(Original);
1468 StackInt = nullptr;
1469
1470 LLVM_DEBUG(dbgs() << "Inline spilling "
1471 << TRI.getRegClassName(MRI.getRegClass(edit.getReg()))
1472 << ':' << edit.getParent() << "\nFrom original "
1473 << printReg(Original) << '\n');
1474 assert(edit.getParent().isSpillable() &&
1475 "Attempting to spill already spilled value.");
1476 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1477
1478 collectRegsToSpill();
1479 reMaterializeAll();
1480
1481 // Remat may handle everything.
1482 if (!RegsToSpill.empty())
1483 spillAll();
1484
1485 Edit->calculateRegClassAndHint(MF, VRAI);
1486}
1487
1488/// Optimizations after all the reg selections and spills are done.
1489void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
1490
1491/// When a spill is inserted, add the spill to MergeableSpills map.
1492void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
1493 Register Original) {
1495 LiveInterval &OrigLI = LIS.getInterval(Original);
1496 // save a copy of LiveInterval in StackSlotToOrigLI because the original
1497 // LiveInterval may be cleared after all its references are spilled.
1498
1499 auto [Place, Inserted] = StackSlotToOrigLI.try_emplace(StackSlot);
1500 if (Inserted) {
1501 auto LI = std::make_unique<LiveInterval>(OrigLI.reg(), OrigLI.weight());
1502 LI->assign(OrigLI, Allocator);
1503 Place->second = std::move(LI);
1504 }
1505
1506 SlotIndex Idx = LIS.getInstructionIndex(Spill);
1507 VNInfo *OrigVNI = Place->second->getVNInfoAt(Idx.getRegSlot());
1508 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1509 MergeableSpills[MIdx].insert(&Spill);
1510}
1511
1512/// When a spill is removed, remove the spill from MergeableSpills map.
1513/// Return true if the spill is removed successfully.
1514bool HoistSpillHelper::rmFromMergeableSpills(MachineInstr &Spill,
1515 int StackSlot) {
1516 auto It = StackSlotToOrigLI.find(StackSlot);
1517 if (It == StackSlotToOrigLI.end())
1518 return false;
1519 SlotIndex Idx = LIS.getInstructionIndex(Spill);
1520 VNInfo *OrigVNI = It->second->getVNInfoAt(Idx.getRegSlot());
1521 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1522 return MergeableSpills[MIdx].erase(&Spill);
1523}
1524
1525/// Check BB to see if it is a possible target BB to place a hoisted spill,
1526/// i.e., there should be a living sibling of OrigReg at the insert point.
1527bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
1528 MachineBasicBlock &BB, Register &LiveReg) {
1529 SlotIndex Idx = IPA.getLastInsertPoint(OrigLI, BB);
1530 // The original def could be after the last insert point in the root block,
1531 // we can't hoist to here.
1532 if (Idx < OrigVNI.def) {
1533 // TODO: We could be better here. If LI is not alive in landing pad
1534 // we could hoist spill after LIP.
1535 LLVM_DEBUG(dbgs() << "can't spill in root block - def after LIP\n");
1536 return false;
1537 }
1538 Register OrigReg = OrigLI.reg();
1539 SmallSetVector<Register, 16> &Siblings = Virt2SiblingsMap[OrigReg];
1540 assert(OrigLI.getVNInfoAt(Idx) == &OrigVNI && "Unexpected VNI");
1541
1542 for (const Register &SibReg : Siblings) {
1543 LiveInterval &LI = LIS.getInterval(SibReg);
1544 if (!LI.getVNInfoAt(Idx))
1545 continue;
1546 // All of the sub-ranges should be alive at the prospective slot index.
1547 // Otherwise, we might risk storing unrelated / compromised values from some
1548 // sub-registers to the spill slot.
1549 if (all_of(LI.subranges(), [&](const LiveInterval::SubRange &SR) {
1550 return SR.getVNInfoAt(Idx) != nullptr;
1551 })) {
1552 LiveReg = SibReg;
1553 return true;
1554 }
1555 }
1556 return false;
1557}
1558
1559/// Remove redundant spills in the same BB. Save those redundant spills in
1560/// SpillsToRm, and save the spill to keep and its BB in SpillBBToSpill map.
1561void HoistSpillHelper::rmRedundantSpills(
1565 // For each spill saw, check SpillBBToSpill[] and see if its BB already has
1566 // another spill inside. If a BB contains more than one spill, only keep the
1567 // earlier spill with smaller SlotIndex.
1568 for (auto *const CurrentSpill : Spills) {
1569 MachineBasicBlock *Block = CurrentSpill->getParent();
1570 MachineDomTreeNode *Node = MDT.getNode(Block);
1571 MachineInstr *PrevSpill = SpillBBToSpill[Node];
1572 if (PrevSpill) {
1573 SlotIndex PIdx = LIS.getInstructionIndex(*PrevSpill);
1574 SlotIndex CIdx = LIS.getInstructionIndex(*CurrentSpill);
1575 MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill;
1576 MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill;
1577 SpillsToRm.push_back(SpillToRm);
1578 SpillBBToSpill[MDT.getNode(Block)] = SpillToKeep;
1579 } else {
1580 SpillBBToSpill[MDT.getNode(Block)] = CurrentSpill;
1581 }
1582 }
1583 for (auto *const SpillToRm : SpillsToRm)
1584 Spills.erase(SpillToRm);
1585}
1586
1587/// Starting from \p Root find a top-down traversal order of the dominator
1588/// tree to visit all basic blocks containing the elements of \p Spills.
1589/// Redundant spills will be found and put into \p SpillsToRm at the same
1590/// time. \p SpillBBToSpill will be populated as part of the process and
1591/// maps a basic block to the first store occurring in the basic block.
1592/// \post SpillsToRm.union(Spills\@post) == Spills\@pre
1593void HoistSpillHelper::getVisitOrders(
1599 // The set contains all the possible BB nodes to which we may hoist
1600 // original spills.
1602 // Save the BB nodes on the path from the first BB node containing
1603 // non-redundant spill to the Root node.
1605 // All the spills to be hoisted must originate from a single def instruction
1606 // to the OrigReg. It means the def instruction should dominate all the spills
1607 // to be hoisted. We choose the BB where the def instruction is located as
1608 // the Root.
1609 MachineDomTreeNode *RootIDomNode = MDT[Root]->getIDom();
1610 // For every node on the dominator tree with spill, walk up on the dominator
1611 // tree towards the Root node until it is reached. If there is other node
1612 // containing spill in the middle of the path, the previous spill saw will
1613 // be redundant and the node containing it will be removed. All the nodes on
1614 // the path starting from the first node with non-redundant spill to the Root
1615 // node will be added to the WorkSet, which will contain all the possible
1616 // locations where spills may be hoisted to after the loop below is done.
1617 for (auto *const Spill : Spills) {
1618 MachineBasicBlock *Block = Spill->getParent();
1620 MachineInstr *SpillToRm = nullptr;
1621 while (Node != RootIDomNode) {
1622 // If Node dominates Block, and it already contains a spill, the spill in
1623 // Block will be redundant.
1624 if (Node != MDT[Block] && SpillBBToSpill[Node]) {
1625 SpillToRm = SpillBBToSpill[MDT[Block]];
1626 break;
1627 /// If we see the Node already in WorkSet, the path from the Node to
1628 /// the Root node must already be traversed by another spill.
1629 /// Then no need to repeat.
1630 } else if (WorkSet.count(Node)) {
1631 break;
1632 } else {
1633 NodesOnPath.insert(Node);
1634 }
1635 Node = Node->getIDom();
1636 }
1637 if (SpillToRm) {
1638 SpillsToRm.push_back(SpillToRm);
1639 } else {
1640 // Add a BB containing the original spills to SpillsToKeep -- i.e.,
1641 // set the initial status before hoisting start. The value of BBs
1642 // containing original spills is set to 0, in order to descriminate
1643 // with BBs containing hoisted spills which will be inserted to
1644 // SpillsToKeep later during hoisting.
1645 SpillsToKeep[MDT[Block]] = Register();
1646 WorkSet.insert_range(NodesOnPath);
1647 }
1648 NodesOnPath.clear();
1649 }
1650
1651 // Sort the nodes in WorkSet in top-down order and save the nodes
1652 // in Orders. Orders will be used for hoisting in runHoistSpills.
1653 unsigned idx = 0;
1654 Orders.push_back(MDT.getNode(Root));
1655 do {
1656 MachineDomTreeNode *Node = Orders[idx++];
1657 for (MachineDomTreeNode *Child : Node->children()) {
1658 if (WorkSet.count(Child))
1659 Orders.push_back(Child);
1660 }
1661 } while (idx != Orders.size());
1662 assert(Orders.size() == WorkSet.size() &&
1663 "Orders have different size with WorkSet");
1664
1665#ifndef NDEBUG
1666 LLVM_DEBUG(dbgs() << "Orders size is " << Orders.size() << "\n");
1668 for (; RIt != Orders.rend(); RIt++)
1669 LLVM_DEBUG(dbgs() << "BB" << (*RIt)->getBlock()->getNumber() << ",");
1670 LLVM_DEBUG(dbgs() << "\n");
1671#endif
1672}
1673
1674/// Try to hoist spills according to BB hotness. The spills to removed will
1675/// be saved in \p SpillsToRm. The spills to be inserted will be saved in
1676/// \p SpillsToIns.
1677void HoistSpillHelper::runHoistSpills(
1678 LiveInterval &OrigLI, VNInfo &OrigVNI,
1682 // Visit order of dominator tree nodes.
1684 // SpillsToKeep contains all the nodes where spills are to be inserted
1685 // during hoisting. If the spill to be inserted is an original spill
1686 // (not a hoisted one), the value of the map entry is 0. If the spill
1687 // is a hoisted spill, the value of the map entry is the VReg to be used
1688 // as the source of the spill.
1690 // Map from BB to the first spill inside of it.
1692
1693 rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill);
1694
1695 MachineBasicBlock *Root = LIS.getMBBFromIndex(OrigVNI.def);
1696 getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep,
1697 SpillBBToSpill);
1698
1699 // SpillsInSubTreeMap keeps the map from a dom tree node to a pair of
1700 // nodes set and the cost of all the spills inside those nodes.
1701 // The nodes set are the locations where spills are to be inserted
1702 // in the subtree of current node.
1703 using NodesCostPair =
1704 std::pair<SmallPtrSet<MachineDomTreeNode *, 16>, BlockFrequency>;
1706
1707 // Iterate Orders set in reverse order, which will be a bottom-up order
1708 // in the dominator tree. Once we visit a dom tree node, we know its
1709 // children have already been visited and the spill locations in the
1710 // subtrees of all the children have been determined.
1712 for (; RIt != Orders.rend(); RIt++) {
1713 MachineBasicBlock *Block = (*RIt)->getBlock();
1714
1715 // If Block contains an original spill, simply continue.
1716 if (auto It = SpillsToKeep.find(*RIt);
1717 It != SpillsToKeep.end() && !It->second) {
1718 auto &SIt = SpillsInSubTreeMap[*RIt];
1719 SIt.first.insert(*RIt);
1720 // Sit.second contains the cost of spill.
1721 SIt.second = MBFI.getBlockFreq(Block);
1722 continue;
1723 }
1724
1725 // Collect spills in subtree of current node (*RIt) to
1726 // SpillsInSubTreeMap[*RIt].first.
1727 for (MachineDomTreeNode *Child : (*RIt)->children()) {
1728 if (!SpillsInSubTreeMap.contains(Child))
1729 continue;
1730 // The stmt:
1731 // "auto &[SpillsInSubTree, SubTreeCost] = SpillsInSubTreeMap[*RIt]"
1732 // below should be placed before getting the begin and end iterators of
1733 // SpillsInSubTreeMap[Child].first, or else the iterators may be
1734 // invalidated when SpillsInSubTreeMap[*RIt] is seen the first time
1735 // and the map grows and then the original buckets in the map are moved.
1736 auto &[SpillsInSubTree, SubTreeCost] = SpillsInSubTreeMap[*RIt];
1737 auto ChildIt = SpillsInSubTreeMap.find(Child);
1738 SubTreeCost += ChildIt->second.second;
1739 auto BI = ChildIt->second.first.begin();
1740 auto EI = ChildIt->second.first.end();
1741 SpillsInSubTree.insert(BI, EI);
1742 SpillsInSubTreeMap.erase(ChildIt);
1743 }
1744
1745 auto &[SpillsInSubTree, SubTreeCost] = SpillsInSubTreeMap[*RIt];
1746 // No spills in subtree, simply continue.
1747 if (SpillsInSubTree.empty())
1748 continue;
1749
1750 // Check whether Block is a possible candidate to insert spill.
1751 Register LiveReg;
1752 if (!isSpillCandBB(OrigLI, OrigVNI, *Block, LiveReg))
1753 continue;
1754
1755 // If there are multiple spills that could be merged, bias a little
1756 // to hoist the spill.
1757 BranchProbability MarginProb = (SpillsInSubTree.size() > 1)
1758 ? BranchProbability(9, 10)
1759 : BranchProbability(1, 1);
1760 if (SubTreeCost > MBFI.getBlockFreq(Block) * MarginProb) {
1761 // Hoist: Move spills to current Block.
1762 for (auto *const SpillBB : SpillsInSubTree) {
1763 // When SpillBB is a BB contains original spill, insert the spill
1764 // to SpillsToRm.
1765 if (auto It = SpillsToKeep.find(SpillBB);
1766 It != SpillsToKeep.end() && !It->second) {
1767 MachineInstr *SpillToRm = SpillBBToSpill[SpillBB];
1768 SpillsToRm.push_back(SpillToRm);
1769 }
1770 // SpillBB will not contain spill anymore, remove it from SpillsToKeep.
1771 SpillsToKeep.erase(SpillBB);
1772 }
1773 // Current Block is the BB containing the new hoisted spill. Add it to
1774 // SpillsToKeep. LiveReg is the source of the new spill.
1775 SpillsToKeep[*RIt] = LiveReg;
1776 LLVM_DEBUG({
1777 dbgs() << "spills in BB: ";
1778 for (const auto Rspill : SpillsInSubTree)
1779 dbgs() << Rspill->getBlock()->getNumber() << " ";
1780 dbgs() << "were promoted to BB" << (*RIt)->getBlock()->getNumber()
1781 << "\n";
1782 });
1783 SpillsInSubTree.clear();
1784 SpillsInSubTree.insert(*RIt);
1785 SubTreeCost = MBFI.getBlockFreq(Block);
1786 }
1787 }
1788 // For spills in SpillsToKeep with LiveReg set (i.e., not original spill),
1789 // save them to SpillsToIns.
1790 for (const auto &Ent : SpillsToKeep) {
1791 if (Ent.second)
1792 SpillsToIns[Ent.first->getBlock()] = Ent.second;
1793 }
1794}
1795
1796/// For spills with equal values, remove redundant spills and hoist those left
1797/// to less hot spots.
1798///
1799/// Spills with equal values will be collected into the same set in
1800/// MergeableSpills when spill is inserted. These equal spills are originated
1801/// from the same defining instruction and are dominated by the instruction.
1802/// Before hoisting all the equal spills, redundant spills inside in the same
1803/// BB are first marked to be deleted. Then starting from the spills left, walk
1804/// up on the dominator tree towards the Root node where the define instruction
1805/// is located, mark the dominated spills to be deleted along the way and
1806/// collect the BB nodes on the path from non-dominated spills to the define
1807/// instruction into a WorkSet. The nodes in WorkSet are the candidate places
1808/// where we are considering to hoist the spills. We iterate the WorkSet in
1809/// bottom-up order, and for each node, we will decide whether to hoist spills
1810/// inside its subtree to that node. In this way, we can get benefit locally
1811/// even if hoisting all the equal spills to one cold place is impossible.
1812void HoistSpillHelper::hoistAllSpills() {
1813 SmallVector<Register, 4> NewVRegs;
1814 LiveRangeEdit Edit(nullptr, NewVRegs, MF, LIS, &VRM, this);
1815
1816 for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
1818 Register Original = VRM.getPreSplitReg(Reg);
1819 if (!MRI.def_empty(Reg) && Original.isValid())
1820 Virt2SiblingsMap[Original].insert(Reg);
1821 }
1822
1823 // Each entry in MergeableSpills contains a spill set with equal values.
1824 for (auto &Ent : MergeableSpills) {
1825 int Slot = Ent.first.first;
1826 LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
1827 VNInfo *OrigVNI = Ent.first.second;
1828 SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
1829 if (Ent.second.empty())
1830 continue;
1831
1832 LLVM_DEBUG({
1833 dbgs() << "\nFor Slot" << Slot << " and VN" << OrigVNI->id << ":\n"
1834 << "Equal spills in BB: ";
1835 for (const auto spill : EqValSpills)
1836 dbgs() << spill->getParent()->getNumber() << " ";
1837 dbgs() << "\n";
1838 });
1839
1840 // SpillsToRm is the spill set to be removed from EqValSpills.
1842 // SpillsToIns is the spill set to be newly inserted after hoisting.
1844
1845 runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns);
1846
1847 LLVM_DEBUG({
1848 dbgs() << "Finally inserted spills in BB: ";
1849 for (const auto &Ispill : SpillsToIns)
1850 dbgs() << Ispill.first->getNumber() << " ";
1851 dbgs() << "\nFinally removed spills in BB: ";
1852 for (const auto Rspill : SpillsToRm)
1853 dbgs() << Rspill->getParent()->getNumber() << " ";
1854 dbgs() << "\n";
1855 });
1856
1857 // Stack live range update.
1858 LiveInterval &StackIntvl = LSS.getInterval(Slot);
1859 if (!SpillsToIns.empty() || !SpillsToRm.empty())
1860 StackIntvl.MergeValueInAsValue(OrigLI, OrigVNI,
1861 StackIntvl.getValNumInfo(0));
1862
1863 // Insert hoisted spills.
1864 for (auto const &Insert : SpillsToIns) {
1865 MachineBasicBlock *BB = Insert.first;
1866 Register LiveReg = Insert.second;
1867 MachineBasicBlock::iterator MII = IPA.getLastInsertPointIter(OrigLI, *BB);
1868 MachineInstrSpan MIS(MII, BB);
1869 TII.storeRegToStackSlot(*BB, MII, LiveReg, false, Slot,
1870 MRI.getRegClass(LiveReg), Register());
1871 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MII);
1872 for (const MachineInstr &MI : make_range(MIS.begin(), MII))
1873 getVDefInterval(MI, LIS);
1874 ++NumSpills;
1875 }
1876
1877 // Remove redundant spills or change them to dead instructions.
1878 NumSpills -= SpillsToRm.size();
1879 for (auto *const RMEnt : SpillsToRm) {
1880 RMEnt->setDesc(TII.get(TargetOpcode::KILL));
1881 for (unsigned i = RMEnt->getNumOperands(); i; --i) {
1882 MachineOperand &MO = RMEnt->getOperand(i - 1);
1883 if (MO.isReg() && MO.isImplicit() && MO.isDef() && !MO.isDead())
1884 RMEnt->removeOperand(i - 1);
1885 }
1886 }
1887 Edit.eliminateDeadDefs(SpillsToRm, {});
1888 }
1889
1890 // Flush vregs that were unassigned from the matrix during shrinking but
1891 // were not split (so LRE_DidCloneVirtReg never re-assigned them).
1892 for (auto &[VReg, PhysReg] : PendingReassignments) {
1893 assert(Matrix && LIS.hasInterval(VReg) &&
1894 "Pending reassignment without matrix or live interval");
1895 Matrix->assign(LIS.getInterval(VReg), PhysReg);
1896 }
1897 PendingReassignments.clear();
1898}
1899
1900/// Called when a virtual register's live interval is about to be shrunk.
1901/// Unassign from the matrix so the shrunk interval can be re-assigned by a
1902/// later LRE_DidCloneVirtReg or by hoistAllSpills' flush, and stash the
1903/// physreg in PendingReassignments since the unassign clears VRM.
1904void HoistSpillHelper::LRE_WillShrinkVirtReg(Register VirtReg) {
1905 if (!Matrix || !VRM.hasPhys(VirtReg) || !LIS.hasInterval(VirtReg))
1906 return;
1907
1908 MCRegister PhysReg = VRM.getPhys(VirtReg);
1909 LiveInterval &LI = LIS.getInterval(VirtReg);
1910 Matrix->unassign(LI, /*ClearAllReferencingSegments=*/true);
1911 PendingReassignments[VirtReg] = PhysReg;
1912}
1913
1914/// Called before a virtual register is erased from LiveIntervals.
1915/// Forcibly remove the register from LiveRegMatrix before it's deleted,
1916/// preventing dangling pointers.
1917bool HoistSpillHelper::LRE_CanEraseVirtReg(Register VirtReg) {
1918 PendingReassignments.erase(VirtReg);
1919 if (Matrix && VRM.hasPhys(VirtReg)) {
1920 const LiveInterval &LI = LIS.getInterval(VirtReg);
1921 Matrix->unassign(LI, /*ClearAllReferencingSegments=*/true);
1922 }
1923 return true; // Allow deletion to proceed
1924}
1925
1926/// For VirtReg clone, the \p New register should have the same physreg or
1927/// stackslot as the \p old register.
1928void HoistSpillHelper::LRE_DidCloneVirtReg(Register New, Register Old) {
1929 // New is freshly created by LiveRangeEdit::eliminateDeadDefs and its interval
1930 // is guaranteed to exist on every path below.
1931 assert(LIS.hasInterval(New) && "Cloned vreg without live interval");
1932
1933 auto PendingIt = PendingReassignments.find(Old);
1934 if (PendingIt != PendingReassignments.end()) {
1935 // Old was already unassigned in LRE_WillShrinkVirtReg, which only
1936 // enrolls vregs when Matrix is non-null and the interval exists.
1937 assert(Matrix && LIS.hasInterval(Old) &&
1938 "Pending reassignment without matrix or live interval");
1939 MCRegister PhysReg = PendingIt->second;
1940 PendingReassignments.erase(PendingIt);
1941
1942 // Reassign both Old (with its shrunk interval) and New to the matrix.
1943 Matrix->assign(LIS.getInterval(Old), PhysReg);
1944 Matrix->assign(LIS.getInterval(New), PhysReg);
1945 } else if (VRM.hasPhys(Old)) {
1946 MCRegister PhysReg = VRM.getPhys(Old);
1947 if (Matrix) {
1948 if (LIS.hasInterval(Old)) {
1949 const LiveInterval &LI = LIS.getInterval(Old);
1950 // Drop stale pre-clone segments before reassigning Old's current LI.
1951 Matrix->unassign(LI, /*ClearAllReferencingSegments=*/true);
1952 Matrix->assign(LI, PhysReg);
1953 }
1954 Matrix->assign(LIS.getInterval(New), PhysReg);
1955 } else {
1956 VRM.assignVirt2Phys(New, PhysReg);
1957 }
1958 } else if (VRM.getStackSlot(Old) != VirtRegMap::NO_STACK_SLOT) {
1959 VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old));
1960 } else {
1961 llvm_unreachable("VReg should be assigned either physreg or stackslot");
1962 }
1963 if (VRM.hasShape(Old))
1964 VRM.assignVirt2Shape(New, VRM.getShape(Old));
1965}
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:678
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)
Check if Def fully defines a VReg 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)
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
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool erase(const KeyT &Val)
Definition DenseMap.h:377
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
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)
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()
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
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.
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.
void setIsKill(bool Val=true)
void setIsUndef(bool Val=true)
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
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...
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
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:66
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
Definition SmallPtrSet.h:99
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:345
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.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
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:66
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:1739
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr RegState getKillRegState(bool B)
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:633
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 >
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:1947
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
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.