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 
9 #include "llvm/CodeGen/CalcSpillWeights.h"
10 #include "llvm/ADT/SmallPtrSet.h"
11 #include "llvm/CodeGen/LiveInterval.h"
12 #include "llvm/CodeGen/LiveIntervals.h"
13 #include "llvm/CodeGen/MachineFunction.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/CodeGen/MachineLoopInfo.h"
16 #include "llvm/CodeGen/MachineOperand.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetInstrInfo.h"
19 #include "llvm/CodeGen/TargetRegisterInfo.h"
20 #include "llvm/CodeGen/TargetSubtargetInfo.h"
21 #include "llvm/CodeGen/VirtRegMap.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <cassert>
25 #include <tuple>
26 
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "calcspillweights"
30 
31 void VirtRegAuxInfo::calculateSpillWeightsAndHints() {
32   LLVM_DEBUG(dbgs() << "********** Compute Spill Weights **********\n"
33                     << "********** Function: " << MF.getName() << '\n');
34 
35   MachineRegisterInfo &MRI = MF.getRegInfo();
36   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
37     unsigned Reg = Register::index2VirtReg(I);
38     if (MRI.reg_nodbg_empty(Reg))
39       continue;
40     calculateSpillWeightAndHint(LIS.getInterval(Reg));
41   }
42 }
43 
44 // Return the preferred allocation register for reg, given a COPY instruction.
45 static Register copyHint(const MachineInstr *mi, unsigned reg,
46                          const TargetRegisterInfo &tri,
47                          const MachineRegisterInfo &mri) {
48   unsigned sub, hsub;
49   Register hreg;
50   if (mi->getOperand(0).getReg() == reg) {
51     sub = mi->getOperand(0).getSubReg();
52     hreg = mi->getOperand(1).getReg();
53     hsub = mi->getOperand(1).getSubReg();
54   } else {
55     sub = mi->getOperand(1).getSubReg();
56     hreg = mi->getOperand(0).getReg();
57     hsub = mi->getOperand(0).getSubReg();
58   }
59 
60   if (!hreg)
61     return 0;
62 
63   if (Register::isVirtualRegister(hreg))
64     return sub == hsub ? hreg : Register();
65 
66   const TargetRegisterClass *rc = mri.getRegClass(reg);
67   Register CopiedPReg = (hsub ? tri.getSubReg(hreg, hsub) : hreg);
68   if (rc->contains(CopiedPReg))
69     return CopiedPReg;
70 
71   // Check if reg:sub matches so that a super register could be hinted.
72   if (sub)
73     return tri.getMatchingSuperReg(CopiedPReg, sub, rc);
74 
75   return 0;
76 }
77 
78 // Check if all values in LI are rematerializable
79 static bool isRematerializable(const LiveInterval &LI,
80                                const LiveIntervals &LIS,
81                                VirtRegMap *VRM,
82                                const TargetInstrInfo &TII) {
83   unsigned Reg = LI.reg();
84   unsigned Original = VRM ? VRM->getOriginal(Reg) : 0;
85   for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
86        I != E; ++I) {
87     const VNInfo *VNI = *I;
88     if (VNI->isUnused())
89       continue;
90     if (VNI->isPHIDef())
91       return false;
92 
93     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
94     assert(MI && "Dead valno in interval");
95 
96     // Trace copies introduced by live range splitting.  The inline
97     // spiller can rematerialize through these copies, so the spill
98     // weight must reflect this.
99     if (VRM) {
100       while (MI->isFullCopy()) {
101         // The copy destination must match the interval register.
102         if (MI->getOperand(0).getReg() != Reg)
103           return false;
104 
105         // Get the source register.
106         Reg = MI->getOperand(1).getReg();
107 
108         // If the original (pre-splitting) registers match this
109         // copy came from a split.
110         if (!Register::isVirtualRegister(Reg) ||
111             VRM->getOriginal(Reg) != Original)
112           return false;
113 
114         // Follow the copy live-in value.
115         const LiveInterval &SrcLI = LIS.getInterval(Reg);
116         LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
117         VNI = SrcQ.valueIn();
118         assert(VNI && "Copy from non-existing value");
119         if (VNI->isPHIDef())
120           return false;
121         MI = LIS.getInstructionFromIndex(VNI->def);
122         assert(MI && "Dead valno in interval");
123       }
124     }
125 
126     if (!TII.isTriviallyReMaterializable(*MI, LIS.getAliasAnalysis()))
127       return false;
128   }
129   return true;
130 }
131 
132 void VirtRegAuxInfo::calculateSpillWeightAndHint(LiveInterval &li) {
133   float weight = weightCalcHelper(li);
134   // Check if unspillable.
135   if (weight < 0)
136     return;
137   li.setWeight(weight);
138 }
139 
140 float VirtRegAuxInfo::futureWeight(LiveInterval &li, SlotIndex start,
141                                    SlotIndex end) {
142   return weightCalcHelper(li, &start, &end);
143 }
144 
145 float VirtRegAuxInfo::weightCalcHelper(LiveInterval &li, SlotIndex *start,
146                                        SlotIndex *end) {
147   MachineRegisterInfo &mri = MF.getRegInfo();
148   const TargetRegisterInfo &tri = *MF.getSubtarget().getRegisterInfo();
149   MachineBasicBlock *mbb = nullptr;
150   MachineLoop *loop = nullptr;
151   bool isExiting = false;
152   float totalWeight = 0;
153   unsigned numInstr = 0; // Number of instructions using li
154   SmallPtrSet<MachineInstr*, 8> visited;
155 
156   std::pair<unsigned, unsigned> TargetHint = mri.getRegAllocationHint(li.reg());
157 
158   if (li.isSpillable() && VRM) {
159     Register Reg = li.reg();
160     Register Original = VRM->getOriginal(Reg);
161     const LiveInterval &OrigInt = LIS.getInterval(Original);
162     // li comes from a split of OrigInt. If OrigInt was marked
163     // as not spillable, make sure the new interval is marked
164     // as not spillable as well.
165     if (!OrigInt.isSpillable())
166       li.markNotSpillable();
167   }
168 
169   // Don't recompute spill weight for an unspillable register.
170   bool Spillable = li.isSpillable();
171 
172   bool localSplitArtifact = start && end;
173 
174   // Do not update future local split artifacts.
175   bool updateLI = !localSplitArtifact;
176 
177   if (localSplitArtifact) {
178     MachineBasicBlock *localMBB = LIS.getMBBFromIndex(*end);
179     assert(localMBB == LIS.getMBBFromIndex(*start) &&
180            "start and end are expected to be in the same basic block");
181 
182     // Local split artifact will have 2 additional copy instructions and they
183     // will be in the same BB.
184     // localLI = COPY other
185     // ...
186     // other   = COPY localLI
187     totalWeight += LiveIntervals::getSpillWeight(true, false, &MBFI, localMBB);
188     totalWeight += LiveIntervals::getSpillWeight(false, true, &MBFI, localMBB);
189 
190     numInstr += 2;
191   }
192 
193   // CopyHint is a sortable hint derived from a COPY instruction.
194   struct CopyHint {
195     unsigned Reg;
196     float Weight;
197     bool IsPhys;
198     CopyHint(unsigned R, float W, bool P) :
199       Reg(R), Weight(W), IsPhys(P) {}
200     bool operator<(const CopyHint &rhs) const {
201       // Always prefer any physreg hint.
202       if (IsPhys != rhs.IsPhys)
203         return (IsPhys && !rhs.IsPhys);
204       if (Weight != rhs.Weight)
205         return (Weight > rhs.Weight);
206       return Reg < rhs.Reg; // Tie-breaker.
207     }
208   };
209   std::set<CopyHint> CopyHints;
210 
211   for (MachineRegisterInfo::reg_instr_nodbg_iterator
212            I = mri.reg_instr_nodbg_begin(li.reg()),
213            E = mri.reg_instr_nodbg_end();
214        I != E;) {
215     MachineInstr *mi = &*(I++);
216 
217     // For local split artifacts, we are interested only in instructions between
218     // the expected start and end of the range.
219     SlotIndex si = LIS.getInstructionIndex(*mi);
220     if (localSplitArtifact && ((si < *start) || (si > *end)))
221       continue;
222 
223     numInstr++;
224     if (mi->isIdentityCopy() || mi->isImplicitDef())
225       continue;
226     if (!visited.insert(mi).second)
227       continue;
228 
229     float weight = 1.0f;
230     if (Spillable) {
231       // Get loop info for mi.
232       if (mi->getParent() != mbb) {
233         mbb = mi->getParent();
234         loop = Loops.getLoopFor(mbb);
235         isExiting = loop ? loop->isLoopExiting(mbb) : false;
236       }
237 
238       // Calculate instr weight.
239       bool reads, writes;
240       std::tie(reads, writes) = mi->readsWritesVirtualRegister(li.reg());
241       weight = LiveIntervals::getSpillWeight(writes, reads, &MBFI, *mi);
242 
243       // Give extra weight to what looks like a loop induction variable update.
244       if (writes && isExiting && LIS.isLiveOutOfMBB(li, mbb))
245         weight *= 3;
246 
247       totalWeight += weight;
248     }
249 
250     // Get allocation hints from copies.
251     if (!mi->isCopy())
252       continue;
253     Register hint = copyHint(mi, li.reg(), tri, mri);
254     if (!hint)
255       continue;
256     // Force hweight onto the stack so that x86 doesn't add hidden precision,
257     // making the comparison incorrectly pass (i.e., 1 > 1 == true??).
258     //
259     // FIXME: we probably shouldn't use floats at all.
260     volatile float hweight = Hint[hint] += weight;
261     if (Register::isVirtualRegister(hint) || mri.isAllocatable(hint))
262       CopyHints.insert(
263           CopyHint(hint, hweight, Register::isPhysicalRegister(hint)));
264   }
265 
266   Hint.clear();
267 
268   // Pass all the sorted copy hints to mri.
269   if (updateLI && CopyHints.size()) {
270     // Remove a generic hint if previously added by target.
271     if (TargetHint.first == 0 && TargetHint.second)
272       mri.clearSimpleHint(li.reg());
273 
274     std::set<unsigned> HintedRegs;
275     for (auto &Hint : CopyHints) {
276       if (!HintedRegs.insert(Hint.Reg).second ||
277           (TargetHint.first != 0 && Hint.Reg == TargetHint.second))
278         // Don't add the same reg twice or the target-type hint again.
279         continue;
280       mri.addRegAllocationHint(li.reg(), Hint.Reg);
281     }
282 
283     // Weakly boost the spill weight of hinted registers.
284     totalWeight *= 1.01F;
285   }
286 
287   // If the live interval was already unspillable, leave it that way.
288   if (!Spillable)
289     return -1.0;
290 
291   // Mark li as unspillable if all live ranges are tiny and the interval
292   // is not live at any reg mask.  If the interval is live at a reg mask
293   // spilling may be required.
294   if (updateLI && li.isZeroLength(LIS.getSlotIndexes()) &&
295       !li.isLiveAtIndexes(LIS.getRegMaskSlots())) {
296     li.markNotSpillable();
297     return -1.0;
298   }
299 
300   // If all of the definitions of the interval are re-materializable,
301   // it is a preferred candidate for spilling.
302   // FIXME: this gets much more complicated once we support non-trivial
303   // re-materialization.
304   if (isRematerializable(li, LIS, VRM, *MF.getSubtarget().getInstrInfo()))
305     totalWeight *= 0.5F;
306 
307   if (localSplitArtifact)
308     return normalize(totalWeight, start->distance(*end), numInstr);
309   return normalize(totalWeight, li.getSize(), numInstr);
310 }
311