1//===-- llvm/CodeGen/AsmPrinter/DbgValueHistoryCalculator.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 "DbgValueHistoryCalculator.h"
11#include "llvm/ADT/SmallVector.h"
12#include "llvm/CodeGen/MachineBasicBlock.h"
13#include "llvm/CodeGen/MachineFunction.h"
14#include "llvm/Support/Debug.h"
15#include "llvm/Target/TargetRegisterInfo.h"
16#include <algorithm>
17#include <map>
18#include <set>
19
20#define DEBUG_TYPE "dwarfdebug"
21
22namespace llvm {
23
24// \brief If @MI is a DBG_VALUE with debug value described by a
25// defined register, returns the number of this register.
26// In the other case, returns 0.
27static unsigned isDescribedByReg(const MachineInstr &MI) {
28  assert(MI.isDebugValue());
29  assert(MI.getNumOperands() == 3);
30  // If location of variable is described using a register (directly or
31  // indirecltly), this register is always a first operand.
32  return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
33}
34
35void DbgValueHistoryMap::startInstrRange(const MDNode *Var,
36                                         const MachineInstr &MI) {
37  // Instruction range should start with a DBG_VALUE instruction for the
38  // variable.
39  assert(MI.isDebugValue() && MI.getDebugVariable() == Var);
40  auto &Ranges = VarInstrRanges[Var];
41  if (!Ranges.empty() && Ranges.back().second == nullptr &&
42      Ranges.back().first->isIdenticalTo(&MI)) {
43    DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
44                 << "\t" << Ranges.back().first << "\t" << MI << "\n");
45    return;
46  }
47  Ranges.push_back(std::make_pair(&MI, nullptr));
48}
49
50void DbgValueHistoryMap::endInstrRange(const MDNode *Var,
51                                       const MachineInstr &MI) {
52  auto &Ranges = VarInstrRanges[Var];
53  // Verify that the current instruction range is not yet closed.
54  assert(!Ranges.empty() && Ranges.back().second == nullptr);
55  // For now, instruction ranges are not allowed to cross basic block
56  // boundaries.
57  assert(Ranges.back().first->getParent() == MI.getParent());
58  Ranges.back().second = &MI;
59}
60
61unsigned DbgValueHistoryMap::getRegisterForVar(const MDNode *Var) const {
62  const auto &I = VarInstrRanges.find(Var);
63  if (I == VarInstrRanges.end())
64    return 0;
65  const auto &Ranges = I->second;
66  if (Ranges.empty() || Ranges.back().second != nullptr)
67    return 0;
68  return isDescribedByReg(*Ranges.back().first);
69}
70
71namespace {
72// Maps physreg numbers to the variables they describe.
73typedef std::map<unsigned, SmallVector<const MDNode *, 1>> RegDescribedVarsMap;
74}
75
76// \brief Claim that @Var is not described by @RegNo anymore.
77static void dropRegDescribedVar(RegDescribedVarsMap &RegVars,
78                                unsigned RegNo, const MDNode *Var) {
79  const auto &I = RegVars.find(RegNo);
80  assert(RegNo != 0U && I != RegVars.end());
81  auto &VarSet = I->second;
82  const auto &VarPos = std::find(VarSet.begin(), VarSet.end(), Var);
83  assert(VarPos != VarSet.end());
84  VarSet.erase(VarPos);
85  // Don't keep empty sets in a map to keep it as small as possible.
86  if (VarSet.empty())
87    RegVars.erase(I);
88}
89
90// \brief Claim that @Var is now described by @RegNo.
91static void addRegDescribedVar(RegDescribedVarsMap &RegVars,
92                               unsigned RegNo, const MDNode *Var) {
93  assert(RegNo != 0U);
94  auto &VarSet = RegVars[RegNo];
95  assert(std::find(VarSet.begin(), VarSet.end(), Var) == VarSet.end());
96  VarSet.push_back(Var);
97}
98
99// \brief Terminate the location range for variables described by register
100// @RegNo by inserting @ClobberingInstr to their history.
101static void clobberRegisterUses(RegDescribedVarsMap &RegVars, unsigned RegNo,
102                                DbgValueHistoryMap &HistMap,
103                                const MachineInstr &ClobberingInstr) {
104  const auto &I = RegVars.find(RegNo);
105  if (I == RegVars.end())
106    return;
107  // Iterate over all variables described by this register and add this
108  // instruction to their history, clobbering it.
109  for (const auto &Var : I->second)
110    HistMap.endInstrRange(Var, ClobberingInstr);
111  RegVars.erase(I);
112}
113
114// \brief Collect all registers clobbered by @MI and insert them to @Regs.
115static void collectClobberedRegisters(const MachineInstr &MI,
116                                      const TargetRegisterInfo *TRI,
117                                      std::set<unsigned> &Regs) {
118  for (const MachineOperand &MO : MI.operands()) {
119    if (!MO.isReg() || !MO.isDef() || !MO.getReg())
120      continue;
121    for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
122      Regs.insert(*AI);
123  }
124}
125
126// \brief Returns the first instruction in @MBB which corresponds to
127// the function epilogue, or nullptr if @MBB doesn't contain an epilogue.
128static const MachineInstr *getFirstEpilogueInst(const MachineBasicBlock &MBB) {
129  auto LastMI = MBB.getLastNonDebugInstr();
130  if (LastMI == MBB.end() || !LastMI->isReturn())
131    return nullptr;
132  // Assume that epilogue starts with instruction having the same debug location
133  // as the return instruction.
134  DebugLoc LastLoc = LastMI->getDebugLoc();
135  auto Res = LastMI;
136  for (MachineBasicBlock::const_reverse_iterator I(std::next(LastMI)); I != MBB.rend();
137       ++I) {
138    if (I->getDebugLoc() != LastLoc)
139      return Res;
140    Res = std::prev(I.base());
141  }
142  // If all instructions have the same debug location, assume whole MBB is
143  // an epilogue.
144  return MBB.begin();
145}
146
147// \brief Collect registers that are modified in the function body (their
148// contents is changed only in the prologue and epilogue).
149static void collectChangingRegs(const MachineFunction *MF,
150                                const TargetRegisterInfo *TRI,
151                                std::set<unsigned> &Regs) {
152  for (const auto &MBB : *MF) {
153    auto FirstEpilogueInst = getFirstEpilogueInst(MBB);
154    bool IsInEpilogue = false;
155    for (const auto &MI : MBB) {
156      IsInEpilogue |= &MI == FirstEpilogueInst;
157      if (!MI.getFlag(MachineInstr::FrameSetup) && !IsInEpilogue)
158        collectClobberedRegisters(MI, TRI, Regs);
159    }
160  }
161}
162
163void calculateDbgValueHistory(const MachineFunction *MF,
164                              const TargetRegisterInfo *TRI,
165                              DbgValueHistoryMap &Result) {
166  std::set<unsigned> ChangingRegs;
167  collectChangingRegs(MF, TRI, ChangingRegs);
168
169  RegDescribedVarsMap RegVars;
170  for (const auto &MBB : *MF) {
171    for (const auto &MI : MBB) {
172      if (!MI.isDebugValue()) {
173        // Not a DBG_VALUE instruction. It may clobber registers which describe
174        // some variables.
175        std::set<unsigned> MIClobberedRegs;
176        collectClobberedRegisters(MI, TRI, MIClobberedRegs);
177        for (unsigned RegNo : MIClobberedRegs) {
178          if (ChangingRegs.count(RegNo))
179            clobberRegisterUses(RegVars, RegNo, Result, MI);
180        }
181        continue;
182      }
183
184      assert(MI.getNumOperands() > 1 && "Invalid DBG_VALUE instruction!");
185      const MDNode *Var = MI.getDebugVariable();
186
187      if (unsigned PrevReg = Result.getRegisterForVar(Var))
188        dropRegDescribedVar(RegVars, PrevReg, Var);
189
190      Result.startInstrRange(Var, MI);
191
192      if (unsigned NewReg = isDescribedByReg(MI))
193        addRegDescribedVar(RegVars, NewReg, Var);
194    }
195
196    // Make sure locations for register-described variables are valid only
197    // until the end of the basic block (unless it's the last basic block, in
198    // which case let their liveness run off to the end of the function).
199    if (!MBB.empty() &&  &MBB != &MF->back()) {
200      for (unsigned RegNo : ChangingRegs)
201        clobberRegisterUses(RegVars, RegNo, Result, MBB.back());
202    }
203  }
204}
205
206}
207