blob: f956974b1aafee9cc011aed41b21535d2dac05a5 [file] [log] [blame]
Vikram TV859ad292015-12-16 11:09:48 +00001//===------ LiveDebugValues.cpp - Tracking Debug Value MIs ----------------===//
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/// This pass implements a data flow analysis that propagates debug location
11/// information by inserting additional DBG_VALUE instructions into the machine
12/// instruction stream. The pass internally builds debug location liveness
13/// ranges to determine the points where additional DBG_VALUEs need to be
14/// inserted.
15///
16/// This is a separate pass from DbgValueHistoryCalculator to facilitate
17/// testing and improve modularity.
18///
19//===----------------------------------------------------------------------===//
20
Daniel Berlin72560592016-01-10 18:08:32 +000021#include "llvm/ADT/PostOrderIterator.h"
22#include "llvm/ADT/SmallPtrSet.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000023#include "llvm/ADT/SparseBitVector.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000024#include "llvm/ADT/Statistic.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000025#include "llvm/ADT/UniqueVector.h"
Adrian Prantl7f5866c2016-09-28 17:51:14 +000026#include "llvm/CodeGen/LexicalScopes.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000027#include "llvm/CodeGen/MachineFrameInfo.h"
Vikram TV859ad292015-12-16 11:09:48 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000031#include "llvm/CodeGen/MachineMemOperand.h"
Vikram TV859ad292015-12-16 11:09:48 +000032#include "llvm/CodeGen/Passes.h"
Reid Kleckner28865802016-04-14 18:29:59 +000033#include "llvm/IR/DebugInfo.h"
Vikram TV859ad292015-12-16 11:09:48 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000036#include "llvm/Target/TargetFrameLowering.h"
Vikram TV859ad292015-12-16 11:09:48 +000037#include "llvm/Target/TargetInstrInfo.h"
Reid Klecknerf6f04f82016-03-25 17:54:46 +000038#include "llvm/Target/TargetLowering.h"
Vikram TV859ad292015-12-16 11:09:48 +000039#include "llvm/Target/TargetRegisterInfo.h"
40#include "llvm/Target/TargetSubtargetInfo.h"
Vikram TV859ad292015-12-16 11:09:48 +000041#include <list>
Mehdi Aminib550cb12016-04-18 09:17:29 +000042#include <queue>
Vikram TV859ad292015-12-16 11:09:48 +000043
44using namespace llvm;
45
46#define DEBUG_TYPE "live-debug-values"
47
48STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
49
50namespace {
51
Adrian Prantl6ee02c72016-05-25 22:21:12 +000052// \brief If @MI is a DBG_VALUE with debug value described by a defined
53// register, returns the number of this register. In the other case, returns 0.
Adrian Prantl00698732016-05-25 22:37:29 +000054static unsigned isDbgValueDescribedByReg(const MachineInstr &MI) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +000055 assert(MI.isDebugValue() && "expected a DBG_VALUE");
56 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
57 // If location of variable is described using a register (directly
58 // or indirectly), this register is always a first operand.
59 return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
60}
61
Vikram TV859ad292015-12-16 11:09:48 +000062class LiveDebugValues : public MachineFunctionPass {
63
64private:
65 const TargetRegisterInfo *TRI;
66 const TargetInstrInfo *TII;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000067 const TargetFrameLowering *TFI;
Adrian Prantl7f5866c2016-09-28 17:51:14 +000068 LexicalScopes LS;
69
70 /// Keeps track of lexical scopes associated with a user value's source
71 /// location.
72 class UserValueScopes {
73 DebugLoc DL;
74 LexicalScopes &LS;
75 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
76
77 public:
78 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
79
80 /// Return true if current scope dominates at least one machine
81 /// instruction in a given machine basic block.
82 bool dominates(MachineBasicBlock *MBB) {
83 if (LBlocks.empty())
84 LS.getMachineBasicBlocks(DL, LBlocks);
85 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
86 }
87 };
Vikram TV859ad292015-12-16 11:09:48 +000088
Adrian Prantl7509d542016-05-26 21:42:47 +000089 /// Based on std::pair so it can be used as an index into a DenseMap.
Vikram TV859ad292015-12-16 11:09:48 +000090 typedef std::pair<const DILocalVariable *, const DILocation *>
Adrian Prantl7509d542016-05-26 21:42:47 +000091 DebugVariableBase;
Vikram TV859ad292015-12-16 11:09:48 +000092 /// A potentially inlined instance of a variable.
Adrian Prantl7509d542016-05-26 21:42:47 +000093 struct DebugVariable : public DebugVariableBase {
94 DebugVariable(const DILocalVariable *Var, const DILocation *InlinedAt)
95 : DebugVariableBase(Var, InlinedAt) {}
Vikram TV859ad292015-12-16 11:09:48 +000096
Adrian Prantl7509d542016-05-26 21:42:47 +000097 const DILocalVariable *getVar() const { return this->first; };
98 const DILocation *getInlinedAt() const { return this->second; };
Vikram TV859ad292015-12-16 11:09:48 +000099
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000100 bool operator<(const DebugVariable &DV) const {
Adrian Prantl7509d542016-05-26 21:42:47 +0000101 if (getVar() == DV.getVar())
102 return getInlinedAt() < DV.getInlinedAt();
103 return getVar() < DV.getVar();
Vikram TV859ad292015-12-16 11:09:48 +0000104 }
105 };
106
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000107 /// A pair of debug variable and value location.
Vikram TV859ad292015-12-16 11:09:48 +0000108 struct VarLoc {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000109 const DebugVariable Var;
110 const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000111 mutable UserValueScopes UVS;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000112 enum { InvalidKind = 0, RegisterKind } Kind;
Vikram TV859ad292015-12-16 11:09:48 +0000113
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000114 /// The value location. Stored separately to avoid repeatedly
115 /// extracting it from MI.
116 union {
117 struct {
118 uint32_t RegNo;
119 uint32_t Offset;
120 } RegisterLoc;
121 uint64_t Hash;
122 } Loc;
123
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000124 VarLoc(const MachineInstr &MI, LexicalScopes &LS)
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000125 : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000126 UVS(MI.getDebugLoc(), LS), Kind(InvalidKind) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000127 static_assert((sizeof(Loc) == sizeof(uint64_t)),
128 "hash does not cover all members of Loc");
129 assert(MI.isDebugValue() && "not a DBG_VALUE");
130 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
Adrian Prantl00698732016-05-25 22:37:29 +0000131 if (int RegNo = isDbgValueDescribedByReg(MI)) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000132 Kind = RegisterKind;
133 Loc.RegisterLoc.RegNo = RegNo;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000134 int64_t Offset =
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000135 MI.isIndirectDebugValue() ? MI.getOperand(1).getImm() : 0;
136 // We don't support offsets larger than 4GiB here. They are
137 // slated to be replaced with DIExpressions anyway.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000138 // With indirect debug values used for spill locations, Offset
139 // can be negative.
140 if (Offset == INT64_MIN || std::abs(Offset) >= (1LL << 32))
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000141 Kind = InvalidKind;
142 else
143 Loc.RegisterLoc.Offset = Offset;
144 }
145 }
146
147 /// If this variable is described by a register, return it,
148 /// otherwise return 0.
149 unsigned isDescribedByReg() const {
150 if (Kind == RegisterKind)
151 return Loc.RegisterLoc.RegNo;
152 return 0;
153 }
154
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000155 /// Determine whether the lexical scope of this value's debug location
156 /// dominates MBB.
157 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
158
Matthias Braun194ded52017-01-28 06:53:55 +0000159#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160 LLVM_DUMP_METHOD void dump() const { MI.dump(); }
161#endif
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000162
163 bool operator==(const VarLoc &Other) const {
164 return Var == Other.Var && Loc.Hash == Other.Loc.Hash;
165 }
166
Adrian Prantl7509d542016-05-26 21:42:47 +0000167 /// This operator guarantees that VarLocs are sorted by Variable first.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000168 bool operator<(const VarLoc &Other) const {
169 if (Var == Other.Var)
170 return Loc.Hash < Other.Loc.Hash;
171 return Var < Other.Var;
172 }
Vikram TV859ad292015-12-16 11:09:48 +0000173 };
174
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000175 typedef UniqueVector<VarLoc> VarLocMap;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000176 typedef SparseBitVector<> VarLocSet;
177 typedef SmallDenseMap<const MachineBasicBlock *, VarLocSet> VarLocInMBB;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000178 struct SpillDebugPair {
179 MachineInstr *SpillInst;
180 MachineInstr *DebugInst;
181 };
182 typedef SmallVector<SpillDebugPair, 4> SpillMap;
Vikram TV859ad292015-12-16 11:09:48 +0000183
Adrian Prantl7509d542016-05-26 21:42:47 +0000184 /// This holds the working set of currently open ranges. For fast
185 /// access, this is done both as a set of VarLocIDs, and a map of
186 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
187 /// previous open ranges for the same variable.
188 class OpenRangesSet {
189 VarLocSet VarLocs;
190 SmallDenseMap<DebugVariableBase, unsigned, 8> Vars;
191
192 public:
193 const VarLocSet &getVarLocs() const { return VarLocs; }
194
195 /// Terminate all open ranges for Var by removing it from the set.
196 void erase(DebugVariable Var) {
197 auto It = Vars.find(Var);
198 if (It != Vars.end()) {
199 unsigned ID = It->second;
200 VarLocs.reset(ID);
201 Vars.erase(It);
202 }
203 }
204
205 /// Terminate all open ranges listed in \c KillSet by removing
206 /// them from the set.
207 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
208 VarLocs.intersectWithComplement(KillSet);
209 for (unsigned ID : KillSet)
210 Vars.erase(VarLocIDs[ID].Var);
211 }
212
213 /// Insert a new range into the set.
214 void insert(unsigned VarLocID, DebugVariableBase Var) {
215 VarLocs.set(VarLocID);
216 Vars.insert({Var, VarLocID});
217 }
218
219 /// Empty the set.
220 void clear() {
221 VarLocs.clear();
222 Vars.clear();
223 }
224
225 /// Return whether the set is empty or not.
226 bool empty() const {
227 assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
228 return VarLocs.empty();
229 }
230 };
231
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000232 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
233 unsigned &Reg);
234 int extractSpillBaseRegAndOffset(const MachineInstr &MI, unsigned &Reg);
235
Adrian Prantl7509d542016-05-26 21:42:47 +0000236 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000237 VarLocMap &VarLocIDs);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000238 void transferSpillInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
239 VarLocMap &VarLocIDs, SpillMap &Spills);
Adrian Prantl7509d542016-05-26 21:42:47 +0000240 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000241 const VarLocMap &VarLocIDs);
Adrian Prantl7509d542016-05-26 21:42:47 +0000242 bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000243 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
Adrian Prantl7509d542016-05-26 21:42:47 +0000244 bool transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000245 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs, SpillMap &Spills,
246 bool transferSpills);
Vikram TV859ad292015-12-16 11:09:48 +0000247
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000248 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000249 const VarLocMap &VarLocIDs,
250 SmallPtrSet<const MachineBasicBlock *, 16> &Visited);
Vikram TV859ad292015-12-16 11:09:48 +0000251
252 bool ExtendRanges(MachineFunction &MF);
253
254public:
255 static char ID;
256
257 /// Default construct and initialize the pass.
258 LiveDebugValues();
259
260 /// Tell the pass manager which passes we depend on and what
261 /// information we preserve.
262 void getAnalysisUsage(AnalysisUsage &AU) const override;
263
Derek Schuffad154c82016-03-28 17:05:30 +0000264 MachineFunctionProperties getRequiredProperties() const override {
265 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000266 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000267 }
268
Vikram TV859ad292015-12-16 11:09:48 +0000269 /// Print to ostream with a message.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000270 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
271 const VarLocMap &VarLocIDs, const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000272 raw_ostream &Out) const;
273
274 /// Calculate the liveness information for the given machine function.
275 bool runOnMachineFunction(MachineFunction &MF) override;
276};
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000277
Vikram TV859ad292015-12-16 11:09:48 +0000278} // namespace
279
280//===----------------------------------------------------------------------===//
281// Implementation
282//===----------------------------------------------------------------------===//
283
284char LiveDebugValues::ID = 0;
285char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
286INITIALIZE_PASS(LiveDebugValues, "livedebugvalues", "Live DEBUG_VALUE analysis",
287 false, false)
288
289/// Default construct and initialize the pass.
290LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
291 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
292}
293
294/// Tell the pass manager which passes we depend on and what information we
295/// preserve.
296void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
Matt Arsenaultb1630a12016-06-08 05:18:01 +0000297 AU.setPreservesCFG();
Vikram TV859ad292015-12-16 11:09:48 +0000298 MachineFunctionPass::getAnalysisUsage(AU);
299}
300
Vikram TV859ad292015-12-16 11:09:48 +0000301//===----------------------------------------------------------------------===//
302// Debug Range Extension Implementation
303//===----------------------------------------------------------------------===//
304
Matthias Braun194ded52017-01-28 06:53:55 +0000305#ifndef NDEBUG
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000306void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
307 const VarLocInMBB &V,
308 const VarLocMap &VarLocIDs,
309 const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000310 raw_ostream &Out) const {
Keith Walkerf83a19f2016-09-20 16:04:31 +0000311 Out << '\n' << msg << '\n';
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000312 for (const MachineBasicBlock &BB : MF) {
313 const auto &L = V.lookup(&BB);
314 Out << "MBB: " << BB.getName() << ":\n";
315 for (unsigned VLL : L) {
316 const VarLoc &VL = VarLocIDs[VLL];
Adrian Prantl7509d542016-05-26 21:42:47 +0000317 Out << " Var: " << VL.Var.getVar()->getName();
Vikram TV859ad292015-12-16 11:09:48 +0000318 Out << " MI: ";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000319 VL.dump();
Vikram TV859ad292015-12-16 11:09:48 +0000320 }
321 }
322 Out << "\n";
323}
Matthias Braun194ded52017-01-28 06:53:55 +0000324#endif
Vikram TV859ad292015-12-16 11:09:48 +0000325
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000326/// Given a spill instruction, extract the register and offset used to
327/// address the spill location in a target independent way.
328int LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI,
329 unsigned &Reg) {
330 assert(MI.hasOneMemOperand() &&
331 "Spill instruction does not have exactly one memory operand?");
332 auto MMOI = MI.memoperands_begin();
333 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
334 assert(PVal->kind() == PseudoSourceValue::FixedStack &&
335 "Inconsistent memory operand in spill instruction");
336 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
337 const MachineBasicBlock *MBB = MI.getParent();
338 return TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
339}
340
Vikram TV859ad292015-12-16 11:09:48 +0000341/// End all previous ranges related to @MI and start a new range from @MI
342/// if it is a DBG_VALUE instr.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000343void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000344 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000345 VarLocMap &VarLocIDs) {
Vikram TV859ad292015-12-16 11:09:48 +0000346 if (!MI.isDebugValue())
347 return;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000348 const DILocalVariable *Var = MI.getDebugVariable();
349 const DILocation *DebugLoc = MI.getDebugLoc();
350 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
351 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
Vikram TV859ad292015-12-16 11:09:48 +0000352 "Expected inlined-at fields to agree");
Vikram TV859ad292015-12-16 11:09:48 +0000353
354 // End all previous ranges of Var.
Adrian Prantl7509d542016-05-26 21:42:47 +0000355 DebugVariable V(Var, InlinedAt);
356 OpenRanges.erase(V);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000357
358 // Add the VarLoc to OpenRanges from this DBG_VALUE.
359 // TODO: Currently handles DBG_VALUE which has only reg as location.
Adrian Prantl7509d542016-05-26 21:42:47 +0000360 if (isDbgValueDescribedByReg(MI)) {
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000361 VarLoc VL(MI, LS);
Adrian Prantl7509d542016-05-26 21:42:47 +0000362 unsigned ID = VarLocIDs.insert(VL);
363 OpenRanges.insert(ID, VL.Var);
364 }
Vikram TV859ad292015-12-16 11:09:48 +0000365}
366
367/// A definition of a register may mark the end of a range.
368void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000369 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000370 const VarLocMap &VarLocIDs) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000371 MachineFunction *MF = MI.getParent()->getParent();
372 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
373 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000374 SparseBitVector<> KillSet;
Vikram TV859ad292015-12-16 11:09:48 +0000375 for (const MachineOperand &MO : MI.operands()) {
Adrian Prantlea8880b2017-03-03 01:08:25 +0000376 // Determine whether the operand is a register def. Assume that call
377 // instructions never clobber SP, because some backends (e.g., AArch64)
378 // never list SP in the regmask.
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000379 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Adrian Prantlea8880b2017-03-03 01:08:25 +0000380 TRI->isPhysicalRegister(MO.getReg()) &&
381 !(MI.isCall() && MO.getReg() == SP)) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000382 // Remove ranges of all aliased registers.
383 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
Adrian Prantl7509d542016-05-26 21:42:47 +0000384 for (unsigned ID : OpenRanges.getVarLocs())
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000385 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
386 KillSet.set(ID);
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000387 } else if (MO.isRegMask()) {
388 // Remove ranges of all clobbered registers. Register masks don't usually
389 // list SP as preserved. While the debug info may be off for an
390 // instruction or two around callee-cleanup calls, transferring the
391 // DEBUG_VALUE across the call is still a better user experience.
Adrian Prantl7509d542016-05-26 21:42:47 +0000392 for (unsigned ID : OpenRanges.getVarLocs()) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000393 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
394 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
395 KillSet.set(ID);
396 }
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000397 }
Vikram TV859ad292015-12-16 11:09:48 +0000398 }
Adrian Prantl7509d542016-05-26 21:42:47 +0000399 OpenRanges.erase(KillSet, VarLocIDs);
Vikram TV859ad292015-12-16 11:09:48 +0000400}
401
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000402/// Decide if @MI is a spill instruction and return true if it is. We use 2
403/// criteria to make this decision:
404/// - Is this instruction a store to a spill slot?
405/// - Is there a register operand that is both used and killed?
406/// TODO: Store optimization can fold spills into other stores (including
407/// other spills). We do not handle this yet (more than one memory operand).
408bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
409 MachineFunction *MF, unsigned &Reg) {
410 const MachineFrameInfo &FrameInfo = MF->getFrameInfo();
411 int FI;
412 const MachineMemOperand *MMO;
413
414 // TODO: Handle multiple stores folded into one.
415 if (!MI.hasOneMemOperand())
416 return false;
417
418 // To identify a spill instruction, use the same criteria as in AsmPrinter.
419 if (!((TII->isStoreToStackSlotPostFE(MI, FI) ||
420 TII->hasStoreToStackSlot(MI, MMO, FI)) &&
421 FrameInfo.isSpillSlotObjectIndex(FI)))
422 return false;
423
424 // In a spill instruction generated by the InlineSpiller the spilled register
425 // has its kill flag set. Return false if we don't find such a register.
426 Reg = 0;
427 for (const MachineOperand &MO : MI.operands()) {
428 if (MO.isReg() && MO.isUse() && MO.isKill()) {
429 Reg = MO.getReg();
430 break;
431 }
432 }
433 return Reg != 0;
434}
435
436/// A spilled register may indicate that we have to end the current range of
437/// a variable and create a new one for the spill location.
438/// We don't want to insert any instructions in transfer(), so we just create
439/// the DBG_VALUE witout inserting it and keep track of it in @Spills.
440/// It will be inserted into the BB when we're done iterating over the
441/// instructions.
442void LiveDebugValues::transferSpillInst(MachineInstr &MI,
443 OpenRangesSet &OpenRanges,
444 VarLocMap &VarLocIDs,
445 SpillMap &Spills) {
446 unsigned Reg;
447 MachineFunction *MF = MI.getParent()->getParent();
448 if (!isSpillInstruction(MI, MF, Reg))
449 return;
450
451 // Check if the register is the location of a debug value.
452 for (unsigned ID : OpenRanges.getVarLocs()) {
453 if (VarLocIDs[ID].isDescribedByReg() == Reg) {
454 DEBUG(dbgs() << "Spilling Register " << PrintReg(Reg, TRI) << '('
455 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
456
457 // Create a DBG_VALUE instruction to describe the Var in its spilled
458 // location, but don't insert it yet to avoid invalidating the
459 // iterator in our caller.
460 unsigned SpillBase;
461 int SpillOffset = extractSpillBaseRegAndOffset(MI, SpillBase);
462 const MachineInstr *DMI = &VarLocIDs[ID].MI;
463 MachineInstr *SpDMI =
464 BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), true, SpillBase, 0,
465 DMI->getDebugVariable(), DMI->getDebugExpression());
466 SpDMI->getOperand(1).setImm(SpillOffset);
467 DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
468 SpDMI->print(dbgs(), false, TII));
469
470 // The newly created DBG_VALUE instruction SpDMI must be inserted after
471 // MI. Keep track of the pairing.
472 SpillDebugPair MIP = {&MI, SpDMI};
473 Spills.push_back(MIP);
474
475 // End all previous ranges of Var.
476 OpenRanges.erase(VarLocIDs[ID].Var);
477
478 // Add the VarLoc to OpenRanges.
479 VarLoc VL(*SpDMI, LS);
480 unsigned SpillLocID = VarLocIDs.insert(VL);
481 OpenRanges.insert(SpillLocID, VL.Var);
482 return;
483 }
484 }
485}
486
Vikram TV859ad292015-12-16 11:09:48 +0000487/// Terminate all open ranges at the end of the current basic block.
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000488bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000489 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000490 VarLocInMBB &OutLocs,
491 const VarLocMap &VarLocIDs) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000492 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000493 const MachineBasicBlock *CurMBB = MI.getParent();
494 if (!(MI.isTerminator() || (&MI == &CurMBB->instr_back())))
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000495 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000496
497 if (OpenRanges.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000498 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000499
Adrian Prantl7509d542016-05-26 21:42:47 +0000500 DEBUG(for (unsigned ID : OpenRanges.getVarLocs()) {
501 // Copy OpenRanges to OutLocs, if not already present.
502 dbgs() << "Add to OutLocs: "; VarLocIDs[ID].dump();
503 });
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000504 VarLocSet &VLS = OutLocs[CurMBB];
Adrian Prantl7509d542016-05-26 21:42:47 +0000505 Changed = VLS |= OpenRanges.getVarLocs();
Vikram TV859ad292015-12-16 11:09:48 +0000506 OpenRanges.clear();
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000507 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000508}
509
510/// This routine creates OpenRanges and OutLocs.
Adrian Prantl7509d542016-05-26 21:42:47 +0000511bool LiveDebugValues::transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000512 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
513 SpillMap &Spills, bool transferSpills) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000514 bool Changed = false;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000515 transferDebugValue(MI, OpenRanges, VarLocIDs);
516 transferRegisterDef(MI, OpenRanges, VarLocIDs);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000517 if (transferSpills)
518 transferSpillInst(MI, OpenRanges, VarLocIDs, Spills);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000519 Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000520 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000521}
522
523/// This routine joins the analysis results of all incoming edges in @MBB by
524/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
525/// source variable in all the predecessors of @MBB reside in the same location.
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000526bool LiveDebugValues::join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000527 VarLocInMBB &InLocs, const VarLocMap &VarLocIDs,
528 SmallPtrSet<const MachineBasicBlock *, 16> &Visited) {
Vikram TV859ad292015-12-16 11:09:48 +0000529 DEBUG(dbgs() << "join MBB: " << MBB.getName() << "\n");
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000530 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000531
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000532 VarLocSet InLocsT; // Temporary incoming locations.
Vikram TV859ad292015-12-16 11:09:48 +0000533
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000534 // For all predecessors of this MBB, find the set of VarLocs that
535 // can be joined.
Keith Walker83ebef52016-09-27 16:46:07 +0000536 int NumVisited = 0;
Vikram TV859ad292015-12-16 11:09:48 +0000537 for (auto p : MBB.predecessors()) {
Keith Walker83ebef52016-09-27 16:46:07 +0000538 // Ignore unvisited predecessor blocks. As we are processing
539 // the blocks in reverse post-order any unvisited block can
540 // be considered to not remove any incoming values.
541 if (!Visited.count(p))
542 continue;
Vikram TV859ad292015-12-16 11:09:48 +0000543 auto OL = OutLocs.find(p);
544 // Join is null in case of empty OutLocs from any of the pred.
545 if (OL == OutLocs.end())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000546 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000547
Keith Walker83ebef52016-09-27 16:46:07 +0000548 // Just copy over the Out locs to incoming locs for the first visited
549 // predecessor, and for all other predecessors join the Out locs.
550 if (!NumVisited)
Vikram TV859ad292015-12-16 11:09:48 +0000551 InLocsT = OL->second;
Keith Walker83ebef52016-09-27 16:46:07 +0000552 else
553 InLocsT &= OL->second;
554 NumVisited++;
Vikram TV859ad292015-12-16 11:09:48 +0000555 }
556
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000557 // Filter out DBG_VALUES that are out of scope.
558 VarLocSet KillSet;
559 for (auto ID : InLocsT)
560 if (!VarLocIDs[ID].dominates(MBB))
561 KillSet.set(ID);
562 InLocsT.intersectWithComplement(KillSet);
563
Keith Walker83ebef52016-09-27 16:46:07 +0000564 // As we are processing blocks in reverse post-order we
565 // should have processed at least one predecessor, unless it
566 // is the entry block which has no predecessor.
567 assert((NumVisited || MBB.pred_empty()) &&
568 "Should have processed at least one predecessor");
Vikram TV859ad292015-12-16 11:09:48 +0000569 if (InLocsT.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000570 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000571
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000572 VarLocSet &ILS = InLocs[&MBB];
Vikram TV859ad292015-12-16 11:09:48 +0000573
574 // Insert DBG_VALUE instructions, if not already inserted.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000575 VarLocSet Diff = InLocsT;
576 Diff.intersectWithComplement(ILS);
577 for (auto ID : Diff) {
578 // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
579 // new range is started for the var from the mbb's beginning by inserting
580 // a new DBG_VALUE. transfer() will end this range however appropriate.
581 const VarLoc &DiffIt = VarLocIDs[ID];
582 const MachineInstr *DMI = &DiffIt.MI;
583 MachineInstr *MI =
584 BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
585 DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(), 0,
586 DMI->getDebugVariable(), DMI->getDebugExpression());
587 if (DMI->isIndirectDebugValue())
588 MI->getOperand(1).setImm(DMI->getOperand(1).getImm());
589 DEBUG(dbgs() << "Inserted: "; MI->dump(););
590 ILS.set(ID);
591 ++NumInserted;
592 Changed = true;
Vikram TV859ad292015-12-16 11:09:48 +0000593 }
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000594 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000595}
596
597/// Calculate the liveness information for the given machine function and
598/// extend ranges across basic blocks.
599bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
600
601 DEBUG(dbgs() << "\nDebug Range Extension\n");
602
603 bool Changed = false;
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000604 bool OLChanged = false;
605 bool MBBJoined = false;
Vikram TV859ad292015-12-16 11:09:48 +0000606
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000607 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
Adrian Prantl7509d542016-05-26 21:42:47 +0000608 OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000609 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
610 VarLocInMBB InLocs; // Ranges that are incoming after joining.
611 SpillMap Spills; // DBG_VALUEs associated with spills.
Vikram TV859ad292015-12-16 11:09:48 +0000612
Daniel Berlin72560592016-01-10 18:08:32 +0000613 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
614 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
615 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000616 std::greater<unsigned int>>
617 Worklist;
Daniel Berlin72560592016-01-10 18:08:32 +0000618 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000619 std::greater<unsigned int>>
620 Pending;
621
Vikram TV859ad292015-12-16 11:09:48 +0000622 // Initialize every mbb with OutLocs.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000623 // We are not looking at any spill instructions during the initial pass
624 // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
625 // instructions for spills of registers that are known to be user variables
626 // within the BB in which the spill occurs.
Vikram TV859ad292015-12-16 11:09:48 +0000627 for (auto &MBB : MF)
628 for (auto &MI : MBB)
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000629 transfer(MI, OpenRanges, OutLocs, VarLocIDs, Spills,
630 /*transferSpills=*/false);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000631
632 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "OutLocs after initialization",
633 dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000634
Daniel Berlin72560592016-01-10 18:08:32 +0000635 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
636 unsigned int RPONumber = 0;
637 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
638 OrderToBB[RPONumber] = *RI;
639 BBToOrder[*RI] = RPONumber;
640 Worklist.push(RPONumber);
641 ++RPONumber;
642 }
Daniel Berlin72560592016-01-10 18:08:32 +0000643 // This is a standard "union of predecessor outs" dataflow problem.
644 // To solve it, we perform join() and transfer() using the two worklist method
645 // until the ranges converge.
646 // Ranges have converged when both worklists are empty.
Keith Walker83ebef52016-09-27 16:46:07 +0000647 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
Daniel Berlin72560592016-01-10 18:08:32 +0000648 while (!Worklist.empty() || !Pending.empty()) {
649 // We track what is on the pending worklist to avoid inserting the same
650 // thing twice. We could avoid this with a custom priority queue, but this
651 // is probably not worth it.
652 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
Keith Walkerf83a19f2016-09-20 16:04:31 +0000653 DEBUG(dbgs() << "Processing Worklist\n");
Daniel Berlin72560592016-01-10 18:08:32 +0000654 while (!Worklist.empty()) {
655 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
656 Worklist.pop();
Keith Walker83ebef52016-09-27 16:46:07 +0000657 MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited);
658 Visited.insert(MBB);
Daniel Berlin72560592016-01-10 18:08:32 +0000659 if (MBBJoined) {
660 MBBJoined = false;
661 Changed = true;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000662 // Now that we have started to extend ranges across BBs we need to
663 // examine spill instructions to see whether they spill registers that
664 // correspond to user variables.
Daniel Berlin72560592016-01-10 18:08:32 +0000665 for (auto &MI : *MBB)
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000666 OLChanged |= transfer(MI, OpenRanges, OutLocs, VarLocIDs, Spills,
667 /*transferSpills=*/true);
668
669 // Add any DBG_VALUE instructions necessitated by spills.
670 for (auto &SP : Spills)
671 MBB->insertAfter(MachineBasicBlock::iterator(*SP.SpillInst),
672 SP.DebugInst);
673 Spills.clear();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000674
675 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
676 "OutLocs after propagating", dbgs()));
677 DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
678 "InLocs after propagating", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000679
Daniel Berlin72560592016-01-10 18:08:32 +0000680 if (OLChanged) {
681 OLChanged = false;
682 for (auto s : MBB->successors())
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000683 if (OnPending.insert(s).second) {
Daniel Berlin72560592016-01-10 18:08:32 +0000684 Pending.push(BBToOrder[s]);
685 }
686 }
Vikram TV859ad292015-12-16 11:09:48 +0000687 }
688 }
Daniel Berlin72560592016-01-10 18:08:32 +0000689 Worklist.swap(Pending);
690 // At this point, pending must be empty, since it was just the empty
691 // worklist
692 assert(Pending.empty() && "Pending should be empty");
Vikram TV859ad292015-12-16 11:09:48 +0000693 }
Daniel Berlin72560592016-01-10 18:08:32 +0000694
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000695 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
696 DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000697 return Changed;
698}
699
700bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000701 if (!MF.getFunction()->getSubprogram())
702 // LiveDebugValues will already have removed all DBG_VALUEs.
703 return false;
704
Vikram TV859ad292015-12-16 11:09:48 +0000705 TRI = MF.getSubtarget().getRegisterInfo();
706 TII = MF.getSubtarget().getInstrInfo();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000707 TFI = MF.getSubtarget().getFrameLowering();
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000708 LS.initialize(MF);
Vikram TV859ad292015-12-16 11:09:48 +0000709
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000710 bool Changed = ExtendRanges(MF);
Vikram TV859ad292015-12-16 11:09:48 +0000711 return Changed;
712}