LLVM 24.0.0git
CalcSpillWeights.cpp
Go to the documentation of this file.
1//===- CalcSpillWeights.cpp -----------------------------------------------===//
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
24#include "llvm/Support/Debug.h"
27#include <cassert>
28#include <tuple>
29
30using namespace llvm;
31
32#define DEBUG_TYPE "calcspillweights"
33
34bool VirtRegAuxInfo::getCachedOptimizeForSize() {
35 if (!CachedOptForSize.has_value())
36 CachedOptForSize = PSI && llvm::shouldOptimizeForSize(&MF, PSI, &MBFI);
37 return *CachedOptForSize;
38}
39
41 LLVM_DEBUG(dbgs() << "********** Compute Spill Weights **********\n"
42 << "********** Function: " << MF.getName() << '\n');
43
44 MachineRegisterInfo &MRI = MF.getRegInfo();
45 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
47 if (MRI.reg_nodbg_empty(Reg))
48 continue;
49 calculateSpillWeightAndHint(LIS.getInterval(Reg));
50 }
51}
52
53// Return the preferred allocation register for reg, given a COPY instruction.
56 const MachineRegisterInfo &MRI) {
57 unsigned Sub, HSub;
58 Register HReg;
59 if (MI->getOperand(0).getReg() == Reg) {
60 Sub = MI->getOperand(0).getSubReg();
61 HReg = MI->getOperand(1).getReg();
62 HSub = MI->getOperand(1).getSubReg();
63 } else {
64 Sub = MI->getOperand(1).getSubReg();
65 HReg = MI->getOperand(0).getReg();
66 HSub = MI->getOperand(0).getSubReg();
67 }
68
69 if (!HReg)
70 return 0;
71
72 if (HReg.isVirtual())
73 return Sub == HSub ? HReg : Register();
74
75 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
76 MCRegister CopiedPReg = HSub ? TRI.getSubReg(HReg, HSub) : HReg.asMCReg();
77 if (RC->contains(CopiedPReg))
78 return CopiedPReg;
79
80 // Check if reg:sub matches so that a super register could be hinted.
81 if (Sub)
82 return TRI.getMatchingSuperReg(CopiedPReg, Sub, RC);
83
84 return Register();
85}
86
87// Check if all values in LI are rematerializable
89 const LiveIntervals &LIS,
90 const VirtRegMap &VRM,
92 const TargetInstrInfo &TII) {
93 Register Reg = LI.reg();
94 Register Original = VRM.getOriginal(Reg);
97 I != E; ++I) {
98 const VNInfo *VNI = *I;
99 const VNInfo *OrigVNI = VNI;
100 if (VNI->isUnused())
101 continue;
102 if (VNI->isPHIDef())
103 return false;
104
105 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
106 assert(MI && "Dead valno in interval");
107
108 // Trace copies introduced by live range splitting. The inline
109 // spiller can rematerialize through these copies, so the spill
110 // weight must reflect this.
111 while (TII.isFullCopyInstr(*MI)) {
112 // The copy destination must match the interval register.
113 if (MI->getOperand(0).getReg() != Reg)
114 return false;
115
116 // Get the source register.
117 Reg = MI->getOperand(1).getReg();
118
119 // If the original (pre-splitting) registers match this
120 // copy came from a split.
121 if (!Reg.isVirtual() || VRM.getOriginal(Reg) != Original)
122 return false;
123
124 // Follow the copy live-in value.
125 const LiveInterval &SrcLI = LIS.getInterval(Reg);
126 LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
127 VNI = SrcQ.valueIn();
128 assert(VNI && "Copy from non-existing value");
129 if (VNI->isPHIDef())
130 return false;
131 MI = LIS.getInstructionFromIndex(VNI->def);
132 assert(MI && "Dead valno in interval");
133 }
134
135 if (!TII.isReMaterializable(*MI))
136 return false;
137
138 VNIDefs[OrigVNI->id] = MI;
139 }
140
141 // If MI has register uses, it will only be rematerializable if its uses are
142 // also live at the indices it will be rematerialized at.
143 for (MachineOperand &MO : MRI.reg_nodbg_operands(LI.reg())) {
144 if (!MO.readsReg())
145 continue;
146 SlotIndex UseIdx = LIS.getInstructionIndex(*MO.getParent());
147 MachineInstr *Def = VNIDefs[LI.getVNInfoAt(UseIdx)->id];
148 assert(Def && "Use with no def");
149 if (!allUsesAvailableAt(Def, UseIdx, LIS, MRI, TII))
150 return false;
151 }
152
153 return true;
154}
155
157 SlotIndex UseIdx,
158 const LiveIntervals &LIS,
160 const TargetInstrInfo &TII) {
161 SlotIndex OrigIdx = LIS.getInstructionIndex(*MI).getRegSlot(true);
162 UseIdx = std::max(UseIdx, UseIdx.getRegSlot(true));
163 for (const MachineOperand &MO : MI->operands()) {
164 if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
165 continue;
166
167 // We can't remat physreg uses, unless it is a constant or target wants
168 // to ignore this use.
169 if (MO.getReg().isPhysical()) {
170 if (MRI.isConstantPhysReg(MO.getReg()) ||
171 TII.isIgnorableUse(*MI, MI->getOperandNo(&MO)))
172 continue;
173 return false;
174 }
175
176 // A partial (non-undef) subregister def reads the other subregisters.
177 // A rematerialized copy defines a new register that contains undefined
178 // subregisters, so such instructions cannot be rematerialized.
179 if (MO.isDef())
180 return false;
181
182 const LiveInterval &li = LIS.getInterval(MO.getReg());
183 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
184 if (!OVNI)
185 continue;
186
187 // Don't allow rematerialization immediately after the original def.
188 // It would be incorrect if OrigMI redefines the register.
189 // See PR14098.
190 if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
191 return false;
192
193 if (OVNI != li.getVNInfoAt(UseIdx))
194 return false;
195
196 // Check that subrange is live at UseIdx.
197 if (li.hasSubRanges()) {
198 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
199 unsigned SubReg = MO.getSubReg();
200 LaneBitmask LM = SubReg ? TRI->getSubRegIndexLaneMask(SubReg)
201 : MRI.getMaxLaneMaskForVReg(MO.getReg());
202 for (const LiveInterval::SubRange &SR : li.subranges()) {
203 if ((SR.LaneMask & LM).none())
204 continue;
205 if (!SR.liveAt(UseIdx))
206 return false;
207 // Early exit if all used lanes are checked. No need to continue.
208 LM &= ~SR.LaneMask;
209 if (LM.none())
210 break;
211 }
212 }
213 }
214 return true;
215}
216
217bool VirtRegAuxInfo::isLiveAtStatepointVarArg(LiveInterval &LI) {
218 return any_of(VRM.getRegInfo().reg_operands(LI.reg()),
219 [](MachineOperand &MO) {
220 MachineInstr *MI = MO.getParent();
221 if (MI->getOpcode() != TargetOpcode::STATEPOINT)
222 return false;
223 return StatepointOpers(MI).getVarIdx() <= MO.getOperandNo();
224 });
225}
226
228 float Weight = weightCalcHelper(LI);
229 // Check if unspillable.
230 if (Weight < 0)
231 return;
232 LI.setWeight(Weight);
233}
234
236 const MachineRegisterInfo &MRI) {
237 for (const MachineOperand &MO : MRI.reg_operands(LI.reg())) {
238 const MachineInstr *MI = MO.getParent();
239 if (MI->isInlineAsm() && MI->mayFoldInlineAsmRegOp(MI->getOperandNo(&MO)))
240 return true;
241 }
242
243 return false;
244}
245
247 MachineRegisterInfo &MRI = MF.getRegInfo();
248 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
249 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
250 MachineBasicBlock *MBB = nullptr;
251 float TotalWeight = 0;
252 unsigned NumInstr = 0; // Number of instructions using LI
254
255 std::pair<unsigned, Register> TargetHint = MRI.getRegAllocationHint(LI.reg());
256
257 if (LI.isSpillable()) {
258 Register Reg = LI.reg();
259 Register Original = VRM.getOriginal(Reg);
260 const LiveInterval &OrigInt = LIS.getInterval(Original);
261 // li comes from a split of OrigInt. If OrigInt was marked
262 // as not spillable, make sure the new interval is marked
263 // as not spillable as well.
264 if (!OrigInt.isSpillable())
265 LI.markNotSpillable();
266 }
267
268 // Don't recompute spill weight for an unspillable register.
269 bool IsSpillable = LI.isSpillable();
270
271 // CopyHint is a sortable hint derived from a COPY instruction.
272 struct CopyHint {
273 Register Reg;
274 float Weight;
275 bool IsCSR;
276 CopyHint(Register R, float W, bool IsCSR)
277 : Reg(R), Weight(W), IsCSR(IsCSR) {}
278 bool operator<(const CopyHint &Rhs) const {
279 // Always prefer any physreg hint.
280 if (Reg.isPhysical() != Rhs.Reg.isPhysical())
281 return Reg.isPhysical();
282 if (Weight != Rhs.Weight)
283 return (Weight > Rhs.Weight);
284 // Prefer non-CSR to CSR.
285 if (Reg.isPhysical() && IsCSR != Rhs.IsCSR)
286 return !IsCSR;
287 return Reg.id() < Rhs.Reg.id(); // Tie-breaker.
288 }
289 };
290
291 bool IsExiting = false;
294 I = MRI.reg_instr_nodbg_begin(LI.reg()),
295 E = MRI.reg_instr_nodbg_end();
296 I != E;) {
297 MachineInstr *MI = &*(I++);
298
299 NumInstr++;
300 bool identityCopy = false;
301 auto DestSrc = TII.isCopyInstr(*MI);
302 if (DestSrc) {
303 const MachineOperand *DestRegOp = DestSrc->Destination;
304 const MachineOperand *SrcRegOp = DestSrc->Source;
305 identityCopy = DestRegOp->getReg() == SrcRegOp->getReg() &&
306 DestRegOp->getSubReg() == SrcRegOp->getSubReg();
307 }
308
309 if (identityCopy || MI->isImplicitDef())
310 continue;
311 if (!Visited.insert(MI).second)
312 continue;
313
314 // For terminators that produce values, ask the backend if the register is
315 // not spillable.
316 if (TII.isUnspillableTerminator(MI) &&
317 MI->definesRegister(LI.reg(), /*TRI=*/nullptr)) {
318 LI.markNotSpillable();
319 return -1.0f;
320 }
321
322 // Force Weight onto the stack so that x86 doesn't add hidden precision.
323 stack_float_t Weight = 1.0f;
324 if (IsSpillable) {
325 // Get loop info for mi.
326 if (MI->getParent() != MBB) {
327 MBB = MI->getParent();
328 const MachineLoop *Loop = Loops.getLoopFor(MBB);
329 IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
330 }
331
332 // Calculate instr weight.
333 bool Reads, Writes;
334 std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
335 Weight = LiveIntervals::getSpillWeight(Writes, Reads, &MBFI, *MI,
336 getCachedOptimizeForSize());
337
338 // Give extra weight to what looks like a loop induction variable update.
339 if (Writes && IsExiting && LIS.isLiveOutOfMBB(LI, MBB))
340 Weight *= 3;
341
342 TotalWeight += Weight;
343 }
344
345 // Get allocation hints from copies.
346 if (!TII.isCopyInstr(*MI))
347 continue;
348 Register HintReg = copyHint(MI, LI.reg(), TRI, MRI);
349 if (HintReg && (HintReg.isVirtual() || MRI.isAllocatable(HintReg)))
350 Hint[HintReg] += Weight;
351 }
352
353 // Pass all the sorted copy hints to mri.
354 if (Hint.size()) {
355 // Remove a generic hint if previously added by target.
356 if (TargetHint.first == 0 && TargetHint.second)
357 MRI.clearSimpleHint(LI.reg());
358
359 // Don't add the target-type hint again.
360 Register SkipReg = TargetHint.first != 0 ? TargetHint.second : Register();
362 for (const auto &[Reg, Weight] : Hint) {
363 if (Reg != SkipReg)
364 RegHints.emplace_back(
365 Reg, Weight,
366 Reg.isPhysical() ? TRI.isCalleeSavedPhysReg(Reg, MF) : false);
367 }
368 sort(RegHints);
369 for (const auto &[Reg, _, __] : RegHints)
370 MRI.addRegAllocationHint(LI.reg(), Reg);
371
372 // Weakly boost the spill weight of hinted registers.
373 TotalWeight *= 1.01F;
374 }
375
376 // If the live interval was already unspillable, leave it that way.
377 if (!IsSpillable)
378 return -1.0;
379
380 // Mark li as unspillable if all live ranges are tiny and the interval
381 // is not live at any reg mask. If the interval is live at a reg mask
382 // spilling may be required. If li is live as use in statepoint instruction
383 // spilling may be required due to if we mark interval with use in statepoint
384 // as not spillable we are risky to end up with no register to allocate.
385 // At the same time STATEPOINT instruction is perfectly fine to have this
386 // operand on stack, so spilling such interval and folding its load from stack
387 // into instruction itself makes perfect sense.
388 if (LI.isZeroLength(LIS.getSlotIndexes()) &&
389 !LI.isLiveAtIndexes(LIS.getRegMaskSlots()) &&
390 !isLiveAtStatepointVarArg(LI) && !canMemFoldInlineAsm(LI, MRI)) {
391 LI.markNotSpillable();
392 return -1.0;
393 }
394
395 // If all of the definitions of the interval are re-materializable,
396 // it is a preferred candidate for spilling.
397 // FIXME: this gets much more complicated once we support non-trivial
398 // re-materialization.
399 if (isRematerializable(LI, LIS, VRM, MRI, *MF.getSubtarget().getInstrInfo()))
400 TotalWeight *= 0.5F;
401
402 // Finally, we scale the weight by the scale factor of register class.
403 const TargetRegisterClass *RC = MRI.getRegClass(LI.reg());
404 TotalWeight *= TRI.getSpillWeightScaleFactor(RC);
405
406 return normalize(TotalWeight, LI.getSize(), NumInstr);
407}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static bool canMemFoldInlineAsm(LiveInterval &LI, const MachineRegisterInfo &MRI)
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineRegisterInfo & MRI
This file defines the SmallPtrSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
void markNotSpillable()
markNotSpillable - Mark interval as not spillable
Register reg() const
bool isSpillable() const
isSpillable - Can this interval be spilled?
bool hasSubRanges() const
Returns true if subregister liveness information is available.
LLVM_ABI unsigned getSize() const
getSize - Returns the sum of sizes of all the LiveRange's.
iterator_range< subrange_iterator > subranges()
void setWeight(float Value)
static LLVM_ABI float getSpillWeight(bool isDef, bool isUse, const MachineBlockFrequencyInfo *MBFI, const MachineInstr &MI, ProfileSummaryInfo *PSI=nullptr)
Calculate the spill weight to assign to a single instruction.
Result of a LiveRange query.
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
LLVM_ABI bool isLiveAtIndexes(ArrayRef< SlotIndex > Slots) const
vni_iterator vni_begin()
bool isZeroLength(SlotIndexes *Indexes) const
Returns true if the live range is zero length, i.e.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
vni_iterator vni_end()
VNInfoList::const_iterator const_vni_iterator
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< reg_iterator > reg_operands(Register Reg) const
defusechain_instr_iterator< true, true, true, true > reg_instr_nodbg_iterator
reg_instr_nodbg_iterator/reg_instr_nodbg_begin/reg_instr_nodbg_end - Walk all defs and uses of the sp...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
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 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 getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
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.
reference emplace_back(ArgTypes &&... Args)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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...
LLVM_ABI float weightCalcHelper(LiveInterval &LI)
Helper function for weight calculations.
static LLVM_ABI bool allUsesAvailableAt(const MachineInstr *MI, SlotIndex UseIdx, const LiveIntervals &LIS, const MachineRegisterInfo &MRI, const TargetInstrInfo &TII)
LLVM_ABI void calculateSpillWeightsAndHints()
Compute spill weights and allocation hints for all virtual register live intervals.
static LLVM_ABI bool isRematerializable(const LiveInterval &LI, const LiveIntervals &LIS, const VirtRegMap &VRM, const MachineRegisterInfo &MRI, const TargetInstrInfo &TII)
Determine if all values in LI are rematerializable.
virtual float normalize(float UseDefFreq, unsigned Size, unsigned NumInstr)
Weight normalization function.
static LLVM_ABI Register copyHint(const MachineInstr *MI, Register Reg, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI)
Return the preferred allocation register for reg, given a COPY instruction.
LLVM_ABI void calculateSpillWeightAndHint(LiveInterval &LI)
(re)compute li's spill weight and allocation hint.
MachineRegisterInfo & getRegInfo() const
Definition VirtRegMap.h:78
This is an optimization pass for GlobalISel generic memory operations.
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
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
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
@ Sub
Subtraction of integers.
float stack_float_t
Type to force float point values onto the stack, so that x86 doesn't add hidden precision,...
Definition MathExtras.h:821
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
constexpr bool none() const
Definition LaneBitmask.h:52