CalcSpillWeights.cpp 10 KB

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