blob: f1b237d83e8cf85d7ccfdcf8c0736278b5ae6ff8 [file] [log] [blame]
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001//===- LiveDebugValues.cpp - Tracking Debug Value MIs ---------------------===//
Vikram TV859ad292015-12-16 11:09:48 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Vikram TV859ad292015-12-16 11:09:48 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// This pass implements a data flow analysis that propagates debug location
Jeremy Morse67443c32019-08-21 09:22:31 +000010/// information by inserting additional DBG_VALUE insts into the machine
11/// instruction stream. Before running, each DBG_VALUE inst corresponds to a
12/// source assignment of a variable. Afterwards, a DBG_VALUE inst specifies a
13/// variable location for the current basic block (see SourceLevelDebugging.rst).
Vikram TV859ad292015-12-16 11:09:48 +000014///
15/// This is a separate pass from DbgValueHistoryCalculator to facilitate
16/// testing and improve modularity.
17///
Jeremy Morse67443c32019-08-21 09:22:31 +000018/// Each variable location is represented by a VarLoc object that identifies the
19/// source variable, its current machine-location, and the DBG_VALUE inst that
20/// specifies the location. Each VarLoc is indexed in the (function-scope)
21/// VarLocMap, giving each VarLoc a unique index. Rather than operate directly
22/// on machine locations, the dataflow analysis in this pass identifies
23/// locations by their index in the VarLocMap, meaning all the variable
24/// locations in a block can be described by a sparse vector of VarLocMap
25/// indexes.
26///
Vikram TV859ad292015-12-16 11:09:48 +000027//===----------------------------------------------------------------------===//
28
Eugene Zelenko5df3d892017-08-24 21:21:39 +000029#include "llvm/ADT/DenseMap.h"
Daniel Berlin72560592016-01-10 18:08:32 +000030#include "llvm/ADT/PostOrderIterator.h"
31#include "llvm/ADT/SmallPtrSet.h"
Jeremy Morsebf2b2f02019-06-13 12:51:57 +000032#include "llvm/ADT/SmallSet.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000033#include "llvm/ADT/SmallVector.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000034#include "llvm/ADT/SparseBitVector.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000035#include "llvm/ADT/Statistic.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000036#include "llvm/ADT/UniqueVector.h"
Adrian Prantl7f5866c2016-09-28 17:51:14 +000037#include "llvm/CodeGen/LexicalScopes.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000038#include "llvm/CodeGen/MachineBasicBlock.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000039#include "llvm/CodeGen/MachineFrameInfo.h"
Vikram TV859ad292015-12-16 11:09:48 +000040#include "llvm/CodeGen/MachineFunction.h"
41#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000042#include "llvm/CodeGen/MachineInstr.h"
Vikram TV859ad292015-12-16 11:09:48 +000043#include "llvm/CodeGen/MachineInstrBuilder.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000044#include "llvm/CodeGen/MachineMemOperand.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000045#include "llvm/CodeGen/MachineOperand.h"
46#include "llvm/CodeGen/PseudoSourceValue.h"
Wolfgang Pieb90d856c2019-02-04 20:42:45 +000047#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000048#include "llvm/CodeGen/TargetFrameLowering.h"
49#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000050#include "llvm/CodeGen/TargetLowering.h"
Djordje Todorovic12aca5d2019-07-09 08:36:34 +000051#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000052#include "llvm/CodeGen/TargetRegisterInfo.h"
53#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000054#include "llvm/Config/llvm-config.h"
Wolfgang Pieb90d856c2019-02-04 20:42:45 +000055#include "llvm/IR/DIBuilder.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000056#include "llvm/IR/DebugInfoMetadata.h"
57#include "llvm/IR/DebugLoc.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/Module.h"
60#include "llvm/MC/MCRegisterInfo.h"
61#include "llvm/Pass.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Compiler.h"
Vikram TV859ad292015-12-16 11:09:48 +000064#include "llvm/Support/Debug.h"
65#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000066#include <algorithm>
67#include <cassert>
68#include <cstdint>
69#include <functional>
Mehdi Aminib550cb12016-04-18 09:17:29 +000070#include <queue>
Jeremy Morsebf2b2f02019-06-13 12:51:57 +000071#include <tuple>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000072#include <utility>
73#include <vector>
Vikram TV859ad292015-12-16 11:09:48 +000074
75using namespace llvm;
76
Matthias Braun1527baa2017-05-25 21:26:32 +000077#define DEBUG_TYPE "livedebugvalues"
Vikram TV859ad292015-12-16 11:09:48 +000078
79STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
Jeremy Morse0ae54982019-08-23 16:33:42 +000080STATISTIC(NumRemoved, "Number of DBG_VALUE instructions removed");
Vikram TV859ad292015-12-16 11:09:48 +000081
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000082// If @MI is a DBG_VALUE with debug value described by a defined
Adrian Prantl6ee02c72016-05-25 22:21:12 +000083// register, returns the number of this register. In the other case, returns 0.
Matt Arsenaulte3a676e2019-06-24 15:50:29 +000084static Register isDbgValueDescribedByReg(const MachineInstr &MI) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +000085 assert(MI.isDebugValue() && "expected a DBG_VALUE");
86 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
87 // If location of variable is described using a register (directly
88 // or indirectly), this register is always a first operand.
Matt Arsenaulte3a676e2019-06-24 15:50:29 +000089 return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : Register();
Adrian Prantl6ee02c72016-05-25 22:21:12 +000090}
91
Eugene Zelenko5df3d892017-08-24 21:21:39 +000092namespace {
Vikram TV859ad292015-12-16 11:09:48 +000093
Eugene Zelenko5df3d892017-08-24 21:21:39 +000094class LiveDebugValues : public MachineFunctionPass {
Vikram TV859ad292015-12-16 11:09:48 +000095private:
96 const TargetRegisterInfo *TRI;
97 const TargetInstrInfo *TII;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000098 const TargetFrameLowering *TFI;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +000099 BitVector CalleeSavedRegs;
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000100 LexicalScopes LS;
101
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000102 enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
103
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000104 /// Keeps track of lexical scopes associated with a user value's source
105 /// location.
106 class UserValueScopes {
107 DebugLoc DL;
108 LexicalScopes &LS;
109 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
110
111 public:
112 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
113
114 /// Return true if current scope dominates at least one machine
115 /// instruction in a given machine basic block.
116 bool dominates(MachineBasicBlock *MBB) {
117 if (LBlocks.empty())
118 LS.getMachineBasicBlocks(DL, LBlocks);
119 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
120 }
121 };
Vikram TV859ad292015-12-16 11:09:48 +0000122
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000123 using FragmentInfo = DIExpression::FragmentInfo;
124 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
Vikram TV859ad292015-12-16 11:09:48 +0000125
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000126 /// Storage for identifying a potentially inlined instance of a variable,
127 /// or a fragment thereof.
128 class DebugVariable {
129 const DILocalVariable *Variable;
130 OptFragmentInfo Fragment;
131 const DILocation *InlinedAt;
Vikram TV859ad292015-12-16 11:09:48 +0000132
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000133 /// Fragment that will overlap all other fragments. Used as default when
134 /// caller demands a fragment.
135 static const FragmentInfo DefaultFragment;
136
137 public:
138 DebugVariable(const DILocalVariable *Var, OptFragmentInfo &&FragmentInfo,
139 const DILocation *InlinedAt)
140 : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
141
142 DebugVariable(const DILocalVariable *Var, OptFragmentInfo &FragmentInfo,
143 const DILocation *InlinedAt)
144 : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
145
146 DebugVariable(const DILocalVariable *Var, const DIExpression *DIExpr,
147 const DILocation *InlinedAt)
148 : DebugVariable(Var, DIExpr->getFragmentInfo(), InlinedAt) {}
149
150 DebugVariable(const MachineInstr &MI)
151 : DebugVariable(MI.getDebugVariable(),
152 MI.getDebugExpression()->getFragmentInfo(),
153 MI.getDebugLoc()->getInlinedAt()) {}
154
155 const DILocalVariable *getVar() const { return Variable; }
156 const OptFragmentInfo &getFragment() const { return Fragment; }
157 const DILocation *getInlinedAt() const { return InlinedAt; }
158
159 const FragmentInfo getFragmentDefault() const {
160 return Fragment.getValueOr(DefaultFragment);
161 }
162
163 static bool isFragmentDefault(FragmentInfo &F) {
164 return F == DefaultFragment;
165 }
166
167 bool operator==(const DebugVariable &Other) const {
168 return std::tie(Variable, Fragment, InlinedAt) ==
169 std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
170 }
171
172 bool operator<(const DebugVariable &Other) const {
173 return std::tie(Variable, Fragment, InlinedAt) <
174 std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
Vikram TV859ad292015-12-16 11:09:48 +0000175 }
176 };
177
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000178 friend struct llvm::DenseMapInfo<DebugVariable>;
179
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000180 /// A pair of debug variable and value location.
Vikram TV859ad292015-12-16 11:09:48 +0000181 struct VarLoc {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000182 // The location at which a spilled variable resides. It consists of a
183 // register and an offset.
184 struct SpillLoc {
185 unsigned SpillBase;
186 int SpillOffset;
187 bool operator==(const SpillLoc &Other) const {
188 return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
189 }
190 };
191
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000192 /// Identity of the variable at this location.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000193 const DebugVariable Var;
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000194
195 /// The expression applied to this location.
196 const DIExpression *Expr;
197
198 /// DBG_VALUE to clone var/expr information from if this location
199 /// is moved.
200 const MachineInstr &MI;
201
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000202 mutable UserValueScopes UVS;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000203 enum VarLocKind {
204 InvalidKind = 0,
205 RegisterKind,
Jeremy Morsebcff4172019-06-10 15:23:46 +0000206 SpillLocKind,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000207 ImmediateKind,
208 EntryValueKind
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000209 } Kind = InvalidKind;
Vikram TV859ad292015-12-16 11:09:48 +0000210
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000211 /// The value location. Stored separately to avoid repeatedly
212 /// extracting it from MI.
213 union {
Adrian Prantl359846f2017-07-28 23:25:51 +0000214 uint64_t RegNo;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000215 SpillLoc SpillLocation;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000216 uint64_t Hash;
Jeremy Morsebcff4172019-06-10 15:23:46 +0000217 int64_t Immediate;
218 const ConstantFP *FPImm;
219 const ConstantInt *CImm;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000220 } Loc;
221
Jeremy Morse61800a72019-10-04 10:53:47 +0000222 VarLoc(const MachineInstr &MI, LexicalScopes &LS)
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000223 : Var(MI), Expr(MI.getDebugExpression()), MI(MI),
224 UVS(MI.getDebugLoc(), LS) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000225 static_assert((sizeof(Loc) == sizeof(uint64_t)),
226 "hash does not cover all members of Loc");
227 assert(MI.isDebugValue() && "not a DBG_VALUE");
228 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
Adrian Prantl00698732016-05-25 22:37:29 +0000229 if (int RegNo = isDbgValueDescribedByReg(MI)) {
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000230 Kind = MI.isDebugEntryValue() ? EntryValueKind : RegisterKind;
Adrian Prantl359846f2017-07-28 23:25:51 +0000231 Loc.RegNo = RegNo;
Jeremy Morsebcff4172019-06-10 15:23:46 +0000232 } else if (MI.getOperand(0).isImm()) {
233 Kind = ImmediateKind;
234 Loc.Immediate = MI.getOperand(0).getImm();
235 } else if (MI.getOperand(0).isFPImm()) {
236 Kind = ImmediateKind;
237 Loc.FPImm = MI.getOperand(0).getFPImm();
238 } else if (MI.getOperand(0).isCImm()) {
239 Kind = ImmediateKind;
240 Loc.CImm = MI.getOperand(0).getCImm();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000241 }
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000242 assert((Kind != ImmediateKind || !MI.isDebugEntryValue()) &&
243 "entry values must be register locations");
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000244 }
245
Jeremy Morse61800a72019-10-04 10:53:47 +0000246 /// Take the variable and machine-location in DBG_VALUE MI, and build an
247 /// entry location using the given expression.
248 static VarLoc CreateEntryLoc(const MachineInstr &MI, LexicalScopes &LS,
249 const DIExpression *EntryExpr) {
250 VarLoc VL(MI, LS);
251 VL.Kind = EntryValueKind;
252 VL.Expr = EntryExpr;
253 return VL;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000254 }
255
Jeremy Morse61800a72019-10-04 10:53:47 +0000256 /// Copy the register location in DBG_VALUE MI, updating the register to
257 /// be NewReg.
258 static VarLoc CreateCopyLoc(const MachineInstr &MI, LexicalScopes &LS,
259 unsigned NewReg) {
260 VarLoc VL(MI, LS);
261 assert(VL.Kind == RegisterKind);
262 VL.Loc.RegNo = NewReg;
263 return VL;
264 }
265
266 /// Take the variable described by DBG_VALUE MI, and create a VarLoc
267 /// locating it in the specified spill location.
268 static VarLoc CreateSpillLoc(const MachineInstr &MI, unsigned SpillBase,
269 int SpillOffset, LexicalScopes &LS) {
270 VarLoc VL(MI, LS);
271 assert(VL.Kind == RegisterKind);
272 VL.Kind = SpillLocKind;
273 VL.Loc.SpillLocation = {SpillBase, SpillOffset};
274 return VL;
275 }
276
277 /// Create a DBG_VALUE representing this VarLoc in the given function.
278 /// Copies variable-specific information such as DILocalVariable and
279 /// inlining information from the original DBG_VALUE instruction, which may
280 /// have been several transfers ago.
281 MachineInstr *BuildDbgValue(MachineFunction &MF) const {
282 const DebugLoc &DbgLoc = MI.getDebugLoc();
283 bool Indirect = MI.isIndirectDebugValue();
284 const auto &IID = MI.getDesc();
285 const DILocalVariable *Var = MI.getDebugVariable();
286 const DIExpression *DIExpr = MI.getDebugExpression();
287
288 switch (Kind) {
289 case EntryValueKind:
290 // An entry value is a register location -- but with an updated
291 // expression.
292 return BuildMI(MF, DbgLoc, IID, Indirect, Loc.RegNo, Var, Expr);
293 case RegisterKind:
294 // Register locations are like the source DBG_VALUE, but with the
295 // register number from this VarLoc.
296 return BuildMI(MF, DbgLoc, IID, Indirect, Loc.RegNo, Var, DIExpr);
297 case SpillLocKind: {
298 // Spills are indirect DBG_VALUEs, with a base register and offset.
299 // Use the original DBG_VALUEs expression to build the spilt location
300 // on top of. FIXME: spill locations created before this pass runs
301 // are not recognized, and not handled here.
302 auto *SpillExpr = DIExpression::prepend(
303 DIExpr, DIExpression::ApplyOffset, Loc.SpillLocation.SpillOffset);
304 unsigned Base = Loc.SpillLocation.SpillBase;
305 return BuildMI(MF, DbgLoc, IID, true, Base, Var, SpillExpr);
306 }
307 case ImmediateKind: {
308 MachineOperand MO = MI.getOperand(0);
309 return BuildMI(MF, DbgLoc, IID, Indirect, MO, Var, DIExpr);
310 }
311 case InvalidKind:
312 llvm_unreachable("Tried to produce DBG_VALUE for invalid VarLoc");
313 }
Simon Pilgrim84f5cd72019-10-04 12:45:27 +0000314 llvm_unreachable("Unrecognized LiveDebugValues.VarLoc.Kind enum");
Jeremy Morse61800a72019-10-04 10:53:47 +0000315 }
316
317 /// Is the Loc field a constant or constant object?
Jeremy Morsebcff4172019-06-10 15:23:46 +0000318 bool isConstant() const { return Kind == ImmediateKind; }
319
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000320 /// If this variable is described by a register, return it,
321 /// otherwise return 0.
322 unsigned isDescribedByReg() const {
323 if (Kind == RegisterKind)
Adrian Prantl359846f2017-07-28 23:25:51 +0000324 return Loc.RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000325 return 0;
326 }
327
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000328 /// Determine whether the lexical scope of this value's debug location
329 /// dominates MBB.
330 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
331
Aaron Ballman615eb472017-10-15 14:32:27 +0000332#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Jeremy Morse61800a72019-10-04 10:53:47 +0000333 // TRI can be null.
334 void dump(const TargetRegisterInfo *TRI, raw_ostream &Out = dbgs()) const {
335 dbgs() << "VarLoc(";
336 switch (Kind) {
337 case RegisterKind:
338 case EntryValueKind:
339 dbgs() << printReg(Loc.RegNo, TRI);
340 break;
341 case SpillLocKind:
342 dbgs() << printReg(Loc.SpillLocation.SpillBase, TRI);
343 dbgs() << "[" << Loc.SpillLocation.SpillOffset << "]";
344 break;
345 case ImmediateKind:
346 dbgs() << Loc.Immediate;
347 break;
348 case InvalidKind:
349 llvm_unreachable("Invalid VarLoc in dump method");
350 }
351
352 dbgs() << ", \"" << Var.getVar()->getName() << "\", " << *Expr << ", ";
353 if (Var.getInlinedAt())
354 dbgs() << "!" << Var.getInlinedAt()->getMetadataID() << ")\n";
355 else
356 dbgs() << "(null))\n";
357 }
Matthias Braun194ded52017-01-28 06:53:55 +0000358#endif
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000359
360 bool operator==(const VarLoc &Other) const {
Jeremy Morsebcff4172019-06-10 15:23:46 +0000361 return Kind == Other.Kind && Var == Other.Var &&
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000362 Loc.Hash == Other.Loc.Hash && Expr == Other.Expr;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000363 }
364
Adrian Prantl7509d542016-05-26 21:42:47 +0000365 /// This operator guarantees that VarLocs are sorted by Variable first.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000366 bool operator<(const VarLoc &Other) const {
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000367 return std::tie(Var, Kind, Loc.Hash, Expr) <
368 std::tie(Other.Var, Other.Kind, Other.Loc.Hash, Other.Expr);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000369 }
Vikram TV859ad292015-12-16 11:09:48 +0000370 };
371
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000372 using DebugParamMap = SmallDenseMap<const DILocalVariable *, MachineInstr *>;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000373 using VarLocMap = UniqueVector<VarLoc>;
374 using VarLocSet = SparseBitVector<>;
375 using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000376 struct TransferDebugPair {
Jeremy Morse61800a72019-10-04 10:53:47 +0000377 MachineInstr *TransferInst; /// Instruction where this transfer occurs.
378 unsigned LocationID; /// Location number for the transfer dest.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000379 };
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000380 using TransferMap = SmallVector<TransferDebugPair, 4>;
Vikram TV859ad292015-12-16 11:09:48 +0000381
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000382 // Types for recording sets of variable fragments that overlap. For a given
383 // local variable, we record all other fragments of that variable that could
384 // overlap it, to reduce search time.
385 using FragmentOfVar =
386 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
387 using OverlapMap =
388 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
389
390 // Helper while building OverlapMap, a map of all fragments seen for a given
391 // DILocalVariable.
392 using VarToFragments =
393 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
394
Adrian Prantl7509d542016-05-26 21:42:47 +0000395 /// This holds the working set of currently open ranges. For fast
396 /// access, this is done both as a set of VarLocIDs, and a map of
397 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
398 /// previous open ranges for the same variable.
399 class OpenRangesSet {
400 VarLocSet VarLocs;
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000401 SmallDenseMap<DebugVariable, unsigned, 8> Vars;
402 OverlapMap &OverlappingFragments;
Adrian Prantl7509d542016-05-26 21:42:47 +0000403
404 public:
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000405 OpenRangesSet(OverlapMap &_OLapMap) : OverlappingFragments(_OLapMap) {}
406
Adrian Prantl7509d542016-05-26 21:42:47 +0000407 const VarLocSet &getVarLocs() const { return VarLocs; }
408
409 /// Terminate all open ranges for Var by removing it from the set.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000410 void erase(DebugVariable Var);
Adrian Prantl7509d542016-05-26 21:42:47 +0000411
412 /// Terminate all open ranges listed in \c KillSet by removing
413 /// them from the set.
414 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
415 VarLocs.intersectWithComplement(KillSet);
416 for (unsigned ID : KillSet)
417 Vars.erase(VarLocIDs[ID].Var);
418 }
419
420 /// Insert a new range into the set.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000421 void insert(unsigned VarLocID, DebugVariable Var) {
Adrian Prantl7509d542016-05-26 21:42:47 +0000422 VarLocs.set(VarLocID);
423 Vars.insert({Var, VarLocID});
424 }
425
Jeremy Morse67443c32019-08-21 09:22:31 +0000426 /// Insert a set of ranges.
427 void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map) {
428 for (unsigned Id : ToLoad) {
429 const VarLoc &Var = Map[Id];
430 insert(Id, Var.Var);
431 }
432 }
433
Adrian Prantl7509d542016-05-26 21:42:47 +0000434 /// Empty the set.
435 void clear() {
436 VarLocs.clear();
437 Vars.clear();
438 }
439
440 /// Return whether the set is empty or not.
441 bool empty() const {
442 assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
443 return VarLocs.empty();
444 }
445 };
446
Jeremy Morse5d9cd3b2019-09-06 10:08:22 +0000447 /// Tests whether this instruction is a spill to a stack location.
448 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
449
450 /// Decide if @MI is a spill instruction and return true if it is. We use 2
451 /// criteria to make this decision:
452 /// - Is this instruction a store to a spill slot?
453 /// - Is there a register operand that is both used and killed?
454 /// TODO: Store optimization can fold spills into other stores (including
455 /// other spills). We do not handle this yet (more than one memory operand).
456 bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
457 unsigned &Reg);
458
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000459 /// If a given instruction is identified as a spill, return the spill location
460 /// and set \p Reg to the spilled register.
461 Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
462 MachineFunction *MF,
463 unsigned &Reg);
464 /// Given a spill instruction, extract the register and offset used to
465 /// address the spill location in a target independent way.
466 VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000467 void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
468 TransferMap &Transfers, VarLocMap &VarLocIDs,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000469 unsigned OldVarID, TransferKind Kind,
470 unsigned NewReg = 0);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000471
Adrian Prantl7509d542016-05-26 21:42:47 +0000472 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000473 VarLocMap &VarLocIDs);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000474 void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
475 VarLocMap &VarLocIDs, TransferMap &Transfers);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000476 void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
477 VarLocMap &VarLocIDs, TransferMap &Transfers,
478 DebugParamMap &DebugEntryVals,
479 SparseBitVector<> &KillSet);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000480 void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
481 VarLocMap &VarLocIDs, TransferMap &Transfers);
Adrian Prantl7509d542016-05-26 21:42:47 +0000482 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000483 VarLocMap &VarLocIDs, TransferMap &Transfers,
484 DebugParamMap &DebugEntryVals);
Jeremy Morse67443c32019-08-21 09:22:31 +0000485 bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
486 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
Nikola Prica441ad622019-05-27 13:51:30 +0000487
Jeremy Morse67443c32019-08-21 09:22:31 +0000488 void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000489 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000490 TransferMap &Transfers, DebugParamMap &DebugEntryVals,
Jeremy Morse313d2ce2019-08-29 10:53:29 +0000491 OverlapMap &OverlapFragments,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000492 VarToFragments &SeenFragments);
Vikram TV859ad292015-12-16 11:09:48 +0000493
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000494 void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
495 OverlapMap &OLapMap);
496
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000497 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000498 const VarLocMap &VarLocIDs,
Vedant Kumar8c466682018-10-05 21:44:15 +0000499 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
Jeremy Morse67443c32019-08-21 09:22:31 +0000500 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks,
501 VarLocInMBB &PendingInLocs);
502
503 /// Create DBG_VALUE insts for inlocs that have been propagated but
504 /// had their instruction creation deferred.
505 void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
Vikram TV859ad292015-12-16 11:09:48 +0000506
507 bool ExtendRanges(MachineFunction &MF);
508
509public:
510 static char ID;
511
512 /// Default construct and initialize the pass.
513 LiveDebugValues();
514
515 /// Tell the pass manager which passes we depend on and what
516 /// information we preserve.
517 void getAnalysisUsage(AnalysisUsage &AU) const override;
518
Derek Schuffad154c82016-03-28 17:05:30 +0000519 MachineFunctionProperties getRequiredProperties() const override {
520 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000521 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000522 }
523
Vikram TV859ad292015-12-16 11:09:48 +0000524 /// Print to ostream with a message.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000525 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
526 const VarLocMap &VarLocIDs, const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000527 raw_ostream &Out) const;
528
529 /// Calculate the liveness information for the given machine function.
530 bool runOnMachineFunction(MachineFunction &MF) override;
531};
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000532
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000533} // end anonymous namespace
Vikram TV859ad292015-12-16 11:09:48 +0000534
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000535namespace llvm {
536
537template <> struct DenseMapInfo<LiveDebugValues::DebugVariable> {
538 using DV = LiveDebugValues::DebugVariable;
539 using OptFragmentInfo = LiveDebugValues::OptFragmentInfo;
540 using FragmentInfo = LiveDebugValues::FragmentInfo;
541
542 // Empty key: no key should be generated that has no DILocalVariable.
543 static inline DV getEmptyKey() {
544 return DV(nullptr, OptFragmentInfo(), nullptr);
545 }
546
547 // Difference in tombstone is that the Optional is meaningful
548 static inline DV getTombstoneKey() {
549 return DV(nullptr, OptFragmentInfo({0, 0}), nullptr);
550 }
551
552 static unsigned getHashValue(const DV &D) {
553 unsigned HV = 0;
554 const OptFragmentInfo &Fragment = D.getFragment();
555 if (Fragment)
556 HV = DenseMapInfo<FragmentInfo>::getHashValue(*Fragment);
557
558 return hash_combine(D.getVar(), HV, D.getInlinedAt());
559 }
560
561 static bool isEqual(const DV &A, const DV &B) { return A == B; }
562};
563
David Stenberg1278a192019-06-13 14:02:55 +0000564} // namespace llvm
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000565
Vikram TV859ad292015-12-16 11:09:48 +0000566//===----------------------------------------------------------------------===//
567// Implementation
568//===----------------------------------------------------------------------===//
569
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000570const DIExpression::FragmentInfo
571 LiveDebugValues::DebugVariable::DefaultFragment = {
572 std::numeric_limits<uint64_t>::max(),
573 std::numeric_limits<uint64_t>::min()};
574
Vikram TV859ad292015-12-16 11:09:48 +0000575char LiveDebugValues::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000576
Vikram TV859ad292015-12-16 11:09:48 +0000577char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000578
Matthias Braun1527baa2017-05-25 21:26:32 +0000579INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
Vikram TV859ad292015-12-16 11:09:48 +0000580 false, false)
581
582/// Default construct and initialize the pass.
583LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
584 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
585}
586
587/// Tell the pass manager which passes we depend on and what information we
588/// preserve.
589void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
Matt Arsenaultb1630a12016-06-08 05:18:01 +0000590 AU.setPreservesCFG();
Vikram TV859ad292015-12-16 11:09:48 +0000591 MachineFunctionPass::getAnalysisUsage(AU);
592}
593
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000594/// Erase a variable from the set of open ranges, and additionally erase any
595/// fragments that may overlap it.
596void LiveDebugValues::OpenRangesSet::erase(DebugVariable Var) {
597 // Erasure helper.
598 auto DoErase = [this](DebugVariable VarToErase) {
599 auto It = Vars.find(VarToErase);
600 if (It != Vars.end()) {
601 unsigned ID = It->second;
602 VarLocs.reset(ID);
603 Vars.erase(It);
604 }
605 };
606
607 // Erase the variable/fragment that ends here.
608 DoErase(Var);
609
610 // Extract the fragment. Interpret an empty fragment as one that covers all
611 // possible bits.
612 FragmentInfo ThisFragment = Var.getFragmentDefault();
613
614 // There may be fragments that overlap the designated fragment. Look them up
615 // in the pre-computed overlap map, and erase them too.
616 auto MapIt = OverlappingFragments.find({Var.getVar(), ThisFragment});
617 if (MapIt != OverlappingFragments.end()) {
618 for (auto Fragment : MapIt->second) {
619 LiveDebugValues::OptFragmentInfo FragmentHolder;
620 if (!DebugVariable::isFragmentDefault(Fragment))
621 FragmentHolder = LiveDebugValues::OptFragmentInfo(Fragment);
622 DoErase({Var.getVar(), FragmentHolder, Var.getInlinedAt()});
623 }
624 }
625}
626
Vikram TV859ad292015-12-16 11:09:48 +0000627//===----------------------------------------------------------------------===//
628// Debug Range Extension Implementation
629//===----------------------------------------------------------------------===//
630
Matthias Braun194ded52017-01-28 06:53:55 +0000631#ifndef NDEBUG
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000632void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
633 const VarLocInMBB &V,
634 const VarLocMap &VarLocIDs,
635 const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000636 raw_ostream &Out) const {
Keith Walkerf83a19f2016-09-20 16:04:31 +0000637 Out << '\n' << msg << '\n';
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000638 for (const MachineBasicBlock &BB : MF) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000639 const VarLocSet &L = V.lookup(&BB);
640 if (L.empty())
641 continue;
642 Out << "MBB: " << BB.getNumber() << ":\n";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000643 for (unsigned VLL : L) {
644 const VarLoc &VL = VarLocIDs[VLL];
Adrian Prantl7509d542016-05-26 21:42:47 +0000645 Out << " Var: " << VL.Var.getVar()->getName();
Vikram TV859ad292015-12-16 11:09:48 +0000646 Out << " MI: ";
Jeremy Morse61800a72019-10-04 10:53:47 +0000647 VL.dump(TRI, Out);
Vikram TV859ad292015-12-16 11:09:48 +0000648 }
649 }
650 Out << "\n";
651}
Matthias Braun194ded52017-01-28 06:53:55 +0000652#endif
Vikram TV859ad292015-12-16 11:09:48 +0000653
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000654LiveDebugValues::VarLoc::SpillLoc
655LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000656 assert(MI.hasOneMemOperand() &&
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000657 "Spill instruction does not have exactly one memory operand?");
658 auto MMOI = MI.memoperands_begin();
659 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
660 assert(PVal->kind() == PseudoSourceValue::FixedStack &&
661 "Inconsistent memory operand in spill instruction");
662 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
663 const MachineBasicBlock *MBB = MI.getParent();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000664 unsigned Reg;
665 int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
666 return {Reg, Offset};
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000667}
668
Vikram TV859ad292015-12-16 11:09:48 +0000669/// End all previous ranges related to @MI and start a new range from @MI
670/// if it is a DBG_VALUE instr.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000671void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000672 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000673 VarLocMap &VarLocIDs) {
Vikram TV859ad292015-12-16 11:09:48 +0000674 if (!MI.isDebugValue())
675 return;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000676 const DILocalVariable *Var = MI.getDebugVariable();
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000677 const DIExpression *Expr = MI.getDebugExpression();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000678 const DILocation *DebugLoc = MI.getDebugLoc();
679 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
680 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
Vikram TV859ad292015-12-16 11:09:48 +0000681 "Expected inlined-at fields to agree");
Vikram TV859ad292015-12-16 11:09:48 +0000682
683 // End all previous ranges of Var.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000684 DebugVariable V(Var, Expr, InlinedAt);
Adrian Prantl7509d542016-05-26 21:42:47 +0000685 OpenRanges.erase(V);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000686
687 // Add the VarLoc to OpenRanges from this DBG_VALUE.
Jeremy Morsebcff4172019-06-10 15:23:46 +0000688 unsigned ID;
Djordje Todorovic774eabd2019-06-27 18:12:04 +0000689 if (isDbgValueDescribedByReg(MI) || MI.getOperand(0).isImm() ||
690 MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) {
Jeremy Morsebcff4172019-06-10 15:23:46 +0000691 // Use normal VarLoc constructor for registers and immediates.
Djordje Todorovic774eabd2019-06-27 18:12:04 +0000692 VarLoc VL(MI, LS);
Jeremy Morsebcff4172019-06-10 15:23:46 +0000693 ID = VarLocIDs.insert(VL);
Adrian Prantl7509d542016-05-26 21:42:47 +0000694 OpenRanges.insert(ID, VL.Var);
Jeremy Morsebcff4172019-06-10 15:23:46 +0000695 } else if (MI.hasOneMemOperand()) {
Jeremy Morse8b593482019-08-16 10:04:17 +0000696 llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
Jeremy Morsebcff4172019-06-10 15:23:46 +0000697 } else {
698 // This must be an undefined location. We should leave OpenRanges closed.
699 assert(MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 &&
700 "Unexpected non-undef DBG_VALUE encountered");
Adrian Prantl7509d542016-05-26 21:42:47 +0000701 }
Vikram TV859ad292015-12-16 11:09:48 +0000702}
703
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000704void LiveDebugValues::emitEntryValues(MachineInstr &MI,
705 OpenRangesSet &OpenRanges,
706 VarLocMap &VarLocIDs,
707 TransferMap &Transfers,
708 DebugParamMap &DebugEntryVals,
709 SparseBitVector<> &KillSet) {
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000710 for (unsigned ID : KillSet) {
711 if (!VarLocIDs[ID].Var.getVar()->isParameter())
712 continue;
713
714 const MachineInstr *CurrDebugInstr = &VarLocIDs[ID].MI;
715
716 // If parameter's DBG_VALUE is not in the map that means we can't
717 // generate parameter's entry value.
718 if (!DebugEntryVals.count(CurrDebugInstr->getDebugVariable()))
719 continue;
720
721 auto ParamDebugInstr = DebugEntryVals[CurrDebugInstr->getDebugVariable()];
722 DIExpression *NewExpr = DIExpression::prepend(
723 ParamDebugInstr->getDebugExpression(), DIExpression::EntryValue);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000724
Jeremy Morse61800a72019-10-04 10:53:47 +0000725 VarLoc EntryLoc = VarLoc::CreateEntryLoc(*ParamDebugInstr, LS, NewExpr);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000726
Jeremy Morse61800a72019-10-04 10:53:47 +0000727 unsigned EntryValLocID = VarLocIDs.insert(EntryLoc);
728 Transfers.push_back({&MI, EntryValLocID});
729 OpenRanges.insert(EntryValLocID, EntryLoc.Var);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000730 }
731}
732
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000733/// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
734/// with \p OldVarID should be deleted form \p OpenRanges and replaced with
735/// new VarLoc. If \p NewReg is different than default zero value then the
736/// new location will be register location created by the copy like instruction,
737/// otherwise it is variable's location on the stack.
738void LiveDebugValues::insertTransferDebugPair(
739 MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000740 VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
741 unsigned NewReg) {
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000742 const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000743
Nikola Prica2d0106a2019-06-03 09:48:29 +0000744 auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &DebugInstr,
Jeremy Morse61800a72019-10-04 10:53:47 +0000745 &VarLocIDs](VarLoc &VL) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000746 unsigned LocId = VarLocIDs.insert(VL);
Nikola Prica2d0106a2019-06-03 09:48:29 +0000747
748 // Close this variable's previous location range.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000749 DebugVariable V(*DebugInstr);
Nikola Prica2d0106a2019-06-03 09:48:29 +0000750 OpenRanges.erase(V);
751
Jeremy Morse61800a72019-10-04 10:53:47 +0000752 // Record the new location as an open range, and a postponed transfer
753 // inserting a DBG_VALUE for this location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000754 OpenRanges.insert(LocId, VL.Var);
Jeremy Morse61800a72019-10-04 10:53:47 +0000755 TransferDebugPair MIP = {&MI, LocId};
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000756 Transfers.push_back(MIP);
757 };
758
759 // End all previous ranges of Var.
760 OpenRanges.erase(VarLocIDs[OldVarID].Var);
761 switch (Kind) {
762 case TransferKind::TransferCopy: {
763 assert(NewReg &&
764 "No register supplied when handling a copy of a debug value");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000765 // Create a DBG_VALUE instruction to describe the Var in its new
766 // register location.
Jeremy Morse61800a72019-10-04 10:53:47 +0000767 VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg);
768 ProcessVarLoc(VL);
769 LLVM_DEBUG({
770 dbgs() << "Creating VarLoc for register copy:";
771 VL.dump(TRI);
772 });
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000773 return;
774 }
775 case TransferKind::TransferSpill: {
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000776 // Create a DBG_VALUE instruction to describe the Var in its spilled
777 // location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000778 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
Jeremy Morse61800a72019-10-04 10:53:47 +0000779 VarLoc VL = VarLoc::CreateSpillLoc(*DebugInstr, SpillLocation.SpillBase,
780 SpillLocation.SpillOffset, LS);
781 ProcessVarLoc(VL);
782 LLVM_DEBUG({
783 dbgs() << "Creating VarLoc for spill:";
784 VL.dump(TRI);
785 });
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000786 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000787 }
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000788 case TransferKind::TransferRestore: {
789 assert(NewReg &&
790 "No register supplied when handling a restore of a debug value");
791 MachineFunction *MF = MI.getMF();
792 DIBuilder DIB(*const_cast<Function &>(MF->getFunction()).getParent());
Jeremy Morse8b593482019-08-16 10:04:17 +0000793 // DebugInstr refers to the pre-spill location, therefore we can reuse
794 // its expression.
Jeremy Morse61800a72019-10-04 10:53:47 +0000795 VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg);
796 ProcessVarLoc(VL);
797 LLVM_DEBUG({
798 dbgs() << "Creating VarLoc for restore:";
799 VL.dump(TRI);
800 });
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000801 return;
802 }
803 }
804 llvm_unreachable("Invalid transfer kind");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000805}
806
Vikram TV859ad292015-12-16 11:09:48 +0000807/// A definition of a register may mark the end of a range.
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000808void LiveDebugValues::transferRegisterDef(
809 MachineInstr &MI, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
810 TransferMap &Transfers, DebugParamMap &DebugEntryVals) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +0000811 MachineFunction *MF = MI.getMF();
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000812 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
813 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000814 SparseBitVector<> KillSet;
Vikram TV859ad292015-12-16 11:09:48 +0000815 for (const MachineOperand &MO : MI.operands()) {
Adrian Prantlea8880b2017-03-03 01:08:25 +0000816 // Determine whether the operand is a register def. Assume that call
817 // instructions never clobber SP, because some backends (e.g., AArch64)
818 // never list SP in the regmask.
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000819 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000820 Register::isPhysicalRegister(MO.getReg()) &&
Adrian Prantlea8880b2017-03-03 01:08:25 +0000821 !(MI.isCall() && MO.getReg() == SP)) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000822 // Remove ranges of all aliased registers.
823 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
Adrian Prantl7509d542016-05-26 21:42:47 +0000824 for (unsigned ID : OpenRanges.getVarLocs())
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000825 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
826 KillSet.set(ID);
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000827 } else if (MO.isRegMask()) {
828 // Remove ranges of all clobbered registers. Register masks don't usually
829 // list SP as preserved. While the debug info may be off for an
830 // instruction or two around callee-cleanup calls, transferring the
831 // DEBUG_VALUE across the call is still a better user experience.
Adrian Prantl7509d542016-05-26 21:42:47 +0000832 for (unsigned ID : OpenRanges.getVarLocs()) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000833 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
834 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
835 KillSet.set(ID);
836 }
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000837 }
Vikram TV859ad292015-12-16 11:09:48 +0000838 }
Adrian Prantl7509d542016-05-26 21:42:47 +0000839 OpenRanges.erase(KillSet, VarLocIDs);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000840
841 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
842 auto &TM = TPC->getTM<TargetMachine>();
843 if (TM.Options.EnableDebugEntryValues)
844 emitEntryValues(MI, OpenRanges, VarLocIDs, Transfers, DebugEntryVals,
845 KillSet);
846 }
Vikram TV859ad292015-12-16 11:09:48 +0000847}
848
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000849bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
Jeremy Morse5d9cd3b2019-09-06 10:08:22 +0000850 MachineFunction *MF) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000851 // TODO: Handle multiple stores folded into one.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000852 if (!MI.hasOneMemOperand())
853 return false;
854
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000855 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
856 return false; // This is not a spill instruction, since no valid size was
857 // returned from either function.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000858
Jeremy Morse5d9cd3b2019-09-06 10:08:22 +0000859 return true;
860}
861
862bool LiveDebugValues::isLocationSpill(const MachineInstr &MI,
863 MachineFunction *MF, unsigned &Reg) {
864 if (!isSpillInstruction(MI, MF))
865 return false;
866
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000867 auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
868 if (!MO.isReg() || !MO.isUse()) {
869 Reg = 0;
870 return false;
871 }
872 Reg = MO.getReg();
873 return MO.isKill();
874 };
875
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000876 for (const MachineOperand &MO : MI.operands()) {
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000877 // In a spill instruction generated by the InlineSpiller the spilled
878 // register has its kill flag set.
879 if (isKilledReg(MO, Reg))
880 return true;
881 if (Reg != 0) {
882 // Check whether next instruction kills the spilled register.
883 // FIXME: Current solution does not cover search for killed register in
884 // bundles and instructions further down the chain.
885 auto NextI = std::next(MI.getIterator());
886 // Skip next instruction that points to basic block end iterator.
887 if (MI.getParent()->end() == NextI)
888 continue;
889 unsigned RegNext;
890 for (const MachineOperand &MONext : NextI->operands()) {
891 // Return true if we came across the register from the
892 // previous spill instruction that is killed in NextI.
893 if (isKilledReg(MONext, RegNext) && RegNext == Reg)
894 return true;
895 }
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000896 }
897 }
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000898 // Return false if we didn't find spilled register.
899 return false;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000900}
901
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000902Optional<LiveDebugValues::VarLoc::SpillLoc>
903LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
904 MachineFunction *MF, unsigned &Reg) {
905 if (!MI.hasOneMemOperand())
906 return None;
907
908 // FIXME: Handle folded restore instructions with more than one memory
909 // operand.
910 if (MI.getRestoreSize(TII)) {
911 Reg = MI.getOperand(0).getReg();
912 return extractSpillBaseRegAndOffset(MI);
913 }
914 return None;
915}
916
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000917/// A spilled register may indicate that we have to end the current range of
918/// a variable and create a new one for the spill location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000919/// A restored register may indicate the reverse situation.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000920/// We don't want to insert any instructions in process(), so we just create
921/// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000922/// It will be inserted into the BB when we're done iterating over the
923/// instructions.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000924void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
925 OpenRangesSet &OpenRanges,
926 VarLocMap &VarLocIDs,
927 TransferMap &Transfers) {
Wolfgang Piebfacd0522019-01-30 20:37:14 +0000928 MachineFunction *MF = MI.getMF();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000929 TransferKind TKind;
930 unsigned Reg;
931 Optional<VarLoc::SpillLoc> Loc;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000932
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000933 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
934
Jeremy Morse5d9cd3b2019-09-06 10:08:22 +0000935 // First, if there are any DBG_VALUEs pointing at a spill slot that is
936 // written to, then close the variable location. The value in memory
937 // will have changed.
938 VarLocSet KillSet;
939 if (isSpillInstruction(MI, MF)) {
940 Loc = extractSpillBaseRegAndOffset(MI);
941 for (unsigned ID : OpenRanges.getVarLocs()) {
942 const VarLoc &VL = VarLocIDs[ID];
943 if (VL.Kind == VarLoc::SpillLocKind && VL.Loc.SpillLocation == *Loc) {
944 // This location is overwritten by the current instruction -- terminate
945 // the open range, and insert an explicit DBG_VALUE $noreg.
946 //
947 // Doing this at a later stage would require re-interpreting all
948 // DBG_VALUes and DIExpressions to identify whether they point at
949 // memory, and then analysing all memory writes to see if they
950 // overwrite that memory, which is expensive.
951 //
952 // At this stage, we already know which DBG_VALUEs are for spills and
953 // where they are located; it's best to fix handle overwrites now.
954 KillSet.set(ID);
Jeremy Morse61800a72019-10-04 10:53:47 +0000955 VarLoc UndefVL = VarLoc::CreateCopyLoc(VL.MI, LS, 0);
956 unsigned UndefLocID = VarLocIDs.insert(UndefVL);
957 Transfers.push_back({&MI, UndefLocID});
Jeremy Morse5d9cd3b2019-09-06 10:08:22 +0000958 }
959 }
960 OpenRanges.erase(KillSet, VarLocIDs);
961 }
962
963 // Try to recognise spill and restore instructions that may create a new
964 // variable location.
965 if (isLocationSpill(MI, MF, Reg)) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000966 TKind = TransferKind::TransferSpill;
967 LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
968 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
969 << "\n");
970 } else {
971 if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
972 return;
973 TKind = TransferKind::TransferRestore;
974 LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
975 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
976 << "\n");
977 }
978 // Check if the register or spill location is the location of a debug value.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000979 for (unsigned ID : OpenRanges.getVarLocs()) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000980 if (TKind == TransferKind::TransferSpill &&
Jeremy Morse8b593482019-08-16 10:04:17 +0000981 VarLocIDs[ID].isDescribedByReg() == Reg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000982 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
983 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000984 } else if (TKind == TransferKind::TransferRestore &&
Jeremy Morseca0e4b32019-08-29 11:20:54 +0000985 VarLocIDs[ID].Kind == VarLoc::SpillLocKind &&
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000986 VarLocIDs[ID].Loc.SpillLocation == *Loc) {
987 LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
988 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
989 } else
990 continue;
991 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
992 Reg);
993 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000994 }
995}
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000996
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000997/// If \p MI is a register copy instruction, that copies a previously tracked
998/// value from one register to another register that is callee saved, we
999/// create new DBG_VALUE instruction described with copy destination register.
1000void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
1001 OpenRangesSet &OpenRanges,
1002 VarLocMap &VarLocIDs,
1003 TransferMap &Transfers) {
1004 const MachineOperand *SrcRegOp, *DestRegOp;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001005
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001006 if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
1007 !DestRegOp->isDef())
1008 return;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001009
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001010 auto isCalleSavedReg = [&](unsigned Reg) {
1011 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1012 if (CalleeSavedRegs.test(*RAI))
1013 return true;
1014 return false;
1015 };
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001016
Daniel Sanders0c476112019-08-15 19:22:08 +00001017 Register SrcReg = SrcRegOp->getReg();
1018 Register DestReg = DestRegOp->getReg();
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001019
1020 // We want to recognize instructions where destination register is callee
1021 // saved register. If register that could be clobbered by the call is
1022 // included, there would be a great chance that it is going to be clobbered
1023 // soon. It is more likely that previous register location, which is callee
1024 // saved, is going to stay unclobbered longer, even if it is killed.
1025 if (!isCalleSavedReg(DestReg))
1026 return;
1027
1028 for (unsigned ID : OpenRanges.getVarLocs()) {
1029 if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
1030 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001031 TransferKind::TransferCopy, DestReg);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001032 return;
1033 }
1034 }
1035}
1036
Vikram TV859ad292015-12-16 11:09:48 +00001037/// Terminate all open ranges at the end of the current basic block.
Jeremy Morse67443c32019-08-21 09:22:31 +00001038bool LiveDebugValues::transferTerminator(MachineBasicBlock *CurMBB,
1039 OpenRangesSet &OpenRanges,
1040 VarLocInMBB &OutLocs,
1041 const VarLocMap &VarLocIDs) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001042 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +00001043
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001044 LLVM_DEBUG(for (unsigned ID
1045 : OpenRanges.getVarLocs()) {
1046 // Copy OpenRanges to OutLocs, if not already present.
Vedant Kumar9b558382018-10-05 21:44:00 +00001047 dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
Jeremy Morse61800a72019-10-04 10:53:47 +00001048 VarLocIDs[ID].dump(TRI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001049 });
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001050 VarLocSet &VLS = OutLocs[CurMBB];
Jeremy Morse0ae54982019-08-23 16:33:42 +00001051 Changed = VLS != OpenRanges.getVarLocs();
Nikola Prica2d0106a2019-06-03 09:48:29 +00001052 // New OutLocs set may be different due to spill, restore or register
1053 // copy instruction processing.
1054 if (Changed)
1055 VLS = OpenRanges.getVarLocs();
Vikram TV859ad292015-12-16 11:09:48 +00001056 OpenRanges.clear();
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001057 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +00001058}
1059
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001060/// Accumulate a mapping between each DILocalVariable fragment and other
1061/// fragments of that DILocalVariable which overlap. This reduces work during
1062/// the data-flow stage from "Find any overlapping fragments" to "Check if the
1063/// known-to-overlap fragments are present".
1064/// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
1065/// fragment usage.
1066/// \param SeenFragments Map from DILocalVariable to all fragments of that
1067/// Variable which are known to exist.
1068/// \param OverlappingFragments The overlap map being constructed, from one
1069/// Var/Fragment pair to a vector of fragments known to overlap.
1070void LiveDebugValues::accumulateFragmentMap(MachineInstr &MI,
1071 VarToFragments &SeenFragments,
1072 OverlapMap &OverlappingFragments) {
1073 DebugVariable MIVar(MI);
1074 FragmentInfo ThisFragment = MIVar.getFragmentDefault();
1075
1076 // If this is the first sighting of this variable, then we are guaranteed
1077 // there are currently no overlapping fragments either. Initialize the set
1078 // of seen fragments, record no overlaps for the current one, and return.
1079 auto SeenIt = SeenFragments.find(MIVar.getVar());
1080 if (SeenIt == SeenFragments.end()) {
1081 SmallSet<FragmentInfo, 4> OneFragment;
1082 OneFragment.insert(ThisFragment);
1083 SeenFragments.insert({MIVar.getVar(), OneFragment});
1084
1085 OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
1086 return;
1087 }
1088
1089 // If this particular Variable/Fragment pair already exists in the overlap
1090 // map, it has already been accounted for.
1091 auto IsInOLapMap =
1092 OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
1093 if (!IsInOLapMap.second)
1094 return;
1095
1096 auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1097 auto &AllSeenFragments = SeenIt->second;
1098
1099 // Otherwise, examine all other seen fragments for this variable, with "this"
1100 // fragment being a previously unseen fragment. Record any pair of
1101 // overlapping fragments.
1102 for (auto &ASeenFragment : AllSeenFragments) {
1103 // Does this previously seen fragment overlap?
1104 if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1105 // Yes: Mark the current fragment as being overlapped.
1106 ThisFragmentsOverlaps.push_back(ASeenFragment);
1107 // Mark the previously seen fragment as being overlapped by the current
1108 // one.
1109 auto ASeenFragmentsOverlaps =
1110 OverlappingFragments.find({MIVar.getVar(), ASeenFragment});
1111 assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
1112 "Previously seen var fragment has no vector of overlaps");
1113 ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1114 }
1115 }
1116
1117 AllSeenFragments.insert(ThisFragment);
1118}
1119
Vikram TV859ad292015-12-16 11:09:48 +00001120/// This routine creates OpenRanges and OutLocs.
Jeremy Morse67443c32019-08-21 09:22:31 +00001121void LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001122 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001123 TransferMap &Transfers,
1124 DebugParamMap &DebugEntryVals,
Jeremy Morsed2cd9c22019-06-13 13:11:57 +00001125 OverlapMap &OverlapFragments,
1126 VarToFragments &SeenFragments) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001127 transferDebugValue(MI, OpenRanges, VarLocIDs);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001128 transferRegisterDef(MI, OpenRanges, VarLocIDs, Transfers,
1129 DebugEntryVals);
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001130 transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
1131 transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
Vikram TV859ad292015-12-16 11:09:48 +00001132}
1133
1134/// This routine joins the analysis results of all incoming edges in @MBB by
1135/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1136/// source variable in all the predecessors of @MBB reside in the same location.
Vedant Kumar8c466682018-10-05 21:44:15 +00001137bool LiveDebugValues::join(
1138 MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1139 const VarLocMap &VarLocIDs,
1140 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
Jeremy Morse67443c32019-08-21 09:22:31 +00001141 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks,
1142 VarLocInMBB &PendingInLocs) {
Vedant Kumar9b558382018-10-05 21:44:00 +00001143 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001144 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +00001145
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001146 VarLocSet InLocsT; // Temporary incoming locations.
Vikram TV859ad292015-12-16 11:09:48 +00001147
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001148 // For all predecessors of this MBB, find the set of VarLocs that
1149 // can be joined.
Keith Walker83ebef52016-09-27 16:46:07 +00001150 int NumVisited = 0;
Vikram TV859ad292015-12-16 11:09:48 +00001151 for (auto p : MBB.predecessors()) {
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001152 // Ignore backedges if we have not visited the predecessor yet. As the
1153 // predecessor hasn't yet had locations propagated into it, most locations
1154 // will not yet be valid, so treat them as all being uninitialized and
1155 // potentially valid. If a location guessed to be correct here is
1156 // invalidated later, we will remove it when we revisit this block.
Vedant Kumar9b558382018-10-05 21:44:00 +00001157 if (!Visited.count(p)) {
1158 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
1159 << "\n");
Keith Walker83ebef52016-09-27 16:46:07 +00001160 continue;
Vedant Kumar9b558382018-10-05 21:44:00 +00001161 }
Vikram TV859ad292015-12-16 11:09:48 +00001162 auto OL = OutLocs.find(p);
1163 // Join is null in case of empty OutLocs from any of the pred.
1164 if (OL == OutLocs.end())
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001165 return false;
Vikram TV859ad292015-12-16 11:09:48 +00001166
Keith Walker83ebef52016-09-27 16:46:07 +00001167 // Just copy over the Out locs to incoming locs for the first visited
1168 // predecessor, and for all other predecessors join the Out locs.
1169 if (!NumVisited)
Vikram TV859ad292015-12-16 11:09:48 +00001170 InLocsT = OL->second;
Keith Walker83ebef52016-09-27 16:46:07 +00001171 else
1172 InLocsT &= OL->second;
Vedant Kumar9b558382018-10-05 21:44:00 +00001173
1174 LLVM_DEBUG({
1175 if (!InLocsT.empty()) {
1176 for (auto ID : InLocsT)
1177 dbgs() << " gathered candidate incoming var: "
1178 << VarLocIDs[ID].Var.getVar()->getName() << "\n";
1179 }
1180 });
1181
Keith Walker83ebef52016-09-27 16:46:07 +00001182 NumVisited++;
Vikram TV859ad292015-12-16 11:09:48 +00001183 }
1184
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001185 // Filter out DBG_VALUES that are out of scope.
1186 VarLocSet KillSet;
Vedant Kumar8c466682018-10-05 21:44:15 +00001187 bool IsArtificial = ArtificialBlocks.count(&MBB);
1188 if (!IsArtificial) {
1189 for (auto ID : InLocsT) {
1190 if (!VarLocIDs[ID].dominates(MBB)) {
1191 KillSet.set(ID);
1192 LLVM_DEBUG({
1193 auto Name = VarLocIDs[ID].Var.getVar()->getName();
1194 dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
1195 });
1196 }
Vedant Kumar9b558382018-10-05 21:44:00 +00001197 }
1198 }
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001199 InLocsT.intersectWithComplement(KillSet);
1200
Keith Walker83ebef52016-09-27 16:46:07 +00001201 // As we are processing blocks in reverse post-order we
1202 // should have processed at least one predecessor, unless it
1203 // is the entry block which has no predecessor.
1204 assert((NumVisited || MBB.pred_empty()) &&
1205 "Should have processed at least one predecessor");
Vikram TV859ad292015-12-16 11:09:48 +00001206
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001207 VarLocSet &ILS = InLocs[&MBB];
Jeremy Morse67443c32019-08-21 09:22:31 +00001208 VarLocSet &Pending = PendingInLocs[&MBB];
Vikram TV859ad292015-12-16 11:09:48 +00001209
Jeremy Morse67443c32019-08-21 09:22:31 +00001210 // New locations will have DBG_VALUE insts inserted at the start of the
1211 // block, after location propagation has finished. Record the insertions
1212 // that we need to perform in the Pending set.
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001213 VarLocSet Diff = InLocsT;
1214 Diff.intersectWithComplement(ILS);
1215 for (auto ID : Diff) {
Jeremy Morse67443c32019-08-21 09:22:31 +00001216 Pending.set(ID);
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001217 ILS.set(ID);
1218 ++NumInserted;
1219 Changed = true;
Vikram TV859ad292015-12-16 11:09:48 +00001220 }
Jeremy Morse0ae54982019-08-23 16:33:42 +00001221
1222 // We may have lost locations by learning about a predecessor that either
1223 // loses or moves a variable. Find any locations in ILS that are not in the
1224 // new in-locations, and delete those.
1225 VarLocSet Removed = ILS;
1226 Removed.intersectWithComplement(InLocsT);
1227 for (auto ID : Removed) {
1228 Pending.reset(ID);
1229 ILS.reset(ID);
1230 ++NumRemoved;
1231 Changed = true;
1232 }
1233
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001234 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +00001235}
1236
Jeremy Morse67443c32019-08-21 09:22:31 +00001237void LiveDebugValues::flushPendingLocs(VarLocInMBB &PendingInLocs,
1238 VarLocMap &VarLocIDs) {
1239 // PendingInLocs records all locations propagated into blocks, which have
1240 // not had DBG_VALUE insts created. Go through and create those insts now.
1241 for (auto &Iter : PendingInLocs) {
1242 // Map is keyed on a constant pointer, unwrap it so we can insert insts.
1243 auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
1244 VarLocSet &Pending = Iter.second;
1245
1246 for (unsigned ID : Pending) {
1247 // The ID location is live-in to MBB -- work out what kind of machine
1248 // location it is and create a DBG_VALUE.
1249 const VarLoc &DiffIt = VarLocIDs[ID];
Jeremy Morse61800a72019-10-04 10:53:47 +00001250 MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent());
1251 MBB.insert(MBB.instr_begin(), MI);
Jeremy Morse67443c32019-08-21 09:22:31 +00001252
Jeremy Morsec8c5f2a2019-09-04 10:18:03 +00001253 (void)MI;
Jeremy Morse67443c32019-08-21 09:22:31 +00001254 LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
1255 }
1256 }
1257}
1258
Vikram TV859ad292015-12-16 11:09:48 +00001259/// Calculate the liveness information for the given machine function and
1260/// extend ranges across basic blocks.
1261bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001262 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
Vikram TV859ad292015-12-16 11:09:48 +00001263
1264 bool Changed = false;
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001265 bool OLChanged = false;
1266 bool MBBJoined = false;
Vikram TV859ad292015-12-16 11:09:48 +00001267
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001268 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
1269 OverlapMap OverlapFragments; // Map of overlapping variable fragments
1270 OpenRangesSet OpenRanges(OverlapFragments);
1271 // Ranges that are open until end of bb.
1272 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
1273 VarLocInMBB InLocs; // Ranges that are incoming after joining.
1274 TransferMap Transfers; // DBG_VALUEs associated with spills.
Jeremy Morse67443c32019-08-21 09:22:31 +00001275 VarLocInMBB PendingInLocs; // Ranges that are incoming after joining, but
1276 // that we have deferred creating DBG_VALUE insts
1277 // for immediately.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001278
1279 VarToFragments SeenFragments;
Vikram TV859ad292015-12-16 11:09:48 +00001280
Vedant Kumar8c466682018-10-05 21:44:15 +00001281 // Blocks which are artificial, i.e. blocks which exclusively contain
1282 // instructions without locations, or with line 0 locations.
1283 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1284
Daniel Berlin72560592016-01-10 18:08:32 +00001285 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1286 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1287 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001288 std::greater<unsigned int>>
1289 Worklist;
Daniel Berlin72560592016-01-10 18:08:32 +00001290 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001291 std::greater<unsigned int>>
1292 Pending;
1293
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001294 // Besides parameter's modification, check whether a DBG_VALUE is inlined
1295 // in order to deduce whether the variable that it tracks comes from
1296 // a different function. If that is the case we can't track its entry value.
1297 auto IsUnmodifiedFuncParam = [&](const MachineInstr &MI) {
1298 auto *DIVar = MI.getDebugVariable();
1299 return DIVar->isParameter() && DIVar->isNotModified() &&
1300 !MI.getDebugLoc()->getInlinedAt();
1301 };
1302
1303 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
1304 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Daniel Sanders0c476112019-08-15 19:22:08 +00001305 Register FP = TRI->getFrameRegister(MF);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001306 auto IsRegOtherThanSPAndFP = [&](const MachineOperand &Op) -> bool {
1307 return Op.isReg() && Op.getReg() != SP && Op.getReg() != FP;
1308 };
1309
1310 // Working set of currently collected debug variables mapped to DBG_VALUEs
1311 // representing candidates for production of debug entry values.
1312 DebugParamMap DebugEntryVals;
1313
1314 MachineBasicBlock &First_MBB = *(MF.begin());
1315 // Only in the case of entry MBB collect DBG_VALUEs representing
1316 // function parameters in order to generate debug entry values for them.
1317 // Currently, we generate debug entry values only for parameters that are
1318 // unmodified throughout the function and located in a register.
1319 // TODO: Add support for parameters that are described as fragments.
1320 // TODO: Add support for modified arguments that can be expressed
1321 // by using its entry value.
1322 // TODO: Add support for local variables that are expressed in terms of
1323 // parameters entry values.
1324 for (auto &MI : First_MBB)
1325 if (MI.isDebugValue() && IsUnmodifiedFuncParam(MI) &&
1326 !MI.isIndirectDebugValue() && IsRegOtherThanSPAndFP(MI.getOperand(0)) &&
1327 !DebugEntryVals.count(MI.getDebugVariable()) &&
1328 !MI.getDebugExpression()->isFragment())
1329 DebugEntryVals[MI.getDebugVariable()] = &MI;
1330
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001331 // Initialize per-block structures and scan for fragment overlaps.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001332 for (auto &MBB : MF) {
Jeremy Morse67443c32019-08-21 09:22:31 +00001333 PendingInLocs[&MBB] = VarLocSet();
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001334
1335 for (auto &MI : MBB) {
1336 if (MI.isDebugValue())
1337 accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
1338 }
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001339 }
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001340
Vedant Kumar8c466682018-10-05 21:44:15 +00001341 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
1342 if (const DebugLoc &DL = MI.getDebugLoc())
1343 return DL.getLine() != 0;
1344 return false;
1345 };
1346 for (auto &MBB : MF)
1347 if (none_of(MBB.instrs(), hasNonArtificialLocation))
1348 ArtificialBlocks.insert(&MBB);
1349
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001350 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1351 "OutLocs after initialization", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001352
Daniel Berlin72560592016-01-10 18:08:32 +00001353 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1354 unsigned int RPONumber = 0;
1355 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
1356 OrderToBB[RPONumber] = *RI;
1357 BBToOrder[*RI] = RPONumber;
1358 Worklist.push(RPONumber);
1359 ++RPONumber;
1360 }
Daniel Berlin72560592016-01-10 18:08:32 +00001361 // This is a standard "union of predecessor outs" dataflow problem.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001362 // To solve it, we perform join() and process() using the two worklist method
Daniel Berlin72560592016-01-10 18:08:32 +00001363 // until the ranges converge.
1364 // Ranges have converged when both worklists are empty.
Keith Walker83ebef52016-09-27 16:46:07 +00001365 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
Daniel Berlin72560592016-01-10 18:08:32 +00001366 while (!Worklist.empty() || !Pending.empty()) {
1367 // We track what is on the pending worklist to avoid inserting the same
1368 // thing twice. We could avoid this with a custom priority queue, but this
1369 // is probably not worth it.
1370 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001371 LLVM_DEBUG(dbgs() << "Processing Worklist\n");
Daniel Berlin72560592016-01-10 18:08:32 +00001372 while (!Worklist.empty()) {
1373 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
1374 Worklist.pop();
Jeremy Morse67443c32019-08-21 09:22:31 +00001375 MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
1376 ArtificialBlocks, PendingInLocs);
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001377 MBBJoined |= Visited.insert(MBB).second;
Daniel Berlin72560592016-01-10 18:08:32 +00001378 if (MBBJoined) {
1379 MBBJoined = false;
1380 Changed = true;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001381 // Now that we have started to extend ranges across BBs we need to
1382 // examine spill instructions to see whether they spill registers that
1383 // correspond to user variables.
Jeremy Morse67443c32019-08-21 09:22:31 +00001384 // First load any pending inlocs.
1385 OpenRanges.insertFromLocSet(PendingInLocs[MBB], VarLocIDs);
Daniel Berlin72560592016-01-10 18:08:32 +00001386 for (auto &MI : *MBB)
Jeremy Morsed2cd9c22019-06-13 13:11:57 +00001387 process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001388 DebugEntryVals, OverlapFragments, SeenFragments);
Jeremy Morse67443c32019-08-21 09:22:31 +00001389 OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001390
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001391 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1392 "OutLocs after propagating", dbgs()));
1393 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
1394 "InLocs after propagating", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001395
Daniel Berlin72560592016-01-10 18:08:32 +00001396 if (OLChanged) {
1397 OLChanged = false;
1398 for (auto s : MBB->successors())
Benjamin Kramer4dea8f52016-06-17 18:59:41 +00001399 if (OnPending.insert(s).second) {
Daniel Berlin72560592016-01-10 18:08:32 +00001400 Pending.push(BBToOrder[s]);
1401 }
1402 }
Vikram TV859ad292015-12-16 11:09:48 +00001403 }
1404 }
Daniel Berlin72560592016-01-10 18:08:32 +00001405 Worklist.swap(Pending);
1406 // At this point, pending must be empty, since it was just the empty
1407 // worklist
1408 assert(Pending.empty() && "Pending should be empty");
Vikram TV859ad292015-12-16 11:09:48 +00001409 }
Daniel Berlin72560592016-01-10 18:08:32 +00001410
Jeremy Morse0ca48de22019-10-04 09:38:05 +00001411 // Add any DBG_VALUE instructions created by location transfers.
1412 for (auto &TR : Transfers) {
Jeremy Morse61800a72019-10-04 10:53:47 +00001413 MachineBasicBlock *MBB = TR.TransferInst->getParent();
1414 const VarLoc &VL = VarLocIDs[TR.LocationID];
1415 MachineInstr *MI = VL.BuildDbgValue(MF);
1416 MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI);
Jeremy Morse0ca48de22019-10-04 09:38:05 +00001417 }
1418 Transfers.clear();
1419
Jeremy Morse67443c32019-08-21 09:22:31 +00001420 // Deferred inlocs will not have had any DBG_VALUE insts created; do
1421 // that now.
1422 flushPendingLocs(PendingInLocs, VarLocIDs);
1423
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001424 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
1425 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001426 return Changed;
1427}
1428
1429bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001430 if (!MF.getFunction().getSubprogram())
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001431 // LiveDebugValues will already have removed all DBG_VALUEs.
1432 return false;
1433
Wolfgang Piebe018bbd2017-07-19 19:36:40 +00001434 // Skip functions from NoDebug compilation units.
Matthias Braunf1caa282017-12-15 22:22:58 +00001435 if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
Wolfgang Piebe018bbd2017-07-19 19:36:40 +00001436 DICompileUnit::NoDebug)
1437 return false;
1438
Vikram TV859ad292015-12-16 11:09:48 +00001439 TRI = MF.getSubtarget().getRegisterInfo();
1440 TII = MF.getSubtarget().getInstrInfo();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001441 TFI = MF.getSubtarget().getFrameLowering();
Krasimir Georgiev2f1bba72019-09-18 14:42:09 +00001442 TFI->determineCalleeSaves(MF, CalleeSavedRegs,
1443 std::make_unique<RegScavenger>().get());
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001444 LS.initialize(MF);
Vikram TV859ad292015-12-16 11:09:48 +00001445
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001446 bool Changed = ExtendRanges(MF);
Vikram TV859ad292015-12-16 11:09:48 +00001447 return Changed;
1448}