blob: 3e079d6774e92e14166085ddfd30602310ee4904 [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()) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000376 if (MO.isReg() && MO.isDef() && MO.getReg() &&
377 TRI->isPhysicalRegister(MO.getReg())) {
378 // Remove ranges of all aliased registers.
379 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
Adrian Prantl7509d542016-05-26 21:42:47 +0000380 for (unsigned ID : OpenRanges.getVarLocs())
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000381 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
382 KillSet.set(ID);
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000383 } else if (MO.isRegMask()) {
384 // Remove ranges of all clobbered registers. Register masks don't usually
385 // list SP as preserved. While the debug info may be off for an
386 // instruction or two around callee-cleanup calls, transferring the
387 // DEBUG_VALUE across the call is still a better user experience.
Adrian Prantl7509d542016-05-26 21:42:47 +0000388 for (unsigned ID : OpenRanges.getVarLocs()) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000389 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
390 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
391 KillSet.set(ID);
392 }
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000393 }
Vikram TV859ad292015-12-16 11:09:48 +0000394 }
Adrian Prantl7509d542016-05-26 21:42:47 +0000395 OpenRanges.erase(KillSet, VarLocIDs);
Vikram TV859ad292015-12-16 11:09:48 +0000396}
397
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000398/// Decide if @MI is a spill instruction and return true if it is. We use 2
399/// criteria to make this decision:
400/// - Is this instruction a store to a spill slot?
401/// - Is there a register operand that is both used and killed?
402/// TODO: Store optimization can fold spills into other stores (including
403/// other spills). We do not handle this yet (more than one memory operand).
404bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
405 MachineFunction *MF, unsigned &Reg) {
406 const MachineFrameInfo &FrameInfo = MF->getFrameInfo();
407 int FI;
408 const MachineMemOperand *MMO;
409
410 // TODO: Handle multiple stores folded into one.
411 if (!MI.hasOneMemOperand())
412 return false;
413
414 // To identify a spill instruction, use the same criteria as in AsmPrinter.
415 if (!((TII->isStoreToStackSlotPostFE(MI, FI) ||
416 TII->hasStoreToStackSlot(MI, MMO, FI)) &&
417 FrameInfo.isSpillSlotObjectIndex(FI)))
418 return false;
419
420 // In a spill instruction generated by the InlineSpiller the spilled register
421 // has its kill flag set. Return false if we don't find such a register.
422 Reg = 0;
423 for (const MachineOperand &MO : MI.operands()) {
424 if (MO.isReg() && MO.isUse() && MO.isKill()) {
425 Reg = MO.getReg();
426 break;
427 }
428 }
429 return Reg != 0;
430}
431
432/// A spilled register may indicate that we have to end the current range of
433/// a variable and create a new one for the spill location.
434/// We don't want to insert any instructions in transfer(), so we just create
435/// the DBG_VALUE witout inserting it and keep track of it in @Spills.
436/// It will be inserted into the BB when we're done iterating over the
437/// instructions.
438void LiveDebugValues::transferSpillInst(MachineInstr &MI,
439 OpenRangesSet &OpenRanges,
440 VarLocMap &VarLocIDs,
441 SpillMap &Spills) {
442 unsigned Reg;
443 MachineFunction *MF = MI.getParent()->getParent();
444 if (!isSpillInstruction(MI, MF, Reg))
445 return;
446
447 // Check if the register is the location of a debug value.
448 for (unsigned ID : OpenRanges.getVarLocs()) {
449 if (VarLocIDs[ID].isDescribedByReg() == Reg) {
450 DEBUG(dbgs() << "Spilling Register " << PrintReg(Reg, TRI) << '('
451 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
452
453 // Create a DBG_VALUE instruction to describe the Var in its spilled
454 // location, but don't insert it yet to avoid invalidating the
455 // iterator in our caller.
456 unsigned SpillBase;
457 int SpillOffset = extractSpillBaseRegAndOffset(MI, SpillBase);
458 const MachineInstr *DMI = &VarLocIDs[ID].MI;
459 MachineInstr *SpDMI =
460 BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), true, SpillBase, 0,
461 DMI->getDebugVariable(), DMI->getDebugExpression());
462 SpDMI->getOperand(1).setImm(SpillOffset);
463 DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
464 SpDMI->print(dbgs(), false, TII));
465
466 // The newly created DBG_VALUE instruction SpDMI must be inserted after
467 // MI. Keep track of the pairing.
468 SpillDebugPair MIP = {&MI, SpDMI};
469 Spills.push_back(MIP);
470
471 // End all previous ranges of Var.
472 OpenRanges.erase(VarLocIDs[ID].Var);
473
474 // Add the VarLoc to OpenRanges.
475 VarLoc VL(*SpDMI, LS);
476 unsigned SpillLocID = VarLocIDs.insert(VL);
477 OpenRanges.insert(SpillLocID, VL.Var);
478 return;
479 }
480 }
481}
482
Vikram TV859ad292015-12-16 11:09:48 +0000483/// Terminate all open ranges at the end of the current basic block.
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000484bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000485 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000486 VarLocInMBB &OutLocs,
487 const VarLocMap &VarLocIDs) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000488 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000489 const MachineBasicBlock *CurMBB = MI.getParent();
490 if (!(MI.isTerminator() || (&MI == &CurMBB->instr_back())))
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000491 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000492
493 if (OpenRanges.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000494 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000495
Adrian Prantl7509d542016-05-26 21:42:47 +0000496 DEBUG(for (unsigned ID : OpenRanges.getVarLocs()) {
497 // Copy OpenRanges to OutLocs, if not already present.
498 dbgs() << "Add to OutLocs: "; VarLocIDs[ID].dump();
499 });
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000500 VarLocSet &VLS = OutLocs[CurMBB];
Adrian Prantl7509d542016-05-26 21:42:47 +0000501 Changed = VLS |= OpenRanges.getVarLocs();
Vikram TV859ad292015-12-16 11:09:48 +0000502 OpenRanges.clear();
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000503 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000504}
505
506/// This routine creates OpenRanges and OutLocs.
Adrian Prantl7509d542016-05-26 21:42:47 +0000507bool LiveDebugValues::transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000508 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
509 SpillMap &Spills, bool transferSpills) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000510 bool Changed = false;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000511 transferDebugValue(MI, OpenRanges, VarLocIDs);
512 transferRegisterDef(MI, OpenRanges, VarLocIDs);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000513 if (transferSpills)
514 transferSpillInst(MI, OpenRanges, VarLocIDs, Spills);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000515 Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000516 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000517}
518
519/// This routine joins the analysis results of all incoming edges in @MBB by
520/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
521/// source variable in all the predecessors of @MBB reside in the same location.
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000522bool LiveDebugValues::join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000523 VarLocInMBB &InLocs, const VarLocMap &VarLocIDs,
524 SmallPtrSet<const MachineBasicBlock *, 16> &Visited) {
Vikram TV859ad292015-12-16 11:09:48 +0000525 DEBUG(dbgs() << "join MBB: " << MBB.getName() << "\n");
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000526 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000527
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000528 VarLocSet InLocsT; // Temporary incoming locations.
Vikram TV859ad292015-12-16 11:09:48 +0000529
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000530 // For all predecessors of this MBB, find the set of VarLocs that
531 // can be joined.
Keith Walker83ebef52016-09-27 16:46:07 +0000532 int NumVisited = 0;
Vikram TV859ad292015-12-16 11:09:48 +0000533 for (auto p : MBB.predecessors()) {
Keith Walker83ebef52016-09-27 16:46:07 +0000534 // Ignore unvisited predecessor blocks. As we are processing
535 // the blocks in reverse post-order any unvisited block can
536 // be considered to not remove any incoming values.
537 if (!Visited.count(p))
538 continue;
Vikram TV859ad292015-12-16 11:09:48 +0000539 auto OL = OutLocs.find(p);
540 // Join is null in case of empty OutLocs from any of the pred.
541 if (OL == OutLocs.end())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000542 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000543
Keith Walker83ebef52016-09-27 16:46:07 +0000544 // Just copy over the Out locs to incoming locs for the first visited
545 // predecessor, and for all other predecessors join the Out locs.
546 if (!NumVisited)
Vikram TV859ad292015-12-16 11:09:48 +0000547 InLocsT = OL->second;
Keith Walker83ebef52016-09-27 16:46:07 +0000548 else
549 InLocsT &= OL->second;
550 NumVisited++;
Vikram TV859ad292015-12-16 11:09:48 +0000551 }
552
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000553 // Filter out DBG_VALUES that are out of scope.
554 VarLocSet KillSet;
555 for (auto ID : InLocsT)
556 if (!VarLocIDs[ID].dominates(MBB))
557 KillSet.set(ID);
558 InLocsT.intersectWithComplement(KillSet);
559
Keith Walker83ebef52016-09-27 16:46:07 +0000560 // As we are processing blocks in reverse post-order we
561 // should have processed at least one predecessor, unless it
562 // is the entry block which has no predecessor.
563 assert((NumVisited || MBB.pred_empty()) &&
564 "Should have processed at least one predecessor");
Vikram TV859ad292015-12-16 11:09:48 +0000565 if (InLocsT.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000566 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000567
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000568 VarLocSet &ILS = InLocs[&MBB];
Vikram TV859ad292015-12-16 11:09:48 +0000569
570 // Insert DBG_VALUE instructions, if not already inserted.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000571 VarLocSet Diff = InLocsT;
572 Diff.intersectWithComplement(ILS);
573 for (auto ID : Diff) {
574 // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
575 // new range is started for the var from the mbb's beginning by inserting
576 // a new DBG_VALUE. transfer() will end this range however appropriate.
577 const VarLoc &DiffIt = VarLocIDs[ID];
578 const MachineInstr *DMI = &DiffIt.MI;
579 MachineInstr *MI =
580 BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
581 DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(), 0,
582 DMI->getDebugVariable(), DMI->getDebugExpression());
583 if (DMI->isIndirectDebugValue())
584 MI->getOperand(1).setImm(DMI->getOperand(1).getImm());
585 DEBUG(dbgs() << "Inserted: "; MI->dump(););
586 ILS.set(ID);
587 ++NumInserted;
588 Changed = true;
Vikram TV859ad292015-12-16 11:09:48 +0000589 }
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000590 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000591}
592
593/// Calculate the liveness information for the given machine function and
594/// extend ranges across basic blocks.
595bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
596
597 DEBUG(dbgs() << "\nDebug Range Extension\n");
598
599 bool Changed = false;
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000600 bool OLChanged = false;
601 bool MBBJoined = false;
Vikram TV859ad292015-12-16 11:09:48 +0000602
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000603 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
Adrian Prantl7509d542016-05-26 21:42:47 +0000604 OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000605 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
606 VarLocInMBB InLocs; // Ranges that are incoming after joining.
607 SpillMap Spills; // DBG_VALUEs associated with spills.
Vikram TV859ad292015-12-16 11:09:48 +0000608
Daniel Berlin72560592016-01-10 18:08:32 +0000609 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
610 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
611 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000612 std::greater<unsigned int>>
613 Worklist;
Daniel Berlin72560592016-01-10 18:08:32 +0000614 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000615 std::greater<unsigned int>>
616 Pending;
617
Vikram TV859ad292015-12-16 11:09:48 +0000618 // Initialize every mbb with OutLocs.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000619 // We are not looking at any spill instructions during the initial pass
620 // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
621 // instructions for spills of registers that are known to be user variables
622 // within the BB in which the spill occurs.
Vikram TV859ad292015-12-16 11:09:48 +0000623 for (auto &MBB : MF)
624 for (auto &MI : MBB)
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000625 transfer(MI, OpenRanges, OutLocs, VarLocIDs, Spills,
626 /*transferSpills=*/false);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000627
628 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "OutLocs after initialization",
629 dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000630
Daniel Berlin72560592016-01-10 18:08:32 +0000631 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
632 unsigned int RPONumber = 0;
633 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
634 OrderToBB[RPONumber] = *RI;
635 BBToOrder[*RI] = RPONumber;
636 Worklist.push(RPONumber);
637 ++RPONumber;
638 }
Daniel Berlin72560592016-01-10 18:08:32 +0000639 // This is a standard "union of predecessor outs" dataflow problem.
640 // To solve it, we perform join() and transfer() using the two worklist method
641 // until the ranges converge.
642 // Ranges have converged when both worklists are empty.
Keith Walker83ebef52016-09-27 16:46:07 +0000643 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
Daniel Berlin72560592016-01-10 18:08:32 +0000644 while (!Worklist.empty() || !Pending.empty()) {
645 // We track what is on the pending worklist to avoid inserting the same
646 // thing twice. We could avoid this with a custom priority queue, but this
647 // is probably not worth it.
648 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
Keith Walkerf83a19f2016-09-20 16:04:31 +0000649 DEBUG(dbgs() << "Processing Worklist\n");
Daniel Berlin72560592016-01-10 18:08:32 +0000650 while (!Worklist.empty()) {
651 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
652 Worklist.pop();
Keith Walker83ebef52016-09-27 16:46:07 +0000653 MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited);
654 Visited.insert(MBB);
Daniel Berlin72560592016-01-10 18:08:32 +0000655 if (MBBJoined) {
656 MBBJoined = false;
657 Changed = true;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000658 // Now that we have started to extend ranges across BBs we need to
659 // examine spill instructions to see whether they spill registers that
660 // correspond to user variables.
Daniel Berlin72560592016-01-10 18:08:32 +0000661 for (auto &MI : *MBB)
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000662 OLChanged |= transfer(MI, OpenRanges, OutLocs, VarLocIDs, Spills,
663 /*transferSpills=*/true);
664
665 // Add any DBG_VALUE instructions necessitated by spills.
666 for (auto &SP : Spills)
667 MBB->insertAfter(MachineBasicBlock::iterator(*SP.SpillInst),
668 SP.DebugInst);
669 Spills.clear();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000670
671 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
672 "OutLocs after propagating", dbgs()));
673 DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
674 "InLocs after propagating", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000675
Daniel Berlin72560592016-01-10 18:08:32 +0000676 if (OLChanged) {
677 OLChanged = false;
678 for (auto s : MBB->successors())
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000679 if (OnPending.insert(s).second) {
Daniel Berlin72560592016-01-10 18:08:32 +0000680 Pending.push(BBToOrder[s]);
681 }
682 }
Vikram TV859ad292015-12-16 11:09:48 +0000683 }
684 }
Daniel Berlin72560592016-01-10 18:08:32 +0000685 Worklist.swap(Pending);
686 // At this point, pending must be empty, since it was just the empty
687 // worklist
688 assert(Pending.empty() && "Pending should be empty");
Vikram TV859ad292015-12-16 11:09:48 +0000689 }
Daniel Berlin72560592016-01-10 18:08:32 +0000690
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000691 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
692 DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000693 return Changed;
694}
695
696bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000697 if (!MF.getFunction()->getSubprogram())
698 // LiveDebugValues will already have removed all DBG_VALUEs.
699 return false;
700
Vikram TV859ad292015-12-16 11:09:48 +0000701 TRI = MF.getSubtarget().getRegisterInfo();
702 TII = MF.getSubtarget().getInstrInfo();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000703 TFI = MF.getSubtarget().getFrameLowering();
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000704 LS.initialize(MF);
Vikram TV859ad292015-12-16 11:09:48 +0000705
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000706 bool Changed = ExtendRanges(MF);
Vikram TV859ad292015-12-16 11:09:48 +0000707 return Changed;
708}