blob: 6acaf4099c3e70792be564cb728702e3d66b0856 [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"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080060#include "llvm/InitializePasses.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000061#include "llvm/MC/MCRegisterInfo.h"
62#include "llvm/Pass.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/Compiler.h"
Vikram TV859ad292015-12-16 11:09:48 +000065#include "llvm/Support/Debug.h"
66#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000067#include <algorithm>
68#include <cassert>
69#include <cstdint>
70#include <functional>
Mehdi Aminib550cb12016-04-18 09:17:29 +000071#include <queue>
Jeremy Morsebf2b2f02019-06-13 12:51:57 +000072#include <tuple>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000073#include <utility>
74#include <vector>
Vikram TV859ad292015-12-16 11:09:48 +000075
76using namespace llvm;
77
Matthias Braun1527baa2017-05-25 21:26:32 +000078#define DEBUG_TYPE "livedebugvalues"
Vikram TV859ad292015-12-16 11:09:48 +000079
80STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
Jeremy Morse0ae54982019-08-23 16:33:42 +000081STATISTIC(NumRemoved, "Number of DBG_VALUE instructions removed");
Vikram TV859ad292015-12-16 11:09:48 +000082
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000083// If @MI is a DBG_VALUE with debug value described by a defined
Adrian Prantl6ee02c72016-05-25 22:21:12 +000084// register, returns the number of this register. In the other case, returns 0.
Matt Arsenaulte3a676e2019-06-24 15:50:29 +000085static Register isDbgValueDescribedByReg(const MachineInstr &MI) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +000086 assert(MI.isDebugValue() && "expected a DBG_VALUE");
87 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
88 // If location of variable is described using a register (directly
89 // or indirectly), this register is always a first operand.
Matt Arsenaulte3a676e2019-06-24 15:50:29 +000090 return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : Register();
Adrian Prantl6ee02c72016-05-25 22:21:12 +000091}
92
David Stenberg4fec44c2019-11-13 10:36:13 +010093/// If \p Op is a stack or frame register return true, otherwise return false.
94/// This is used to avoid basing the debug entry values on the registers, since
95/// we do not support it at the moment.
96static bool isRegOtherThanSPAndFP(const MachineOperand &Op,
97 const MachineInstr &MI,
98 const TargetRegisterInfo *TRI) {
99 if (!Op.isReg())
100 return false;
101
102 const MachineFunction *MF = MI.getParent()->getParent();
103 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
104 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
105 Register FP = TRI->getFrameRegister(*MF);
106 Register Reg = Op.getReg();
107
108 return Reg && Reg != SP && Reg != FP;
109}
110
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000111namespace {
Vikram TV859ad292015-12-16 11:09:48 +0000112
David Stenberg5e646ff2019-11-13 10:37:53 +0100113using DefinedRegsSet = SmallSet<Register, 32>;
114
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000115class LiveDebugValues : public MachineFunctionPass {
Vikram TV859ad292015-12-16 11:09:48 +0000116private:
117 const TargetRegisterInfo *TRI;
118 const TargetInstrInfo *TII;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000119 const TargetFrameLowering *TFI;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000120 BitVector CalleeSavedRegs;
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000121 LexicalScopes LS;
122
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000123 enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
124
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000125 /// Keeps track of lexical scopes associated with a user value's source
126 /// location.
127 class UserValueScopes {
128 DebugLoc DL;
129 LexicalScopes &LS;
130 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
131
132 public:
133 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
134
135 /// Return true if current scope dominates at least one machine
136 /// instruction in a given machine basic block.
137 bool dominates(MachineBasicBlock *MBB) {
138 if (LBlocks.empty())
139 LS.getMachineBasicBlocks(DL, LBlocks);
140 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
141 }
142 };
Vikram TV859ad292015-12-16 11:09:48 +0000143
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000144 using FragmentInfo = DIExpression::FragmentInfo;
145 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
Vikram TV859ad292015-12-16 11:09:48 +0000146
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000147 /// A pair of debug variable and value location.
Vikram TV859ad292015-12-16 11:09:48 +0000148 struct VarLoc {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000149 // The location at which a spilled variable resides. It consists of a
150 // register and an offset.
151 struct SpillLoc {
152 unsigned SpillBase;
153 int SpillOffset;
154 bool operator==(const SpillLoc &Other) const {
155 return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
156 }
157 };
158
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000159 /// Identity of the variable at this location.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000160 const DebugVariable Var;
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000161
162 /// The expression applied to this location.
163 const DIExpression *Expr;
164
165 /// DBG_VALUE to clone var/expr information from if this location
166 /// is moved.
167 const MachineInstr &MI;
168
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000169 mutable UserValueScopes UVS;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000170 enum VarLocKind {
171 InvalidKind = 0,
172 RegisterKind,
Jeremy Morsebcff4172019-06-10 15:23:46 +0000173 SpillLocKind,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000174 ImmediateKind,
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100175 EntryValueKind,
176 EntryValueBackupKind,
177 EntryValueCopyBackupKind
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000178 } Kind = InvalidKind;
Vikram TV859ad292015-12-16 11:09:48 +0000179
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000180 /// The value location. Stored separately to avoid repeatedly
181 /// extracting it from MI.
182 union {
Adrian Prantl359846f2017-07-28 23:25:51 +0000183 uint64_t RegNo;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000184 SpillLoc SpillLocation;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000185 uint64_t Hash;
Jeremy Morsebcff4172019-06-10 15:23:46 +0000186 int64_t Immediate;
187 const ConstantFP *FPImm;
188 const ConstantInt *CImm;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000189 } Loc;
190
Jeremy Morse61800a72019-10-04 10:53:47 +0000191 VarLoc(const MachineInstr &MI, LexicalScopes &LS)
stozer269a9af2019-12-03 12:24:41 +0000192 : Var(MI.getDebugVariable(), MI.getDebugExpression(),
193 MI.getDebugLoc()->getInlinedAt()),
194 Expr(MI.getDebugExpression()), MI(MI), UVS(MI.getDebugLoc(), LS) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000195 static_assert((sizeof(Loc) == sizeof(uint64_t)),
196 "hash does not cover all members of Loc");
197 assert(MI.isDebugValue() && "not a DBG_VALUE");
198 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
Adrian Prantl00698732016-05-25 22:37:29 +0000199 if (int RegNo = isDbgValueDescribedByReg(MI)) {
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100200 Kind = RegisterKind;
Adrian Prantl359846f2017-07-28 23:25:51 +0000201 Loc.RegNo = RegNo;
Jeremy Morsebcff4172019-06-10 15:23:46 +0000202 } else if (MI.getOperand(0).isImm()) {
203 Kind = ImmediateKind;
204 Loc.Immediate = MI.getOperand(0).getImm();
205 } else if (MI.getOperand(0).isFPImm()) {
206 Kind = ImmediateKind;
207 Loc.FPImm = MI.getOperand(0).getFPImm();
208 } else if (MI.getOperand(0).isCImm()) {
209 Kind = ImmediateKind;
210 Loc.CImm = MI.getOperand(0).getCImm();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000211 }
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100212
213 // We create the debug entry values from the factory functions rather than
214 // from this ctor.
215 assert(Kind != EntryValueKind && !isEntryBackupLoc());
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000216 }
217
Jeremy Morse61800a72019-10-04 10:53:47 +0000218 /// Take the variable and machine-location in DBG_VALUE MI, and build an
219 /// entry location using the given expression.
220 static VarLoc CreateEntryLoc(const MachineInstr &MI, LexicalScopes &LS,
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100221 const DIExpression *EntryExpr, unsigned Reg) {
Jeremy Morse61800a72019-10-04 10:53:47 +0000222 VarLoc VL(MI, LS);
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100223 assert(VL.Kind == RegisterKind);
Jeremy Morse61800a72019-10-04 10:53:47 +0000224 VL.Kind = EntryValueKind;
225 VL.Expr = EntryExpr;
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100226 VL.Loc.RegNo = Reg;
227 return VL;
228 }
229
230 /// Take the variable and machine-location from the DBG_VALUE (from the
231 /// function entry), and build an entry value backup location. The backup
232 /// location will turn into the normal location if the backup is valid at
233 /// the time of the primary location clobbering.
234 static VarLoc CreateEntryBackupLoc(const MachineInstr &MI,
235 LexicalScopes &LS,
236 const DIExpression *EntryExpr) {
237 VarLoc VL(MI, LS);
238 assert(VL.Kind == RegisterKind);
239 VL.Kind = EntryValueBackupKind;
240 VL.Expr = EntryExpr;
241 return VL;
242 }
243
244 /// Take the variable and machine-location from the DBG_VALUE (from the
245 /// function entry), and build a copy of an entry value backup location by
246 /// setting the register location to NewReg.
247 static VarLoc CreateEntryCopyBackupLoc(const MachineInstr &MI,
248 LexicalScopes &LS,
249 const DIExpression *EntryExpr,
250 unsigned NewReg) {
251 VarLoc VL(MI, LS);
252 assert(VL.Kind == RegisterKind);
253 VL.Kind = EntryValueCopyBackupKind;
254 VL.Expr = EntryExpr;
255 VL.Loc.RegNo = NewReg;
Jeremy Morse61800a72019-10-04 10:53:47 +0000256 return VL;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000257 }
258
Jeremy Morse61800a72019-10-04 10:53:47 +0000259 /// Copy the register location in DBG_VALUE MI, updating the register to
260 /// be NewReg.
261 static VarLoc CreateCopyLoc(const MachineInstr &MI, LexicalScopes &LS,
262 unsigned NewReg) {
263 VarLoc VL(MI, LS);
264 assert(VL.Kind == RegisterKind);
265 VL.Loc.RegNo = NewReg;
266 return VL;
267 }
268
269 /// Take the variable described by DBG_VALUE MI, and create a VarLoc
270 /// locating it in the specified spill location.
271 static VarLoc CreateSpillLoc(const MachineInstr &MI, unsigned SpillBase,
272 int SpillOffset, LexicalScopes &LS) {
273 VarLoc VL(MI, LS);
274 assert(VL.Kind == RegisterKind);
275 VL.Kind = SpillLocKind;
276 VL.Loc.SpillLocation = {SpillBase, SpillOffset};
277 return VL;
278 }
279
280 /// Create a DBG_VALUE representing this VarLoc in the given function.
281 /// Copies variable-specific information such as DILocalVariable and
282 /// inlining information from the original DBG_VALUE instruction, which may
283 /// have been several transfers ago.
284 MachineInstr *BuildDbgValue(MachineFunction &MF) const {
285 const DebugLoc &DbgLoc = MI.getDebugLoc();
286 bool Indirect = MI.isIndirectDebugValue();
287 const auto &IID = MI.getDesc();
288 const DILocalVariable *Var = MI.getDebugVariable();
289 const DIExpression *DIExpr = MI.getDebugExpression();
290
291 switch (Kind) {
292 case EntryValueKind:
293 // An entry value is a register location -- but with an updated
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100294 // expression. The register location of such DBG_VALUE is always the one
295 // from the entry DBG_VALUE, it does not matter if the entry value was
296 // copied in to another register due to some optimizations.
297 return BuildMI(MF, DbgLoc, IID, Indirect, MI.getOperand(0).getReg(),
298 Var, Expr);
Jeremy Morse61800a72019-10-04 10:53:47 +0000299 case RegisterKind:
300 // Register locations are like the source DBG_VALUE, but with the
301 // register number from this VarLoc.
302 return BuildMI(MF, DbgLoc, IID, Indirect, Loc.RegNo, Var, DIExpr);
303 case SpillLocKind: {
304 // Spills are indirect DBG_VALUEs, with a base register and offset.
305 // Use the original DBG_VALUEs expression to build the spilt location
306 // on top of. FIXME: spill locations created before this pass runs
307 // are not recognized, and not handled here.
308 auto *SpillExpr = DIExpression::prepend(
309 DIExpr, DIExpression::ApplyOffset, Loc.SpillLocation.SpillOffset);
310 unsigned Base = Loc.SpillLocation.SpillBase;
311 return BuildMI(MF, DbgLoc, IID, true, Base, Var, SpillExpr);
312 }
313 case ImmediateKind: {
314 MachineOperand MO = MI.getOperand(0);
315 return BuildMI(MF, DbgLoc, IID, Indirect, MO, Var, DIExpr);
316 }
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100317 case EntryValueBackupKind:
318 case EntryValueCopyBackupKind:
Jeremy Morse61800a72019-10-04 10:53:47 +0000319 case InvalidKind:
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100320 llvm_unreachable(
321 "Tried to produce DBG_VALUE for invalid or backup VarLoc");
Jeremy Morse61800a72019-10-04 10:53:47 +0000322 }
Simon Pilgrim84f5cd72019-10-04 12:45:27 +0000323 llvm_unreachable("Unrecognized LiveDebugValues.VarLoc.Kind enum");
Jeremy Morse61800a72019-10-04 10:53:47 +0000324 }
325
326 /// Is the Loc field a constant or constant object?
Jeremy Morsebcff4172019-06-10 15:23:46 +0000327 bool isConstant() const { return Kind == ImmediateKind; }
328
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100329 /// Check if the Loc field is an entry backup location.
330 bool isEntryBackupLoc() const {
331 return Kind == EntryValueBackupKind || Kind == EntryValueCopyBackupKind;
332 }
333
334 /// If this variable is described by a register holding the entry value,
335 /// return it, otherwise return 0.
336 unsigned getEntryValueBackupReg() const {
337 if (Kind == EntryValueBackupKind)
338 return Loc.RegNo;
339 return 0;
340 }
341
342 /// If this variable is described by a register holding the copy of the
343 /// entry value, return it, otherwise return 0.
344 unsigned getEntryValueCopyBackupReg() const {
345 if (Kind == EntryValueCopyBackupKind)
346 return Loc.RegNo;
347 return 0;
348 }
349
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000350 /// If this variable is described by a register, return it,
351 /// otherwise return 0.
352 unsigned isDescribedByReg() const {
353 if (Kind == RegisterKind)
Adrian Prantl359846f2017-07-28 23:25:51 +0000354 return Loc.RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000355 return 0;
356 }
357
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000358 /// Determine whether the lexical scope of this value's debug location
359 /// dominates MBB.
360 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
361
Aaron Ballman615eb472017-10-15 14:32:27 +0000362#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Jeremy Morse61800a72019-10-04 10:53:47 +0000363 // TRI can be null.
364 void dump(const TargetRegisterInfo *TRI, raw_ostream &Out = dbgs()) const {
365 dbgs() << "VarLoc(";
366 switch (Kind) {
367 case RegisterKind:
368 case EntryValueKind:
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100369 case EntryValueBackupKind:
370 case EntryValueCopyBackupKind:
Jeremy Morse61800a72019-10-04 10:53:47 +0000371 dbgs() << printReg(Loc.RegNo, TRI);
372 break;
373 case SpillLocKind:
374 dbgs() << printReg(Loc.SpillLocation.SpillBase, TRI);
375 dbgs() << "[" << Loc.SpillLocation.SpillOffset << "]";
376 break;
377 case ImmediateKind:
378 dbgs() << Loc.Immediate;
379 break;
380 case InvalidKind:
381 llvm_unreachable("Invalid VarLoc in dump method");
382 }
383
stozer269a9af2019-12-03 12:24:41 +0000384 dbgs() << ", \"" << Var.getVariable()->getName() << "\", " << *Expr
385 << ", ";
Jeremy Morse61800a72019-10-04 10:53:47 +0000386 if (Var.getInlinedAt())
387 dbgs() << "!" << Var.getInlinedAt()->getMetadataID() << ")\n";
388 else
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100389 dbgs() << "(null))";
390
391 if (isEntryBackupLoc())
392 dbgs() << " (backup loc)\n";
393 else
394 dbgs() << "\n";
Jeremy Morse61800a72019-10-04 10:53:47 +0000395 }
Matthias Braun194ded52017-01-28 06:53:55 +0000396#endif
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000397
398 bool operator==(const VarLoc &Other) const {
Jeremy Morsebcff4172019-06-10 15:23:46 +0000399 return Kind == Other.Kind && Var == Other.Var &&
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000400 Loc.Hash == Other.Loc.Hash && Expr == Other.Expr;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000401 }
402
Adrian Prantl7509d542016-05-26 21:42:47 +0000403 /// This operator guarantees that VarLocs are sorted by Variable first.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000404 bool operator<(const VarLoc &Other) const {
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000405 return std::tie(Var, Kind, Loc.Hash, Expr) <
406 std::tie(Other.Var, Other.Kind, Other.Loc.Hash, Other.Expr);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000407 }
Vikram TV859ad292015-12-16 11:09:48 +0000408 };
409
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000410 using VarLocMap = UniqueVector<VarLoc>;
411 using VarLocSet = SparseBitVector<>;
412 using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000413 struct TransferDebugPair {
Jeremy Morse61800a72019-10-04 10:53:47 +0000414 MachineInstr *TransferInst; /// Instruction where this transfer occurs.
415 unsigned LocationID; /// Location number for the transfer dest.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000416 };
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000417 using TransferMap = SmallVector<TransferDebugPair, 4>;
Vikram TV859ad292015-12-16 11:09:48 +0000418
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000419 // Types for recording sets of variable fragments that overlap. For a given
420 // local variable, we record all other fragments of that variable that could
421 // overlap it, to reduce search time.
422 using FragmentOfVar =
423 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
424 using OverlapMap =
425 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
426
427 // Helper while building OverlapMap, a map of all fragments seen for a given
428 // DILocalVariable.
429 using VarToFragments =
430 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
431
Adrian Prantl7509d542016-05-26 21:42:47 +0000432 /// This holds the working set of currently open ranges. For fast
433 /// access, this is done both as a set of VarLocIDs, and a map of
434 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100435 /// previous open ranges for the same variable. In addition, we keep
436 /// two different maps (Vars/EntryValuesBackupVars), so erase/insert
437 /// methods act differently depending on whether a VarLoc is primary
438 /// location or backup one. In the case the VarLoc is backup location
439 /// we will erase/insert from the EntryValuesBackupVars map, otherwise
440 /// we perform the operation on the Vars.
Adrian Prantl7509d542016-05-26 21:42:47 +0000441 class OpenRangesSet {
442 VarLocSet VarLocs;
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100443 // Map the DebugVariable to recent primary location ID.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000444 SmallDenseMap<DebugVariable, unsigned, 8> Vars;
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100445 // Map the DebugVariable to recent backup location ID.
446 SmallDenseMap<DebugVariable, unsigned, 8> EntryValuesBackupVars;
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000447 OverlapMap &OverlappingFragments;
Adrian Prantl7509d542016-05-26 21:42:47 +0000448
449 public:
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000450 OpenRangesSet(OverlapMap &_OLapMap) : OverlappingFragments(_OLapMap) {}
451
Adrian Prantl7509d542016-05-26 21:42:47 +0000452 const VarLocSet &getVarLocs() const { return VarLocs; }
453
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100454 /// Terminate all open ranges for VL.Var by removing it from the set.
455 void erase(const VarLoc &VL);
Adrian Prantl7509d542016-05-26 21:42:47 +0000456
457 /// Terminate all open ranges listed in \c KillSet by removing
458 /// them from the set.
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100459 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs);
Adrian Prantl7509d542016-05-26 21:42:47 +0000460
461 /// Insert a new range into the set.
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100462 void insert(unsigned VarLocID, const VarLoc &VL);
Adrian Prantl7509d542016-05-26 21:42:47 +0000463
Jeremy Morse67443c32019-08-21 09:22:31 +0000464 /// Insert a set of ranges.
465 void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map) {
466 for (unsigned Id : ToLoad) {
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100467 const VarLoc &VarL = Map[Id];
468 insert(Id, VarL);
Jeremy Morse67443c32019-08-21 09:22:31 +0000469 }
470 }
471
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100472 llvm::Optional<unsigned> getEntryValueBackup(DebugVariable Var);
473
Adrian Prantl7509d542016-05-26 21:42:47 +0000474 /// Empty the set.
475 void clear() {
476 VarLocs.clear();
477 Vars.clear();
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100478 EntryValuesBackupVars.clear();
Adrian Prantl7509d542016-05-26 21:42:47 +0000479 }
480
481 /// Return whether the set is empty or not.
482 bool empty() const {
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100483 assert(Vars.empty() == EntryValuesBackupVars.empty() &&
484 Vars.empty() == VarLocs.empty() &&
485 "open ranges are inconsistent");
Adrian Prantl7509d542016-05-26 21:42:47 +0000486 return VarLocs.empty();
487 }
488 };
489
Jeremy Morse5d9cd3b2019-09-06 10:08:22 +0000490 /// Tests whether this instruction is a spill to a stack location.
491 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
492
493 /// Decide if @MI is a spill instruction and return true if it is. We use 2
494 /// criteria to make this decision:
495 /// - Is this instruction a store to a spill slot?
496 /// - Is there a register operand that is both used and killed?
497 /// TODO: Store optimization can fold spills into other stores (including
498 /// other spills). We do not handle this yet (more than one memory operand).
499 bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
500 unsigned &Reg);
501
David Stenberg4fec44c2019-11-13 10:36:13 +0100502 /// Returns true if the given machine instruction is a debug value which we
503 /// can emit entry values for.
504 ///
505 /// Currently, we generate debug entry values only for parameters that are
506 /// unmodified throughout the function and located in a register.
David Stenberg5e646ff2019-11-13 10:37:53 +0100507 bool isEntryValueCandidate(const MachineInstr &MI,
508 const DefinedRegsSet &Regs) const;
David Stenberg4fec44c2019-11-13 10:36:13 +0100509
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000510 /// If a given instruction is identified as a spill, return the spill location
511 /// and set \p Reg to the spilled register.
512 Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
513 MachineFunction *MF,
514 unsigned &Reg);
515 /// Given a spill instruction, extract the register and offset used to
516 /// address the spill location in a target independent way.
517 VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000518 void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
519 TransferMap &Transfers, VarLocMap &VarLocIDs,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000520 unsigned OldVarID, TransferKind Kind,
521 unsigned NewReg = 0);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000522
Adrian Prantl7509d542016-05-26 21:42:47 +0000523 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000524 VarLocMap &VarLocIDs);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000525 void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
526 VarLocMap &VarLocIDs, TransferMap &Transfers);
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100527 bool removeEntryValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
528 VarLocMap &VarLocIDs, const VarLoc &EntryVL);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000529 void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
530 VarLocMap &VarLocIDs, TransferMap &Transfers,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000531 SparseBitVector<> &KillSet);
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100532 void recordEntryValue(const MachineInstr &MI,
533 const DefinedRegsSet &DefinedRegs,
534 OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000535 void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
536 VarLocMap &VarLocIDs, TransferMap &Transfers);
Adrian Prantl7509d542016-05-26 21:42:47 +0000537 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100538 VarLocMap &VarLocIDs, TransferMap &Transfers);
Jeremy Morse67443c32019-08-21 09:22:31 +0000539 bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
540 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
Nikola Prica441ad622019-05-27 13:51:30 +0000541
Jeremy Morse67443c32019-08-21 09:22:31 +0000542 void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100543 VarLocMap &VarLocIDs, TransferMap &Transfers);
Vikram TV859ad292015-12-16 11:09:48 +0000544
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000545 void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
546 OverlapMap &OLapMap);
547
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000548 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000549 const VarLocMap &VarLocIDs,
Vedant Kumar8c466682018-10-05 21:44:15 +0000550 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
Jeremy Morse67443c32019-08-21 09:22:31 +0000551 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks,
552 VarLocInMBB &PendingInLocs);
553
554 /// Create DBG_VALUE insts for inlocs that have been propagated but
555 /// had their instruction creation deferred.
556 void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
Vikram TV859ad292015-12-16 11:09:48 +0000557
558 bool ExtendRanges(MachineFunction &MF);
559
560public:
561 static char ID;
562
563 /// Default construct and initialize the pass.
564 LiveDebugValues();
565
566 /// Tell the pass manager which passes we depend on and what
567 /// information we preserve.
568 void getAnalysisUsage(AnalysisUsage &AU) const override;
569
Derek Schuffad154c82016-03-28 17:05:30 +0000570 MachineFunctionProperties getRequiredProperties() const override {
571 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000572 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000573 }
574
Vikram TV859ad292015-12-16 11:09:48 +0000575 /// Print to ostream with a message.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000576 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
577 const VarLocMap &VarLocIDs, const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000578 raw_ostream &Out) const;
579
580 /// Calculate the liveness information for the given machine function.
581 bool runOnMachineFunction(MachineFunction &MF) override;
582};
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000583
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000584} // end anonymous namespace
Vikram TV859ad292015-12-16 11:09:48 +0000585
586//===----------------------------------------------------------------------===//
587// Implementation
588//===----------------------------------------------------------------------===//
589
590char LiveDebugValues::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000591
Vikram TV859ad292015-12-16 11:09:48 +0000592char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000593
Matthias Braun1527baa2017-05-25 21:26:32 +0000594INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
Vikram TV859ad292015-12-16 11:09:48 +0000595 false, false)
596
597/// Default construct and initialize the pass.
598LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
599 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
600}
601
602/// Tell the pass manager which passes we depend on and what information we
603/// preserve.
604void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
Matt Arsenaultb1630a12016-06-08 05:18:01 +0000605 AU.setPreservesCFG();
Vikram TV859ad292015-12-16 11:09:48 +0000606 MachineFunctionPass::getAnalysisUsage(AU);
607}
608
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000609/// Erase a variable from the set of open ranges, and additionally erase any
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100610/// fragments that may overlap it. If the VarLoc is a buckup location, erase
611/// the variable from the EntryValuesBackupVars set, indicating we should stop
612/// tracking its backup entry location. Otherwise, if the VarLoc is primary
613/// location, erase the variable from the Vars set.
614void LiveDebugValues::OpenRangesSet::erase(const VarLoc &VL) {
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000615 // Erasure helper.
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100616 auto DoErase = [VL, this](DebugVariable VarToErase) {
617 auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
618 auto It = EraseFrom->find(VarToErase);
619 if (It != EraseFrom->end()) {
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000620 unsigned ID = It->second;
621 VarLocs.reset(ID);
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100622 EraseFrom->erase(It);
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000623 }
624 };
625
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100626 DebugVariable Var = VL.Var;
627
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000628 // Erase the variable/fragment that ends here.
629 DoErase(Var);
630
631 // Extract the fragment. Interpret an empty fragment as one that covers all
632 // possible bits.
stozer269a9af2019-12-03 12:24:41 +0000633 FragmentInfo ThisFragment = Var.getFragmentOrDefault();
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000634
635 // There may be fragments that overlap the designated fragment. Look them up
636 // in the pre-computed overlap map, and erase them too.
stozer269a9af2019-12-03 12:24:41 +0000637 auto MapIt = OverlappingFragments.find({Var.getVariable(), ThisFragment});
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000638 if (MapIt != OverlappingFragments.end()) {
639 for (auto Fragment : MapIt->second) {
640 LiveDebugValues::OptFragmentInfo FragmentHolder;
stozer269a9af2019-12-03 12:24:41 +0000641 if (!DebugVariable::isDefaultFragment(Fragment))
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000642 FragmentHolder = LiveDebugValues::OptFragmentInfo(Fragment);
stozer269a9af2019-12-03 12:24:41 +0000643 DoErase({Var.getVariable(), FragmentHolder, Var.getInlinedAt()});
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000644 }
645 }
646}
647
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100648void LiveDebugValues::OpenRangesSet::erase(const VarLocSet &KillSet,
649 const VarLocMap &VarLocIDs) {
650 VarLocs.intersectWithComplement(KillSet);
651 for (unsigned ID : KillSet) {
652 const VarLoc *VL = &VarLocIDs[ID];
653 auto *EraseFrom = VL->isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
654 EraseFrom->erase(VL->Var);
655 }
656}
657
658void LiveDebugValues::OpenRangesSet::insert(unsigned VarLocID,
659 const VarLoc &VL) {
660 auto *InsertInto = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
661 VarLocs.set(VarLocID);
662 InsertInto->insert({VL.Var, VarLocID});
663}
664
665/// Return the Loc ID of an entry value backup location, if it exists for the
666/// variable.
667llvm::Optional<unsigned>
668LiveDebugValues::OpenRangesSet::getEntryValueBackup(DebugVariable Var) {
669 auto It = EntryValuesBackupVars.find(Var);
670 if (It != EntryValuesBackupVars.end())
671 return It->second;
672
673 return llvm::None;
674}
675
Vikram TV859ad292015-12-16 11:09:48 +0000676//===----------------------------------------------------------------------===//
677// Debug Range Extension Implementation
678//===----------------------------------------------------------------------===//
679
Matthias Braun194ded52017-01-28 06:53:55 +0000680#ifndef NDEBUG
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000681void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
682 const VarLocInMBB &V,
683 const VarLocMap &VarLocIDs,
684 const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000685 raw_ostream &Out) const {
Keith Walkerf83a19f2016-09-20 16:04:31 +0000686 Out << '\n' << msg << '\n';
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000687 for (const MachineBasicBlock &BB : MF) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000688 const VarLocSet &L = V.lookup(&BB);
689 if (L.empty())
690 continue;
691 Out << "MBB: " << BB.getNumber() << ":\n";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000692 for (unsigned VLL : L) {
693 const VarLoc &VL = VarLocIDs[VLL];
stozer269a9af2019-12-03 12:24:41 +0000694 Out << " Var: " << VL.Var.getVariable()->getName();
Vikram TV859ad292015-12-16 11:09:48 +0000695 Out << " MI: ";
Jeremy Morse61800a72019-10-04 10:53:47 +0000696 VL.dump(TRI, Out);
Vikram TV859ad292015-12-16 11:09:48 +0000697 }
698 }
699 Out << "\n";
700}
Matthias Braun194ded52017-01-28 06:53:55 +0000701#endif
Vikram TV859ad292015-12-16 11:09:48 +0000702
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000703LiveDebugValues::VarLoc::SpillLoc
704LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000705 assert(MI.hasOneMemOperand() &&
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000706 "Spill instruction does not have exactly one memory operand?");
707 auto MMOI = MI.memoperands_begin();
708 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
709 assert(PVal->kind() == PseudoSourceValue::FixedStack &&
710 "Inconsistent memory operand in spill instruction");
711 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
712 const MachineBasicBlock *MBB = MI.getParent();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000713 unsigned Reg;
714 int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
715 return {Reg, Offset};
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000716}
717
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100718/// Try to salvage the debug entry value if we encounter a new debug value
719/// describing the same parameter, otherwise stop tracking the value. Return
720/// true if we should stop tracking the entry value, otherwise return false.
721bool LiveDebugValues::removeEntryValue(const MachineInstr &MI,
722 OpenRangesSet &OpenRanges,
723 VarLocMap &VarLocIDs,
724 const VarLoc &EntryVL) {
725 // Skip the DBG_VALUE which is the debug entry value itself.
726 if (MI.isIdenticalTo(EntryVL.MI))
727 return false;
728
729 // If the parameter's location is not register location, we can not track
730 // the entry value any more. In addition, if the debug expression from the
731 // DBG_VALUE is not empty, we can assume the parameter's value has changed
732 // indicating that we should stop tracking its entry value as well.
733 if (!MI.getOperand(0).isReg() ||
734 MI.getDebugExpression()->getNumElements() != 0)
735 return true;
736
737 // If the DBG_VALUE comes from a copy instruction that copies the entry value,
738 // it means the parameter's value has not changed and we should be able to use
739 // its entry value.
740 bool TrySalvageEntryValue = false;
741 Register Reg = MI.getOperand(0).getReg();
742 auto I = std::next(MI.getReverseIterator());
743 const MachineOperand *SrcRegOp, *DestRegOp;
744 if (I != MI.getParent()->rend()) {
745 // TODO: Try to keep tracking of an entry value if we encounter a propagated
746 // DBG_VALUE describing the copy of the entry value. (Propagated entry value
747 // does not indicate the parameter modification.)
748 auto DestSrc = TII->isCopyInstr(*I);
749 if (!DestSrc)
750 return true;
751
752 SrcRegOp = DestSrc->Source;
753 DestRegOp = DestSrc->Destination;
754 if (Reg != DestRegOp->getReg())
755 return true;
756 TrySalvageEntryValue = true;
757 }
758
759 if (TrySalvageEntryValue) {
760 for (unsigned ID : OpenRanges.getVarLocs()) {
761 const VarLoc &VL = VarLocIDs[ID];
762 if (!VL.isEntryBackupLoc())
763 continue;
764
765 if (VL.getEntryValueCopyBackupReg() == Reg &&
766 VL.MI.getOperand(0).getReg() == SrcRegOp->getReg())
767 return false;
768 }
769 }
770
771 return true;
772}
773
Vikram TV859ad292015-12-16 11:09:48 +0000774/// End all previous ranges related to @MI and start a new range from @MI
775/// if it is a DBG_VALUE instr.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000776void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000777 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000778 VarLocMap &VarLocIDs) {
Vikram TV859ad292015-12-16 11:09:48 +0000779 if (!MI.isDebugValue())
780 return;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000781 const DILocalVariable *Var = MI.getDebugVariable();
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000782 const DIExpression *Expr = MI.getDebugExpression();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000783 const DILocation *DebugLoc = MI.getDebugLoc();
784 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
785 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
Vikram TV859ad292015-12-16 11:09:48 +0000786 "Expected inlined-at fields to agree");
Vikram TV859ad292015-12-16 11:09:48 +0000787
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000788 DebugVariable V(Var, Expr, InlinedAt);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000789
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100790 // Check if this DBG_VALUE indicates a parameter's value changing.
791 // If that is the case, we should stop tracking its entry value.
792 auto EntryValBackupID = OpenRanges.getEntryValueBackup(V);
793 if (Var->isParameter() && EntryValBackupID) {
794 const VarLoc &EntryVL = VarLocIDs[*EntryValBackupID];
795 if (removeEntryValue(MI, OpenRanges, VarLocIDs, EntryVL)) {
796 LLVM_DEBUG(dbgs() << "Deleting a DBG entry value because of: ";
797 MI.print(dbgs(), /*IsStandalone*/ false,
798 /*SkipOpers*/ false, /*SkipDebugLoc*/ false,
799 /*AddNewLine*/ true, TII));
800 OpenRanges.erase(EntryVL);
801 }
802 }
803
Jeremy Morsebcff4172019-06-10 15:23:46 +0000804 unsigned ID;
Djordje Todorovic774eabd2019-06-27 18:12:04 +0000805 if (isDbgValueDescribedByReg(MI) || MI.getOperand(0).isImm() ||
806 MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) {
Jeremy Morsebcff4172019-06-10 15:23:46 +0000807 // Use normal VarLoc constructor for registers and immediates.
Djordje Todorovic774eabd2019-06-27 18:12:04 +0000808 VarLoc VL(MI, LS);
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100809 // End all previous ranges of VL.Var.
810 OpenRanges.erase(VL);
811
Jeremy Morsebcff4172019-06-10 15:23:46 +0000812 ID = VarLocIDs.insert(VL);
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100813 // Add the VarLoc to OpenRanges from this DBG_VALUE.
814 OpenRanges.insert(ID, VL);
Jeremy Morsebcff4172019-06-10 15:23:46 +0000815 } else if (MI.hasOneMemOperand()) {
Jeremy Morse8b593482019-08-16 10:04:17 +0000816 llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
Jeremy Morsebcff4172019-06-10 15:23:46 +0000817 } else {
818 // This must be an undefined location. We should leave OpenRanges closed.
819 assert(MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 &&
820 "Unexpected non-undef DBG_VALUE encountered");
Adrian Prantl7509d542016-05-26 21:42:47 +0000821 }
Vikram TV859ad292015-12-16 11:09:48 +0000822}
823
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100824/// Turn the entry value backup locations into primary locations.
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000825void LiveDebugValues::emitEntryValues(MachineInstr &MI,
826 OpenRangesSet &OpenRanges,
827 VarLocMap &VarLocIDs,
828 TransferMap &Transfers,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000829 SparseBitVector<> &KillSet) {
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000830 for (unsigned ID : KillSet) {
stozer269a9af2019-12-03 12:24:41 +0000831 if (!VarLocIDs[ID].Var.getVariable()->isParameter())
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000832 continue;
833
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100834 auto DebugVar = VarLocIDs[ID].Var;
835 auto EntryValBackupID = OpenRanges.getEntryValueBackup(DebugVar);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000836
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100837 // If the parameter has the entry value backup, it means we should
838 // be able to use its entry value.
839 if (!EntryValBackupID)
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000840 continue;
841
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100842 const VarLoc &EntryVL = VarLocIDs[*EntryValBackupID];
843 VarLoc EntryLoc =
844 VarLoc::CreateEntryLoc(EntryVL.MI, LS, EntryVL.Expr, EntryVL.Loc.RegNo);
845 unsigned EntryValueID = VarLocIDs.insert(EntryLoc);
846 Transfers.push_back({&MI, EntryValueID});
847 OpenRanges.insert(EntryValueID, EntryLoc);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000848 }
849}
850
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000851/// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
852/// with \p OldVarID should be deleted form \p OpenRanges and replaced with
853/// new VarLoc. If \p NewReg is different than default zero value then the
854/// new location will be register location created by the copy like instruction,
855/// otherwise it is variable's location on the stack.
856void LiveDebugValues::insertTransferDebugPair(
857 MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000858 VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
859 unsigned NewReg) {
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000860 const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000861
Djordje Todorovic52b231e2019-12-05 12:21:51 +0100862 auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &VarLocIDs](VarLoc &VL) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000863 unsigned LocId = VarLocIDs.insert(VL);
Nikola Prica2d0106a2019-06-03 09:48:29 +0000864
865 // Close this variable's previous location range.
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100866 OpenRanges.erase(VL);
Nikola Prica2d0106a2019-06-03 09:48:29 +0000867
Jeremy Morse61800a72019-10-04 10:53:47 +0000868 // Record the new location as an open range, and a postponed transfer
869 // inserting a DBG_VALUE for this location.
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100870 OpenRanges.insert(LocId, VL);
Jeremy Morse61800a72019-10-04 10:53:47 +0000871 TransferDebugPair MIP = {&MI, LocId};
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000872 Transfers.push_back(MIP);
873 };
874
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100875 // End all previous ranges of VL.Var.
876 OpenRanges.erase(VarLocIDs[OldVarID]);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000877 switch (Kind) {
878 case TransferKind::TransferCopy: {
879 assert(NewReg &&
880 "No register supplied when handling a copy of a debug value");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000881 // Create a DBG_VALUE instruction to describe the Var in its new
882 // register location.
Jeremy Morse61800a72019-10-04 10:53:47 +0000883 VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg);
884 ProcessVarLoc(VL);
885 LLVM_DEBUG({
886 dbgs() << "Creating VarLoc for register copy:";
887 VL.dump(TRI);
888 });
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000889 return;
890 }
891 case TransferKind::TransferSpill: {
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000892 // Create a DBG_VALUE instruction to describe the Var in its spilled
893 // location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000894 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
Jeremy Morse61800a72019-10-04 10:53:47 +0000895 VarLoc VL = VarLoc::CreateSpillLoc(*DebugInstr, SpillLocation.SpillBase,
896 SpillLocation.SpillOffset, LS);
897 ProcessVarLoc(VL);
898 LLVM_DEBUG({
899 dbgs() << "Creating VarLoc for spill:";
900 VL.dump(TRI);
901 });
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000902 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000903 }
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000904 case TransferKind::TransferRestore: {
905 assert(NewReg &&
906 "No register supplied when handling a restore of a debug value");
Jeremy Morse8b593482019-08-16 10:04:17 +0000907 // DebugInstr refers to the pre-spill location, therefore we can reuse
908 // its expression.
Jeremy Morse61800a72019-10-04 10:53:47 +0000909 VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg);
910 ProcessVarLoc(VL);
911 LLVM_DEBUG({
912 dbgs() << "Creating VarLoc for restore:";
913 VL.dump(TRI);
914 });
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000915 return;
916 }
917 }
918 llvm_unreachable("Invalid transfer kind");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000919}
920
Vikram TV859ad292015-12-16 11:09:48 +0000921/// A definition of a register may mark the end of a range.
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000922void LiveDebugValues::transferRegisterDef(
923 MachineInstr &MI, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100924 TransferMap &Transfers) {
Tom Weaverf51477652020-01-24 16:29:05 +0000925
926 // Meta Instructions do not affect the debug liveness of any register they
927 // define.
928 if (MI.isMetaInstruction())
929 return;
930
Justin Bognerfdf9bf42017-10-10 23:50:49 +0000931 MachineFunction *MF = MI.getMF();
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000932 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
933 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000934 SparseBitVector<> KillSet;
Vikram TV859ad292015-12-16 11:09:48 +0000935 for (const MachineOperand &MO : MI.operands()) {
Adrian Prantlea8880b2017-03-03 01:08:25 +0000936 // Determine whether the operand is a register def. Assume that call
937 // instructions never clobber SP, because some backends (e.g., AArch64)
938 // never list SP in the regmask.
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000939 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000940 Register::isPhysicalRegister(MO.getReg()) &&
Adrian Prantlea8880b2017-03-03 01:08:25 +0000941 !(MI.isCall() && MO.getReg() == SP)) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000942 // Remove ranges of all aliased registers.
943 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
Adrian Prantl7509d542016-05-26 21:42:47 +0000944 for (unsigned ID : OpenRanges.getVarLocs())
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000945 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
946 KillSet.set(ID);
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000947 } else if (MO.isRegMask()) {
948 // Remove ranges of all clobbered registers. Register masks don't usually
949 // list SP as preserved. While the debug info may be off for an
950 // instruction or two around callee-cleanup calls, transferring the
951 // DEBUG_VALUE across the call is still a better user experience.
Adrian Prantl7509d542016-05-26 21:42:47 +0000952 for (unsigned ID : OpenRanges.getVarLocs()) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000953 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
954 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
955 KillSet.set(ID);
956 }
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000957 }
Vikram TV859ad292015-12-16 11:09:48 +0000958 }
Adrian Prantl7509d542016-05-26 21:42:47 +0000959 OpenRanges.erase(KillSet, VarLocIDs);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000960
961 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
962 auto &TM = TPC->getTM<TargetMachine>();
Djordje Todorovic97ed7062020-02-12 11:54:29 +0100963 if (TM.Options.EnableDebugEntryValues)
Djordje Todorovic4b4ede42019-12-03 14:18:02 +0100964 emitEntryValues(MI, OpenRanges, VarLocIDs, Transfers, KillSet);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000965 }
Vikram TV859ad292015-12-16 11:09:48 +0000966}
967
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000968bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
Jeremy Morse5d9cd3b2019-09-06 10:08:22 +0000969 MachineFunction *MF) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000970 // TODO: Handle multiple stores folded into one.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000971 if (!MI.hasOneMemOperand())
972 return false;
973
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000974 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
975 return false; // This is not a spill instruction, since no valid size was
976 // returned from either function.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000977
Jeremy Morse5d9cd3b2019-09-06 10:08:22 +0000978 return true;
979}
980
981bool LiveDebugValues::isLocationSpill(const MachineInstr &MI,
982 MachineFunction *MF, unsigned &Reg) {
983 if (!isSpillInstruction(MI, MF))
984 return false;
985
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000986 auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
987 if (!MO.isReg() || !MO.isUse()) {
988 Reg = 0;
989 return false;
990 }
991 Reg = MO.getReg();
992 return MO.isKill();
993 };
994
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000995 for (const MachineOperand &MO : MI.operands()) {
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000996 // In a spill instruction generated by the InlineSpiller the spilled
997 // register has its kill flag set.
998 if (isKilledReg(MO, Reg))
999 return true;
1000 if (Reg != 0) {
1001 // Check whether next instruction kills the spilled register.
1002 // FIXME: Current solution does not cover search for killed register in
1003 // bundles and instructions further down the chain.
1004 auto NextI = std::next(MI.getIterator());
1005 // Skip next instruction that points to basic block end iterator.
1006 if (MI.getParent()->end() == NextI)
1007 continue;
1008 unsigned RegNext;
1009 for (const MachineOperand &MONext : NextI->operands()) {
1010 // Return true if we came across the register from the
1011 // previous spill instruction that is killed in NextI.
1012 if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1013 return true;
1014 }
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001015 }
1016 }
Petar Jovanovic0b464e42018-01-16 14:46:05 +00001017 // Return false if we didn't find spilled register.
1018 return false;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001019}
1020
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001021Optional<LiveDebugValues::VarLoc::SpillLoc>
1022LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
1023 MachineFunction *MF, unsigned &Reg) {
1024 if (!MI.hasOneMemOperand())
1025 return None;
1026
1027 // FIXME: Handle folded restore instructions with more than one memory
1028 // operand.
1029 if (MI.getRestoreSize(TII)) {
1030 Reg = MI.getOperand(0).getReg();
1031 return extractSpillBaseRegAndOffset(MI);
1032 }
1033 return None;
1034}
1035
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001036/// A spilled register may indicate that we have to end the current range of
1037/// a variable and create a new one for the spill location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001038/// A restored register may indicate the reverse situation.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001039/// We don't want to insert any instructions in process(), so we just create
1040/// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001041/// It will be inserted into the BB when we're done iterating over the
1042/// instructions.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001043void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
1044 OpenRangesSet &OpenRanges,
1045 VarLocMap &VarLocIDs,
1046 TransferMap &Transfers) {
Wolfgang Piebfacd0522019-01-30 20:37:14 +00001047 MachineFunction *MF = MI.getMF();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001048 TransferKind TKind;
1049 unsigned Reg;
1050 Optional<VarLoc::SpillLoc> Loc;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001051
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001052 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1053
Jeremy Morse5d9cd3b2019-09-06 10:08:22 +00001054 // First, if there are any DBG_VALUEs pointing at a spill slot that is
1055 // written to, then close the variable location. The value in memory
1056 // will have changed.
1057 VarLocSet KillSet;
1058 if (isSpillInstruction(MI, MF)) {
1059 Loc = extractSpillBaseRegAndOffset(MI);
1060 for (unsigned ID : OpenRanges.getVarLocs()) {
1061 const VarLoc &VL = VarLocIDs[ID];
1062 if (VL.Kind == VarLoc::SpillLocKind && VL.Loc.SpillLocation == *Loc) {
1063 // This location is overwritten by the current instruction -- terminate
1064 // the open range, and insert an explicit DBG_VALUE $noreg.
1065 //
1066 // Doing this at a later stage would require re-interpreting all
1067 // DBG_VALUes and DIExpressions to identify whether they point at
1068 // memory, and then analysing all memory writes to see if they
1069 // overwrite that memory, which is expensive.
1070 //
1071 // At this stage, we already know which DBG_VALUEs are for spills and
1072 // where they are located; it's best to fix handle overwrites now.
1073 KillSet.set(ID);
Jeremy Morse61800a72019-10-04 10:53:47 +00001074 VarLoc UndefVL = VarLoc::CreateCopyLoc(VL.MI, LS, 0);
1075 unsigned UndefLocID = VarLocIDs.insert(UndefVL);
1076 Transfers.push_back({&MI, UndefLocID});
Jeremy Morse5d9cd3b2019-09-06 10:08:22 +00001077 }
1078 }
1079 OpenRanges.erase(KillSet, VarLocIDs);
1080 }
1081
1082 // Try to recognise spill and restore instructions that may create a new
1083 // variable location.
1084 if (isLocationSpill(MI, MF, Reg)) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001085 TKind = TransferKind::TransferSpill;
1086 LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
1087 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1088 << "\n");
1089 } else {
1090 if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
1091 return;
1092 TKind = TransferKind::TransferRestore;
1093 LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
1094 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1095 << "\n");
1096 }
1097 // Check if the register or spill location is the location of a debug value.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001098 for (unsigned ID : OpenRanges.getVarLocs()) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001099 if (TKind == TransferKind::TransferSpill &&
Jeremy Morse8b593482019-08-16 10:04:17 +00001100 VarLocIDs[ID].isDescribedByReg() == Reg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001101 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
stozer269a9af2019-12-03 12:24:41 +00001102 << VarLocIDs[ID].Var.getVariable()->getName() << ")\n");
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001103 } else if (TKind == TransferKind::TransferRestore &&
Jeremy Morseca0e4b32019-08-29 11:20:54 +00001104 VarLocIDs[ID].Kind == VarLoc::SpillLocKind &&
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001105 VarLocIDs[ID].Loc.SpillLocation == *Loc) {
1106 LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
stozer269a9af2019-12-03 12:24:41 +00001107 << VarLocIDs[ID].Var.getVariable()->getName() << ")\n");
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001108 } else
1109 continue;
1110 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
1111 Reg);
1112 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001113 }
1114}
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001115
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001116/// If \p MI is a register copy instruction, that copies a previously tracked
1117/// value from one register to another register that is callee saved, we
1118/// create new DBG_VALUE instruction described with copy destination register.
1119void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
1120 OpenRangesSet &OpenRanges,
1121 VarLocMap &VarLocIDs,
1122 TransferMap &Transfers) {
Djordje Todorovic8d2ccd12019-11-08 11:19:58 +01001123 auto DestSrc = TII->isCopyInstr(MI);
1124 if (!DestSrc)
1125 return;
1126
1127 const MachineOperand *DestRegOp = DestSrc->Destination;
1128 const MachineOperand *SrcRegOp = DestSrc->Source;
Djordje Todorovic4b4ede42019-12-03 14:18:02 +01001129
1130 if (!DestRegOp->isDef())
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001131 return;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001132
David Stenberg2a3dc6b2019-10-25 11:21:11 +02001133 auto isCalleeSavedReg = [&](unsigned Reg) {
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001134 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1135 if (CalleeSavedRegs.test(*RAI))
1136 return true;
1137 return false;
1138 };
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001139
Simon Pilgrim3842b942019-10-31 17:58:15 +00001140 Register SrcReg = SrcRegOp->getReg();
1141 Register DestReg = DestRegOp->getReg();
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001142
1143 // We want to recognize instructions where destination register is callee
1144 // saved register. If register that could be clobbered by the call is
1145 // included, there would be a great chance that it is going to be clobbered
1146 // soon. It is more likely that previous register location, which is callee
1147 // saved, is going to stay unclobbered longer, even if it is killed.
David Stenberg2a3dc6b2019-10-25 11:21:11 +02001148 if (!isCalleeSavedReg(DestReg))
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001149 return;
1150
Djordje Todorovic4b4ede42019-12-03 14:18:02 +01001151 // Remember an entry value movement. If we encounter a new debug value of
1152 // a parameter describing only a moving of the value around, rather then
1153 // modifying it, we are still able to use the entry value if needed.
1154 if (isRegOtherThanSPAndFP(*DestRegOp, MI, TRI)) {
1155 for (unsigned ID : OpenRanges.getVarLocs()) {
1156 if (VarLocIDs[ID].getEntryValueBackupReg() == SrcReg) {
1157 LLVM_DEBUG(dbgs() << "Copy of the entry value: "; MI.dump(););
1158 VarLoc EntryValLocCopyBackup = VarLoc::CreateEntryCopyBackupLoc(
1159 VarLocIDs[ID].MI, LS, VarLocIDs[ID].Expr, DestReg);
1160
1161 // Stop tracking the original entry value.
1162 OpenRanges.erase(VarLocIDs[ID]);
1163
1164 // Start tracking the entry value copy.
1165 unsigned EntryValCopyLocID = VarLocIDs.insert(EntryValLocCopyBackup);
1166 OpenRanges.insert(EntryValCopyLocID, EntryValLocCopyBackup);
1167 break;
1168 }
1169 }
1170 }
1171
1172 if (!SrcRegOp->isKill())
1173 return;
1174
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001175 for (unsigned ID : OpenRanges.getVarLocs()) {
1176 if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
1177 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +00001178 TransferKind::TransferCopy, DestReg);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001179 return;
1180 }
1181 }
1182}
1183
Vikram TV859ad292015-12-16 11:09:48 +00001184/// Terminate all open ranges at the end of the current basic block.
Jeremy Morse67443c32019-08-21 09:22:31 +00001185bool LiveDebugValues::transferTerminator(MachineBasicBlock *CurMBB,
1186 OpenRangesSet &OpenRanges,
1187 VarLocInMBB &OutLocs,
1188 const VarLocMap &VarLocIDs) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001189 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +00001190
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001191 LLVM_DEBUG(for (unsigned ID
1192 : OpenRanges.getVarLocs()) {
1193 // Copy OpenRanges to OutLocs, if not already present.
Vedant Kumar9b558382018-10-05 21:44:00 +00001194 dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
Jeremy Morse61800a72019-10-04 10:53:47 +00001195 VarLocIDs[ID].dump(TRI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001196 });
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001197 VarLocSet &VLS = OutLocs[CurMBB];
Jeremy Morse0ae54982019-08-23 16:33:42 +00001198 Changed = VLS != OpenRanges.getVarLocs();
Nikola Prica2d0106a2019-06-03 09:48:29 +00001199 // New OutLocs set may be different due to spill, restore or register
1200 // copy instruction processing.
1201 if (Changed)
1202 VLS = OpenRanges.getVarLocs();
Vikram TV859ad292015-12-16 11:09:48 +00001203 OpenRanges.clear();
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001204 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +00001205}
1206
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001207/// Accumulate a mapping between each DILocalVariable fragment and other
1208/// fragments of that DILocalVariable which overlap. This reduces work during
1209/// the data-flow stage from "Find any overlapping fragments" to "Check if the
1210/// known-to-overlap fragments are present".
1211/// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
1212/// fragment usage.
1213/// \param SeenFragments Map from DILocalVariable to all fragments of that
1214/// Variable which are known to exist.
1215/// \param OverlappingFragments The overlap map being constructed, from one
1216/// Var/Fragment pair to a vector of fragments known to overlap.
1217void LiveDebugValues::accumulateFragmentMap(MachineInstr &MI,
1218 VarToFragments &SeenFragments,
1219 OverlapMap &OverlappingFragments) {
stozer269a9af2019-12-03 12:24:41 +00001220 DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1221 MI.getDebugLoc()->getInlinedAt());
1222 FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001223
1224 // If this is the first sighting of this variable, then we are guaranteed
1225 // there are currently no overlapping fragments either. Initialize the set
1226 // of seen fragments, record no overlaps for the current one, and return.
stozer269a9af2019-12-03 12:24:41 +00001227 auto SeenIt = SeenFragments.find(MIVar.getVariable());
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001228 if (SeenIt == SeenFragments.end()) {
1229 SmallSet<FragmentInfo, 4> OneFragment;
1230 OneFragment.insert(ThisFragment);
stozer269a9af2019-12-03 12:24:41 +00001231 SeenFragments.insert({MIVar.getVariable(), OneFragment});
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001232
stozer269a9af2019-12-03 12:24:41 +00001233 OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001234 return;
1235 }
1236
1237 // If this particular Variable/Fragment pair already exists in the overlap
1238 // map, it has already been accounted for.
1239 auto IsInOLapMap =
stozer269a9af2019-12-03 12:24:41 +00001240 OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001241 if (!IsInOLapMap.second)
1242 return;
1243
1244 auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1245 auto &AllSeenFragments = SeenIt->second;
1246
1247 // Otherwise, examine all other seen fragments for this variable, with "this"
1248 // fragment being a previously unseen fragment. Record any pair of
1249 // overlapping fragments.
1250 for (auto &ASeenFragment : AllSeenFragments) {
1251 // Does this previously seen fragment overlap?
1252 if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1253 // Yes: Mark the current fragment as being overlapped.
1254 ThisFragmentsOverlaps.push_back(ASeenFragment);
1255 // Mark the previously seen fragment as being overlapped by the current
1256 // one.
1257 auto ASeenFragmentsOverlaps =
stozer269a9af2019-12-03 12:24:41 +00001258 OverlappingFragments.find({MIVar.getVariable(), ASeenFragment});
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001259 assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
1260 "Previously seen var fragment has no vector of overlaps");
1261 ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1262 }
1263 }
1264
1265 AllSeenFragments.insert(ThisFragment);
1266}
1267
Djordje Todorovic8c99a542019-10-24 10:08:43 +02001268/// This routine creates OpenRanges.
Jeremy Morse67443c32019-08-21 09:22:31 +00001269void LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
Djordje Todorovic4b4ede42019-12-03 14:18:02 +01001270 VarLocMap &VarLocIDs, TransferMap &Transfers) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001271 transferDebugValue(MI, OpenRanges, VarLocIDs);
Djordje Todorovic4b4ede42019-12-03 14:18:02 +01001272 transferRegisterDef(MI, OpenRanges, VarLocIDs, Transfers);
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001273 transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
1274 transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
Vikram TV859ad292015-12-16 11:09:48 +00001275}
1276
1277/// This routine joins the analysis results of all incoming edges in @MBB by
1278/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1279/// source variable in all the predecessors of @MBB reside in the same location.
Vedant Kumar8c466682018-10-05 21:44:15 +00001280bool LiveDebugValues::join(
1281 MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1282 const VarLocMap &VarLocIDs,
1283 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
Jeremy Morse67443c32019-08-21 09:22:31 +00001284 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks,
1285 VarLocInMBB &PendingInLocs) {
Vedant Kumar9b558382018-10-05 21:44:00 +00001286 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001287 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +00001288
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001289 VarLocSet InLocsT; // Temporary incoming locations.
Vikram TV859ad292015-12-16 11:09:48 +00001290
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001291 // For all predecessors of this MBB, find the set of VarLocs that
1292 // can be joined.
Keith Walker83ebef52016-09-27 16:46:07 +00001293 int NumVisited = 0;
Vikram TV859ad292015-12-16 11:09:48 +00001294 for (auto p : MBB.predecessors()) {
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001295 // Ignore backedges if we have not visited the predecessor yet. As the
1296 // predecessor hasn't yet had locations propagated into it, most locations
1297 // will not yet be valid, so treat them as all being uninitialized and
1298 // potentially valid. If a location guessed to be correct here is
1299 // invalidated later, we will remove it when we revisit this block.
Vedant Kumar9b558382018-10-05 21:44:00 +00001300 if (!Visited.count(p)) {
1301 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
1302 << "\n");
Keith Walker83ebef52016-09-27 16:46:07 +00001303 continue;
Vedant Kumar9b558382018-10-05 21:44:00 +00001304 }
Vikram TV859ad292015-12-16 11:09:48 +00001305 auto OL = OutLocs.find(p);
1306 // Join is null in case of empty OutLocs from any of the pred.
1307 if (OL == OutLocs.end())
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001308 return false;
Vikram TV859ad292015-12-16 11:09:48 +00001309
Keith Walker83ebef52016-09-27 16:46:07 +00001310 // Just copy over the Out locs to incoming locs for the first visited
1311 // predecessor, and for all other predecessors join the Out locs.
1312 if (!NumVisited)
Vikram TV859ad292015-12-16 11:09:48 +00001313 InLocsT = OL->second;
Keith Walker83ebef52016-09-27 16:46:07 +00001314 else
1315 InLocsT &= OL->second;
Vedant Kumar9b558382018-10-05 21:44:00 +00001316
1317 LLVM_DEBUG({
1318 if (!InLocsT.empty()) {
1319 for (auto ID : InLocsT)
1320 dbgs() << " gathered candidate incoming var: "
stozer269a9af2019-12-03 12:24:41 +00001321 << VarLocIDs[ID].Var.getVariable()->getName() << "\n";
Vedant Kumar9b558382018-10-05 21:44:00 +00001322 }
1323 });
1324
Keith Walker83ebef52016-09-27 16:46:07 +00001325 NumVisited++;
Vikram TV859ad292015-12-16 11:09:48 +00001326 }
1327
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001328 // Filter out DBG_VALUES that are out of scope.
1329 VarLocSet KillSet;
Vedant Kumar8c466682018-10-05 21:44:15 +00001330 bool IsArtificial = ArtificialBlocks.count(&MBB);
1331 if (!IsArtificial) {
1332 for (auto ID : InLocsT) {
1333 if (!VarLocIDs[ID].dominates(MBB)) {
1334 KillSet.set(ID);
1335 LLVM_DEBUG({
stozer269a9af2019-12-03 12:24:41 +00001336 auto Name = VarLocIDs[ID].Var.getVariable()->getName();
Vedant Kumar8c466682018-10-05 21:44:15 +00001337 dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
1338 });
1339 }
Vedant Kumar9b558382018-10-05 21:44:00 +00001340 }
1341 }
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001342 InLocsT.intersectWithComplement(KillSet);
1343
Keith Walker83ebef52016-09-27 16:46:07 +00001344 // As we are processing blocks in reverse post-order we
1345 // should have processed at least one predecessor, unless it
1346 // is the entry block which has no predecessor.
1347 assert((NumVisited || MBB.pred_empty()) &&
1348 "Should have processed at least one predecessor");
Vikram TV859ad292015-12-16 11:09:48 +00001349
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001350 VarLocSet &ILS = InLocs[&MBB];
Jeremy Morse67443c32019-08-21 09:22:31 +00001351 VarLocSet &Pending = PendingInLocs[&MBB];
Vikram TV859ad292015-12-16 11:09:48 +00001352
Jeremy Morse67443c32019-08-21 09:22:31 +00001353 // New locations will have DBG_VALUE insts inserted at the start of the
1354 // block, after location propagation has finished. Record the insertions
1355 // that we need to perform in the Pending set.
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001356 VarLocSet Diff = InLocsT;
1357 Diff.intersectWithComplement(ILS);
1358 for (auto ID : Diff) {
Jeremy Morse67443c32019-08-21 09:22:31 +00001359 Pending.set(ID);
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001360 ILS.set(ID);
1361 ++NumInserted;
1362 Changed = true;
Vikram TV859ad292015-12-16 11:09:48 +00001363 }
Jeremy Morse0ae54982019-08-23 16:33:42 +00001364
1365 // We may have lost locations by learning about a predecessor that either
1366 // loses or moves a variable. Find any locations in ILS that are not in the
1367 // new in-locations, and delete those.
1368 VarLocSet Removed = ILS;
1369 Removed.intersectWithComplement(InLocsT);
1370 for (auto ID : Removed) {
1371 Pending.reset(ID);
1372 ILS.reset(ID);
1373 ++NumRemoved;
1374 Changed = true;
1375 }
1376
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001377 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +00001378}
1379
Jeremy Morse67443c32019-08-21 09:22:31 +00001380void LiveDebugValues::flushPendingLocs(VarLocInMBB &PendingInLocs,
1381 VarLocMap &VarLocIDs) {
1382 // PendingInLocs records all locations propagated into blocks, which have
1383 // not had DBG_VALUE insts created. Go through and create those insts now.
1384 for (auto &Iter : PendingInLocs) {
1385 // Map is keyed on a constant pointer, unwrap it so we can insert insts.
1386 auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
1387 VarLocSet &Pending = Iter.second;
1388
1389 for (unsigned ID : Pending) {
1390 // The ID location is live-in to MBB -- work out what kind of machine
1391 // location it is and create a DBG_VALUE.
1392 const VarLoc &DiffIt = VarLocIDs[ID];
Djordje Todorovic4b4ede42019-12-03 14:18:02 +01001393 if (DiffIt.isEntryBackupLoc())
1394 continue;
Jeremy Morse61800a72019-10-04 10:53:47 +00001395 MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent());
1396 MBB.insert(MBB.instr_begin(), MI);
Jeremy Morse67443c32019-08-21 09:22:31 +00001397
Jeremy Morsec8c5f2a2019-09-04 10:18:03 +00001398 (void)MI;
Jeremy Morse67443c32019-08-21 09:22:31 +00001399 LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
1400 }
1401 }
1402}
1403
David Stenberg5e646ff2019-11-13 10:37:53 +01001404bool LiveDebugValues::isEntryValueCandidate(
1405 const MachineInstr &MI, const DefinedRegsSet &DefinedRegs) const {
Djordje Todorovic4b4ede42019-12-03 14:18:02 +01001406 assert(MI.isDebugValue() && "This must be DBG_VALUE.");
David Stenberg4fec44c2019-11-13 10:36:13 +01001407
1408 // TODO: Add support for local variables that are expressed in terms of
1409 // parameters entry values.
1410 // TODO: Add support for modified arguments that can be expressed
1411 // by using its entry value.
1412 auto *DIVar = MI.getDebugVariable();
Djordje Todorovic979592a2019-11-20 12:20:53 +01001413 if (!DIVar->isParameter())
David Stenberg4fec44c2019-11-13 10:36:13 +01001414 return false;
1415
1416 // Do not consider parameters that belong to an inlined function.
1417 if (MI.getDebugLoc()->getInlinedAt())
1418 return false;
1419
1420 // Do not consider indirect debug values (TODO: explain why).
1421 if (MI.isIndirectDebugValue())
1422 return false;
1423
1424 // Only consider parameters that are described using registers. Parameters
1425 // that are passed on the stack are not yet supported, so ignore debug
1426 // values that are described by the frame or stack pointer.
1427 if (!isRegOtherThanSPAndFP(MI.getOperand(0), MI, TRI))
1428 return false;
1429
David Stenberg5e646ff2019-11-13 10:37:53 +01001430 // If a parameter's value has been propagated from the caller, then the
1431 // parameter's DBG_VALUE may be described using a register defined by some
1432 // instruction in the entry block, in which case we shouldn't create an
1433 // entry value.
1434 if (DefinedRegs.count(MI.getOperand(0).getReg()))
1435 return false;
1436
David Stenberg5c7cc6f2019-12-13 10:37:53 +01001437 // TODO: Add support for parameters that have a pre-existing debug expressions
1438 // (e.g. fragments, or indirect parameters using DW_OP_deref).
1439 if (MI.getDebugExpression()->getNumElements() > 0)
David Stenberg4fec44c2019-11-13 10:36:13 +01001440 return false;
1441
1442 return true;
1443}
1444
David Stenberg5e646ff2019-11-13 10:37:53 +01001445/// Collect all register defines (including aliases) for the given instruction.
1446static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs,
1447 const TargetRegisterInfo *TRI) {
1448 for (const MachineOperand &MO : MI.operands())
1449 if (MO.isReg() && MO.isDef() && MO.getReg())
1450 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
1451 Regs.insert(*AI);
1452}
1453
Djordje Todorovic4b4ede42019-12-03 14:18:02 +01001454/// This routine records the entry values of function parameters. The values
1455/// could be used as backup values. If we loose the track of some unmodified
1456/// parameters, the backup values will be used as a primary locations.
1457void LiveDebugValues::recordEntryValue(const MachineInstr &MI,
1458 const DefinedRegsSet &DefinedRegs,
1459 OpenRangesSet &OpenRanges,
1460 VarLocMap &VarLocIDs) {
1461 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
1462 auto &TM = TPC->getTM<TargetMachine>();
Djordje Todorovic97ed7062020-02-12 11:54:29 +01001463 if (!TM.Options.EnableDebugEntryValues)
Djordje Todorovic4b4ede42019-12-03 14:18:02 +01001464 return;
1465 }
1466
1467 DebugVariable V(MI.getDebugVariable(), MI.getDebugExpression(),
1468 MI.getDebugLoc()->getInlinedAt());
1469
1470 if (!isEntryValueCandidate(MI, DefinedRegs) ||
1471 OpenRanges.getEntryValueBackup(V))
1472 return;
1473
1474 LLVM_DEBUG(dbgs() << "Creating the backup entry location: "; MI.dump(););
1475
1476 // Create the entry value and use it as a backup location until it is
1477 // valid. It is valid until a parameter is not changed.
1478 DIExpression *NewExpr =
1479 DIExpression::prepend(MI.getDebugExpression(), DIExpression::EntryValue);
1480 VarLoc EntryValLocAsBackup = VarLoc::CreateEntryBackupLoc(MI, LS, NewExpr);
1481 unsigned EntryValLocID = VarLocIDs.insert(EntryValLocAsBackup);
1482 OpenRanges.insert(EntryValLocID, EntryValLocAsBackup);
1483}
1484
Vikram TV859ad292015-12-16 11:09:48 +00001485/// Calculate the liveness information for the given machine function and
1486/// extend ranges across basic blocks.
1487bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001488 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
Vikram TV859ad292015-12-16 11:09:48 +00001489
1490 bool Changed = false;
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001491 bool OLChanged = false;
1492 bool MBBJoined = false;
Vikram TV859ad292015-12-16 11:09:48 +00001493
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001494 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
Djordje Todorovic8c99a542019-10-24 10:08:43 +02001495 OverlapMap OverlapFragments; // Map of overlapping variable fragments.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001496 OpenRangesSet OpenRanges(OverlapFragments);
1497 // Ranges that are open until end of bb.
1498 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
1499 VarLocInMBB InLocs; // Ranges that are incoming after joining.
Djordje Todorovic8c99a542019-10-24 10:08:43 +02001500 TransferMap Transfers; // DBG_VALUEs associated with transfers (such as
1501 // spills, copies and restores).
Jeremy Morse67443c32019-08-21 09:22:31 +00001502 VarLocInMBB PendingInLocs; // Ranges that are incoming after joining, but
1503 // that we have deferred creating DBG_VALUE insts
1504 // for immediately.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001505
1506 VarToFragments SeenFragments;
Vikram TV859ad292015-12-16 11:09:48 +00001507
Vedant Kumar8c466682018-10-05 21:44:15 +00001508 // Blocks which are artificial, i.e. blocks which exclusively contain
1509 // instructions without locations, or with line 0 locations.
1510 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1511
Daniel Berlin72560592016-01-10 18:08:32 +00001512 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1513 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1514 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001515 std::greater<unsigned int>>
1516 Worklist;
Daniel Berlin72560592016-01-10 18:08:32 +00001517 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001518 std::greater<unsigned int>>
1519 Pending;
1520
David Stenberg5e646ff2019-11-13 10:37:53 +01001521 // Set of register defines that are seen when traversing the entry block
1522 // looking for debug entry value candidates.
1523 DefinedRegsSet DefinedRegs;
1524
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001525 // Only in the case of entry MBB collect DBG_VALUEs representing
1526 // function parameters in order to generate debug entry values for them.
David Stenberg4fec44c2019-11-13 10:36:13 +01001527 MachineBasicBlock &First_MBB = *(MF.begin());
David Stenberg5e646ff2019-11-13 10:37:53 +01001528 for (auto &MI : First_MBB) {
1529 collectRegDefs(MI, DefinedRegs, TRI);
Djordje Todorovic4b4ede42019-12-03 14:18:02 +01001530 if (MI.isDebugValue())
1531 recordEntryValue(MI, DefinedRegs, OpenRanges, VarLocIDs);
David Stenberg5e646ff2019-11-13 10:37:53 +01001532 }
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001533
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001534 // Initialize per-block structures and scan for fragment overlaps.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001535 for (auto &MBB : MF) {
Jeremy Morse67443c32019-08-21 09:22:31 +00001536 PendingInLocs[&MBB] = VarLocSet();
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001537
1538 for (auto &MI : MBB) {
1539 if (MI.isDebugValue())
1540 accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
1541 }
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001542 }
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001543
Vedant Kumar8c466682018-10-05 21:44:15 +00001544 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
1545 if (const DebugLoc &DL = MI.getDebugLoc())
1546 return DL.getLine() != 0;
1547 return false;
1548 };
1549 for (auto &MBB : MF)
1550 if (none_of(MBB.instrs(), hasNonArtificialLocation))
1551 ArtificialBlocks.insert(&MBB);
1552
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001553 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1554 "OutLocs after initialization", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001555
Daniel Berlin72560592016-01-10 18:08:32 +00001556 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1557 unsigned int RPONumber = 0;
1558 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
1559 OrderToBB[RPONumber] = *RI;
1560 BBToOrder[*RI] = RPONumber;
1561 Worklist.push(RPONumber);
1562 ++RPONumber;
1563 }
Daniel Berlin72560592016-01-10 18:08:32 +00001564 // This is a standard "union of predecessor outs" dataflow problem.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001565 // To solve it, we perform join() and process() using the two worklist method
Daniel Berlin72560592016-01-10 18:08:32 +00001566 // until the ranges converge.
1567 // Ranges have converged when both worklists are empty.
Keith Walker83ebef52016-09-27 16:46:07 +00001568 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
Daniel Berlin72560592016-01-10 18:08:32 +00001569 while (!Worklist.empty() || !Pending.empty()) {
1570 // We track what is on the pending worklist to avoid inserting the same
1571 // thing twice. We could avoid this with a custom priority queue, but this
1572 // is probably not worth it.
1573 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001574 LLVM_DEBUG(dbgs() << "Processing Worklist\n");
Daniel Berlin72560592016-01-10 18:08:32 +00001575 while (!Worklist.empty()) {
1576 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
1577 Worklist.pop();
Jeremy Morse67443c32019-08-21 09:22:31 +00001578 MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
1579 ArtificialBlocks, PendingInLocs);
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001580 MBBJoined |= Visited.insert(MBB).second;
Daniel Berlin72560592016-01-10 18:08:32 +00001581 if (MBBJoined) {
1582 MBBJoined = false;
1583 Changed = true;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001584 // Now that we have started to extend ranges across BBs we need to
Djordje Todorovic8c99a542019-10-24 10:08:43 +02001585 // examine spill, copy and restore instructions to see whether they
1586 // operate with registers that correspond to user variables.
Jeremy Morse67443c32019-08-21 09:22:31 +00001587 // First load any pending inlocs.
1588 OpenRanges.insertFromLocSet(PendingInLocs[MBB], VarLocIDs);
Daniel Berlin72560592016-01-10 18:08:32 +00001589 for (auto &MI : *MBB)
Djordje Todorovic4b4ede42019-12-03 14:18:02 +01001590 process(MI, OpenRanges, VarLocIDs, Transfers);
Jeremy Morse67443c32019-08-21 09:22:31 +00001591 OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001592
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001593 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1594 "OutLocs after propagating", dbgs()));
1595 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
1596 "InLocs after propagating", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001597
Daniel Berlin72560592016-01-10 18:08:32 +00001598 if (OLChanged) {
1599 OLChanged = false;
1600 for (auto s : MBB->successors())
Benjamin Kramer4dea8f52016-06-17 18:59:41 +00001601 if (OnPending.insert(s).second) {
Daniel Berlin72560592016-01-10 18:08:32 +00001602 Pending.push(BBToOrder[s]);
1603 }
1604 }
Vikram TV859ad292015-12-16 11:09:48 +00001605 }
1606 }
Daniel Berlin72560592016-01-10 18:08:32 +00001607 Worklist.swap(Pending);
1608 // At this point, pending must be empty, since it was just the empty
1609 // worklist
1610 assert(Pending.empty() && "Pending should be empty");
Vikram TV859ad292015-12-16 11:09:48 +00001611 }
Daniel Berlin72560592016-01-10 18:08:32 +00001612
Jeremy Morse0ca48de22019-10-04 09:38:05 +00001613 // Add any DBG_VALUE instructions created by location transfers.
1614 for (auto &TR : Transfers) {
Jeremy Morse61800a72019-10-04 10:53:47 +00001615 MachineBasicBlock *MBB = TR.TransferInst->getParent();
1616 const VarLoc &VL = VarLocIDs[TR.LocationID];
1617 MachineInstr *MI = VL.BuildDbgValue(MF);
1618 MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI);
Jeremy Morse0ca48de22019-10-04 09:38:05 +00001619 }
1620 Transfers.clear();
1621
Jeremy Morse67443c32019-08-21 09:22:31 +00001622 // Deferred inlocs will not have had any DBG_VALUE insts created; do
1623 // that now.
1624 flushPendingLocs(PendingInLocs, VarLocIDs);
1625
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001626 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
1627 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001628 return Changed;
1629}
1630
1631bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001632 if (!MF.getFunction().getSubprogram())
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001633 // LiveDebugValues will already have removed all DBG_VALUEs.
1634 return false;
1635
Wolfgang Piebe018bbd2017-07-19 19:36:40 +00001636 // Skip functions from NoDebug compilation units.
Matthias Braunf1caa282017-12-15 22:22:58 +00001637 if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
Wolfgang Piebe018bbd2017-07-19 19:36:40 +00001638 DICompileUnit::NoDebug)
1639 return false;
1640
Vikram TV859ad292015-12-16 11:09:48 +00001641 TRI = MF.getSubtarget().getRegisterInfo();
1642 TII = MF.getSubtarget().getInstrInfo();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001643 TFI = MF.getSubtarget().getFrameLowering();
Sander de Smalend6a7da82019-10-29 12:49:34 +00001644 TFI->getCalleeSaves(MF, CalleeSavedRegs);
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001645 LS.initialize(MF);
Vikram TV859ad292015-12-16 11:09:48 +00001646
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001647 bool Changed = ExtendRanges(MF);
Vikram TV859ad292015-12-16 11:09:48 +00001648 return Changed;
1649}