CalcSpillWeights.cpp revision 8112b5322ef60c2dc3cbf0c05671de76df31cf02
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#define DEBUG_TYPE "calcspillweights"
11
12#include "llvm/Function.h"
13#include "llvm/ADT/SmallSet.h"
14#include "llvm/CodeGen/CalcSpillWeights.h"
15#include "llvm/CodeGen/LiveIntervalAnalysis.h"
16#include "llvm/CodeGen/MachineFunction.h"
17#include "llvm/CodeGen/MachineLoopInfo.h"
18#include "llvm/CodeGen/MachineRegisterInfo.h"
19#include "llvm/CodeGen/SlotIndexes.h"
20#include "llvm/Support/Debug.h"
21#include "llvm/Support/raw_ostream.h"
22#include "llvm/Target/TargetInstrInfo.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetRegisterInfo.h"
25#include "llvm/Target/TargetMachine.h"
26using namespace llvm;
27
28char CalculateSpillWeights::ID = 0;
29static RegisterPass<CalculateSpillWeights> X("calcspillweights",
30                                             "Calculate spill weights");
31
32void CalculateSpillWeights::getAnalysisUsage(AnalysisUsage &au) const {
33  au.addRequired<LiveIntervals>();
34  au.addRequired<MachineLoopInfo>();
35  au.setPreservesAll();
36  MachineFunctionPass::getAnalysisUsage(au);
37}
38
39bool CalculateSpillWeights::runOnMachineFunction(MachineFunction &fn) {
40
41  DEBUG(dbgs() << "********** Compute Spill Weights **********\n"
42               << "********** Function: "
43               << fn.getFunction()->getName() << '\n');
44
45  LiveIntervals *lis = &getAnalysis<LiveIntervals>();
46  MachineLoopInfo *loopInfo = &getAnalysis<MachineLoopInfo>();
47  const TargetInstrInfo *tii = fn.getTarget().getInstrInfo();
48  MachineRegisterInfo *mri = &fn.getRegInfo();
49
50  SmallSet<unsigned, 4> processed;
51  for (MachineFunction::iterator mbbi = fn.begin(), mbbe = fn.end();
52       mbbi != mbbe; ++mbbi) {
53    MachineBasicBlock* mbb = mbbi;
54    SlotIndex mbbEnd = lis->getMBBEndIdx(mbb);
55    MachineLoop* loop = loopInfo->getLoopFor(mbb);
56    unsigned loopDepth = loop ? loop->getLoopDepth() : 0;
57    bool isExiting = loop ? loop->isLoopExiting(mbb) : false;
58
59    for (MachineBasicBlock::const_iterator mii = mbb->begin(), mie = mbb->end();
60         mii != mie; ++mii) {
61      const MachineInstr *mi = mii;
62      if (tii->isIdentityCopy(*mi) || mi->isImplicitDef() || mi->isDebugValue())
63        continue;
64
65      for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
66        const MachineOperand &mopi = mi->getOperand(i);
67        if (!mopi.isReg() || mopi.getReg() == 0)
68          continue;
69        unsigned reg = mopi.getReg();
70        if (!TargetRegisterInfo::isVirtualRegister(mopi.getReg()))
71          continue;
72        // Multiple uses of reg by the same instruction. It should not
73        // contribute to spill weight again.
74        if (!processed.insert(reg))
75          continue;
76
77        bool hasDef = mopi.isDef();
78        bool hasUse = !hasDef;
79        for (unsigned j = i+1; j != e; ++j) {
80          const MachineOperand &mopj = mi->getOperand(j);
81          if (!mopj.isReg() || mopj.getReg() != reg)
82            continue;
83          hasDef |= mopj.isDef();
84          hasUse |= mopj.isUse();
85          if (hasDef && hasUse)
86            break;
87        }
88
89        LiveInterval &regInt = lis->getInterval(reg);
90        float weight = lis->getSpillWeight(hasDef, hasUse, loopDepth);
91        if (hasDef && isExiting) {
92          // Looks like this is a loop count variable update.
93          SlotIndex defIdx = lis->getInstructionIndex(mi).getDefIndex();
94          const LiveRange *dlr =
95            lis->getInterval(reg).getLiveRangeContaining(defIdx);
96          if (dlr->end >= mbbEnd)
97            weight *= 3.0F;
98        }
99        regInt.weight += weight;
100      }
101      processed.clear();
102    }
103  }
104
105  for (LiveIntervals::iterator I = lis->begin(), E = lis->end(); I != E; ++I) {
106    LiveInterval &li = *I->second;
107    if (TargetRegisterInfo::isVirtualRegister(li.reg)) {
108      // If the live interval length is essentially zero, i.e. in every live
109      // range the use follows def immediately, it doesn't make sense to spill
110      // it and hope it will be easier to allocate for this li.
111      if (isZeroLengthInterval(&li)) {
112        li.weight = HUGE_VALF;
113        continue;
114      }
115
116      bool isLoad = false;
117      SmallVector<LiveInterval*, 4> spillIs;
118      if (lis->isReMaterializable(li, spillIs, isLoad)) {
119        // If all of the definitions of the interval are re-materializable,
120        // it is a preferred candidate for spilling. If non of the defs are
121        // loads, then it's potentially very cheap to re-materialize.
122        // FIXME: this gets much more complicated once we support non-trivial
123        // re-materialization.
124        if (isLoad)
125          li.weight *= 0.9F;
126        else
127          li.weight *= 0.5F;
128      }
129
130      // Slightly prefer live interval that has been assigned a preferred reg.
131      std::pair<unsigned, unsigned> Hint = mri->getRegAllocationHint(li.reg);
132      if (Hint.first || Hint.second)
133        li.weight *= 1.01F;
134
135      // Divide the weight of the interval by its size.  This encourages
136      // spilling of intervals that are large and have few uses, and
137      // discourages spilling of small intervals with many uses.
138      li.weight /= lis->getApproximateInstructionCount(li) * SlotIndex::NUM;
139    }
140  }
141
142  return false;
143}
144
145/// Returns true if the given live interval is zero length.
146bool CalculateSpillWeights::isZeroLengthInterval(LiveInterval *li) const {
147  for (LiveInterval::Ranges::const_iterator
148       i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
149    if (i->end.getPrevIndex() > i->start)
150      return false;
151  return true;
152}
153