1 //===- CalcSpillWeights.cpp -----------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/CodeGen/CalcSpillWeights.h"
11 #include "llvm/ADT/SmallPtrSet.h"
12 #include "llvm/CodeGen/LiveInterval.h"
13 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineLoopInfo.h"
17 #include "llvm/CodeGen/MachineOperand.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/VirtRegMap.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetSubtargetInfo.h"
25 #include <cassert>
26 #include <tuple>
27 
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "calcspillweights"
31 
32 void llvm::calculateSpillWeightsAndHints(LiveIntervals &LIS,
33                            MachineFunction &MF,
34                            VirtRegMap *VRM,
35                            const MachineLoopInfo &MLI,
36                            const MachineBlockFrequencyInfo &MBFI,
37                            VirtRegAuxInfo::NormalizingFn norm) {
38   DEBUG(dbgs() << "********** Compute Spill Weights **********\n"
39                << "********** Function: " << MF.getName() << '\n');
40 
41   MachineRegisterInfo &MRI = MF.getRegInfo();
42   VirtRegAuxInfo VRAI(MF, LIS, VRM, MLI, MBFI, norm);
43   for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
44     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
45     if (MRI.reg_nodbg_empty(Reg))
46       continue;
47     VRAI.calculateSpillWeightAndHint(LIS.getInterval(Reg));
48   }
49 }
50 
51 // Return the preferred allocation register for reg, given a COPY instruction.
52 static unsigned copyHint(const MachineInstr *mi, unsigned reg,
53                          const TargetRegisterInfo &tri,
54                          const MachineRegisterInfo &mri) {
55   unsigned sub, hreg, hsub;
56   if (mi->getOperand(0).getReg() == reg) {
57     sub = mi->getOperand(0).getSubReg();
58     hreg = mi->getOperand(1).getReg();
59     hsub = mi->getOperand(1).getSubReg();
60   } else {
61     sub = mi->getOperand(1).getSubReg();
62     hreg = mi->getOperand(0).getReg();
63     hsub = mi->getOperand(0).getSubReg();
64   }
65 
66   if (!hreg)
67     return 0;
68 
69   if (TargetRegisterInfo::isVirtualRegister(hreg))
70     return sub == hsub ? hreg : 0;
71 
72   const TargetRegisterClass *rc = mri.getRegClass(reg);
73 
74   // Only allow physreg hints in rc.
75   if (sub == 0)
76     return rc->contains(hreg) ? hreg : 0;
77 
78   // reg:sub should match the physreg hreg.
79   return tri.getMatchingSuperReg(hreg, sub, rc);
80 }
81 
82 // Check if all values in LI are rematerializable
83 static bool isRematerializable(const LiveInterval &LI,
84                                const LiveIntervals &LIS,
85                                VirtRegMap *VRM,
86                                const TargetInstrInfo &TII) {
87   unsigned Reg = LI.reg;
88   unsigned Original = VRM ? VRM->getOriginal(Reg) : 0;
89   for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
90        I != E; ++I) {
91     const VNInfo *VNI = *I;
92     if (VNI->isUnused())
93       continue;
94     if (VNI->isPHIDef())
95       return false;
96 
97     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
98     assert(MI && "Dead valno in interval");
99 
100     // Trace copies introduced by live range splitting.  The inline
101     // spiller can rematerialize through these copies, so the spill
102     // weight must reflect this.
103     if (VRM) {
104       while (MI->isFullCopy()) {
105         // The copy destination must match the interval register.
106         if (MI->getOperand(0).getReg() != Reg)
107           return false;
108 
109         // Get the source register.
110         Reg = MI->getOperand(1).getReg();
111 
112         // If the original (pre-splitting) registers match this
113         // copy came from a split.
114         if (!TargetRegisterInfo::isVirtualRegister(Reg) ||
115             VRM->getOriginal(Reg) != Original)
116           return false;
117 
118         // Follow the copy live-in value.
119         const LiveInterval &SrcLI = LIS.getInterval(Reg);
120         LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
121         VNI = SrcQ.valueIn();
122         assert(VNI && "Copy from non-existing value");
123         if (VNI->isPHIDef())
124           return false;
125         MI = LIS.getInstructionFromIndex(VNI->def);
126         assert(MI && "Dead valno in interval");
127       }
128     }
129 
130     if (!TII.isTriviallyReMaterializable(*MI, LIS.getAliasAnalysis()))
131       return false;
132   }
133   return true;
134 }
135 
136 void
137 VirtRegAuxInfo::calculateSpillWeightAndHint(LiveInterval &li) {
138   MachineRegisterInfo &mri = MF.getRegInfo();
139   const TargetRegisterInfo &tri = *MF.getSubtarget().getRegisterInfo();
140   MachineBasicBlock *mbb = nullptr;
141   MachineLoop *loop = nullptr;
142   bool isExiting = false;
143   float totalWeight = 0;
144   unsigned numInstr = 0; // Number of instructions using li
145   SmallPtrSet<MachineInstr*, 8> visited;
146 
147   // Find the best physreg hint and the best virtreg hint.
148   float bestPhys = 0, bestVirt = 0;
149   unsigned hintPhys = 0, hintVirt = 0;
150 
151   // Don't recompute a target specific hint.
152   bool noHint = mri.getRegAllocationHint(li.reg).first != 0;
153 
154   // Don't recompute spill weight for an unspillable register.
155   bool Spillable = li.isSpillable();
156 
157   for (MachineRegisterInfo::reg_instr_iterator
158        I = mri.reg_instr_begin(li.reg), E = mri.reg_instr_end();
159        I != E; ) {
160     MachineInstr *mi = &*(I++);
161     numInstr++;
162     if (mi->isIdentityCopy() || mi->isImplicitDef() || mi->isDebugValue())
163       continue;
164     if (!visited.insert(mi).second)
165       continue;
166 
167     float weight = 1.0f;
168     if (Spillable) {
169       // Get loop info for mi.
170       if (mi->getParent() != mbb) {
171         mbb = mi->getParent();
172         loop = Loops.getLoopFor(mbb);
173         isExiting = loop ? loop->isLoopExiting(mbb) : false;
174       }
175 
176       // Calculate instr weight.
177       bool reads, writes;
178       std::tie(reads, writes) = mi->readsWritesVirtualRegister(li.reg);
179       weight = LiveIntervals::getSpillWeight(writes, reads, &MBFI, *mi);
180 
181       // Give extra weight to what looks like a loop induction variable update.
182       if (writes && isExiting && LIS.isLiveOutOfMBB(li, mbb))
183         weight *= 3;
184 
185       totalWeight += weight;
186     }
187 
188     // Get allocation hints from copies.
189     if (noHint || !mi->isCopy())
190       continue;
191     unsigned hint = copyHint(mi, li.reg, tri, mri);
192     if (!hint)
193       continue;
194     // Force hweight onto the stack so that x86 doesn't add hidden precision,
195     // making the comparison incorrectly pass (i.e., 1 > 1 == true??).
196     //
197     // FIXME: we probably shouldn't use floats at all.
198     volatile float hweight = Hint[hint] += weight;
199     if (TargetRegisterInfo::isPhysicalRegister(hint)) {
200       if (hweight > bestPhys && mri.isAllocatable(hint)) {
201         bestPhys = hweight;
202         hintPhys = hint;
203       }
204     } else {
205       if (hweight > bestVirt) {
206         bestVirt = hweight;
207         hintVirt = hint;
208       }
209     }
210   }
211 
212   Hint.clear();
213 
214   // Always prefer the physreg hint.
215   if (unsigned hint = hintPhys ? hintPhys : hintVirt) {
216     mri.setRegAllocationHint(li.reg, 0, hint);
217     // Weakly boost the spill weight of hinted registers.
218     totalWeight *= 1.01F;
219   }
220 
221   // If the live interval was already unspillable, leave it that way.
222   if (!Spillable)
223     return;
224 
225   // Mark li as unspillable if all live ranges are tiny and the interval
226   // is not live at any reg mask.  If the interval is live at a reg mask
227   // spilling may be required.
228   if (li.isZeroLength(LIS.getSlotIndexes()) &&
229       !li.isLiveAtIndexes(LIS.getRegMaskSlots())) {
230     li.markNotSpillable();
231     return;
232   }
233 
234   // If all of the definitions of the interval are re-materializable,
235   // it is a preferred candidate for spilling.
236   // FIXME: this gets much more complicated once we support non-trivial
237   // re-materialization.
238   if (isRematerializable(li, LIS, VRM, *MF.getSubtarget().getInstrInfo()))
239     totalWeight *= 0.5F;
240 
241   li.weight = normalize(totalWeight, li.getSize(), numInstr);
242 }
243