blob: ac96c738274c4b9296c27f4848f6349345507c9e [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
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000222 VarLoc(const MachineInstr &MI, LexicalScopes &LS,
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000223 VarLocKind K = InvalidKind)
224 : Var(MI), Expr(MI.getDebugExpression()), MI(MI),
225 UVS(MI.getDebugLoc(), LS) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000226 static_assert((sizeof(Loc) == sizeof(uint64_t)),
227 "hash does not cover all members of Loc");
228 assert(MI.isDebugValue() && "not a DBG_VALUE");
229 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
Adrian Prantl00698732016-05-25 22:37:29 +0000230 if (int RegNo = isDbgValueDescribedByReg(MI)) {
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000231 Kind = MI.isDebugEntryValue() ? EntryValueKind : RegisterKind;
Adrian Prantl359846f2017-07-28 23:25:51 +0000232 Loc.RegNo = RegNo;
Jeremy Morsebcff4172019-06-10 15:23:46 +0000233 } else if (MI.getOperand(0).isImm()) {
234 Kind = ImmediateKind;
235 Loc.Immediate = MI.getOperand(0).getImm();
236 } else if (MI.getOperand(0).isFPImm()) {
237 Kind = ImmediateKind;
238 Loc.FPImm = MI.getOperand(0).getFPImm();
239 } else if (MI.getOperand(0).isCImm()) {
240 Kind = ImmediateKind;
241 Loc.CImm = MI.getOperand(0).getCImm();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000242 }
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000243 assert((Kind != ImmediateKind || !MI.isDebugEntryValue()) &&
244 "entry values must be register locations");
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000245 }
246
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000247 /// The constructor for spill locations.
248 VarLoc(const MachineInstr &MI, unsigned SpillBase, int SpillOffset,
Jeremy Morse8b593482019-08-16 10:04:17 +0000249 LexicalScopes &LS, const MachineInstr &OrigMI)
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000250 : Var(MI), Expr(MI.getDebugExpression()), MI(OrigMI),
251 UVS(MI.getDebugLoc(), LS) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000252 assert(MI.isDebugValue() && "not a DBG_VALUE");
253 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
254 Kind = SpillLocKind;
255 Loc.SpillLocation = {SpillBase, SpillOffset};
256 }
257
Jeremy Morsebcff4172019-06-10 15:23:46 +0000258 // Is the Loc field a constant or constant object?
259 bool isConstant() const { return Kind == ImmediateKind; }
260
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000261 /// If this variable is described by a register, return it,
262 /// otherwise return 0.
263 unsigned isDescribedByReg() const {
264 if (Kind == RegisterKind)
Adrian Prantl359846f2017-07-28 23:25:51 +0000265 return Loc.RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000266 return 0;
267 }
268
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000269 /// Determine whether the lexical scope of this value's debug location
270 /// dominates MBB.
271 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
272
Aaron Ballman615eb472017-10-15 14:32:27 +0000273#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun194ded52017-01-28 06:53:55 +0000274 LLVM_DUMP_METHOD void dump() const { MI.dump(); }
275#endif
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000276
277 bool operator==(const VarLoc &Other) const {
Jeremy Morsebcff4172019-06-10 15:23:46 +0000278 return Kind == Other.Kind && Var == Other.Var &&
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000279 Loc.Hash == Other.Loc.Hash && Expr == Other.Expr;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000280 }
281
Adrian Prantl7509d542016-05-26 21:42:47 +0000282 /// This operator guarantees that VarLocs are sorted by Variable first.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000283 bool operator<(const VarLoc &Other) const {
Jeremy Morse337a7cb2019-09-04 11:09:05 +0000284 return std::tie(Var, Kind, Loc.Hash, Expr) <
285 std::tie(Other.Var, Other.Kind, Other.Loc.Hash, Other.Expr);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000286 }
Vikram TV859ad292015-12-16 11:09:48 +0000287 };
288
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000289 using DebugParamMap = SmallDenseMap<const DILocalVariable *, MachineInstr *>;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000290 using VarLocMap = UniqueVector<VarLoc>;
291 using VarLocSet = SparseBitVector<>;
292 using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000293 struct TransferDebugPair {
294 MachineInstr *TransferInst;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000295 MachineInstr *DebugInst;
296 };
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000297 using TransferMap = SmallVector<TransferDebugPair, 4>;
Vikram TV859ad292015-12-16 11:09:48 +0000298
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000299 // Types for recording sets of variable fragments that overlap. For a given
300 // local variable, we record all other fragments of that variable that could
301 // overlap it, to reduce search time.
302 using FragmentOfVar =
303 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
304 using OverlapMap =
305 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
306
307 // Helper while building OverlapMap, a map of all fragments seen for a given
308 // DILocalVariable.
309 using VarToFragments =
310 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
311
Adrian Prantl7509d542016-05-26 21:42:47 +0000312 /// This holds the working set of currently open ranges. For fast
313 /// access, this is done both as a set of VarLocIDs, and a map of
314 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
315 /// previous open ranges for the same variable.
316 class OpenRangesSet {
317 VarLocSet VarLocs;
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000318 SmallDenseMap<DebugVariable, unsigned, 8> Vars;
319 OverlapMap &OverlappingFragments;
Adrian Prantl7509d542016-05-26 21:42:47 +0000320
321 public:
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000322 OpenRangesSet(OverlapMap &_OLapMap) : OverlappingFragments(_OLapMap) {}
323
Adrian Prantl7509d542016-05-26 21:42:47 +0000324 const VarLocSet &getVarLocs() const { return VarLocs; }
325
326 /// Terminate all open ranges for Var by removing it from the set.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000327 void erase(DebugVariable Var);
Adrian Prantl7509d542016-05-26 21:42:47 +0000328
329 /// Terminate all open ranges listed in \c KillSet by removing
330 /// them from the set.
331 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
332 VarLocs.intersectWithComplement(KillSet);
333 for (unsigned ID : KillSet)
334 Vars.erase(VarLocIDs[ID].Var);
335 }
336
337 /// Insert a new range into the set.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000338 void insert(unsigned VarLocID, DebugVariable Var) {
Adrian Prantl7509d542016-05-26 21:42:47 +0000339 VarLocs.set(VarLocID);
340 Vars.insert({Var, VarLocID});
341 }
342
Jeremy Morse67443c32019-08-21 09:22:31 +0000343 /// Insert a set of ranges.
344 void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map) {
345 for (unsigned Id : ToLoad) {
346 const VarLoc &Var = Map[Id];
347 insert(Id, Var.Var);
348 }
349 }
350
Adrian Prantl7509d542016-05-26 21:42:47 +0000351 /// Empty the set.
352 void clear() {
353 VarLocs.clear();
354 Vars.clear();
355 }
356
357 /// Return whether the set is empty or not.
358 bool empty() const {
359 assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
360 return VarLocs.empty();
361 }
362 };
363
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000364 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
365 unsigned &Reg);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000366 /// If a given instruction is identified as a spill, return the spill location
367 /// and set \p Reg to the spilled register.
368 Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
369 MachineFunction *MF,
370 unsigned &Reg);
371 /// Given a spill instruction, extract the register and offset used to
372 /// address the spill location in a target independent way.
373 VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000374 void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
375 TransferMap &Transfers, VarLocMap &VarLocIDs,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000376 unsigned OldVarID, TransferKind Kind,
377 unsigned NewReg = 0);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000378
Adrian Prantl7509d542016-05-26 21:42:47 +0000379 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000380 VarLocMap &VarLocIDs);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000381 void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
382 VarLocMap &VarLocIDs, TransferMap &Transfers);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000383 void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
384 VarLocMap &VarLocIDs, TransferMap &Transfers,
385 DebugParamMap &DebugEntryVals,
386 SparseBitVector<> &KillSet);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000387 void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
388 VarLocMap &VarLocIDs, TransferMap &Transfers);
Adrian Prantl7509d542016-05-26 21:42:47 +0000389 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000390 VarLocMap &VarLocIDs, TransferMap &Transfers,
391 DebugParamMap &DebugEntryVals);
Jeremy Morse67443c32019-08-21 09:22:31 +0000392 bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
393 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
Nikola Prica441ad622019-05-27 13:51:30 +0000394
Jeremy Morse67443c32019-08-21 09:22:31 +0000395 void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000396 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000397 TransferMap &Transfers, DebugParamMap &DebugEntryVals,
Jeremy Morse313d2ce2019-08-29 10:53:29 +0000398 OverlapMap &OverlapFragments,
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000399 VarToFragments &SeenFragments);
Vikram TV859ad292015-12-16 11:09:48 +0000400
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000401 void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
402 OverlapMap &OLapMap);
403
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000404 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000405 const VarLocMap &VarLocIDs,
Vedant Kumar8c466682018-10-05 21:44:15 +0000406 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
Jeremy Morse67443c32019-08-21 09:22:31 +0000407 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks,
408 VarLocInMBB &PendingInLocs);
409
410 /// Create DBG_VALUE insts for inlocs that have been propagated but
411 /// had their instruction creation deferred.
412 void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
Vikram TV859ad292015-12-16 11:09:48 +0000413
414 bool ExtendRanges(MachineFunction &MF);
415
416public:
417 static char ID;
418
419 /// Default construct and initialize the pass.
420 LiveDebugValues();
421
422 /// Tell the pass manager which passes we depend on and what
423 /// information we preserve.
424 void getAnalysisUsage(AnalysisUsage &AU) const override;
425
Derek Schuffad154c82016-03-28 17:05:30 +0000426 MachineFunctionProperties getRequiredProperties() const override {
427 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000428 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000429 }
430
Vikram TV859ad292015-12-16 11:09:48 +0000431 /// Print to ostream with a message.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000432 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
433 const VarLocMap &VarLocIDs, const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000434 raw_ostream &Out) const;
435
436 /// Calculate the liveness information for the given machine function.
437 bool runOnMachineFunction(MachineFunction &MF) override;
438};
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000439
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000440} // end anonymous namespace
Vikram TV859ad292015-12-16 11:09:48 +0000441
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000442namespace llvm {
443
444template <> struct DenseMapInfo<LiveDebugValues::DebugVariable> {
445 using DV = LiveDebugValues::DebugVariable;
446 using OptFragmentInfo = LiveDebugValues::OptFragmentInfo;
447 using FragmentInfo = LiveDebugValues::FragmentInfo;
448
449 // Empty key: no key should be generated that has no DILocalVariable.
450 static inline DV getEmptyKey() {
451 return DV(nullptr, OptFragmentInfo(), nullptr);
452 }
453
454 // Difference in tombstone is that the Optional is meaningful
455 static inline DV getTombstoneKey() {
456 return DV(nullptr, OptFragmentInfo({0, 0}), nullptr);
457 }
458
459 static unsigned getHashValue(const DV &D) {
460 unsigned HV = 0;
461 const OptFragmentInfo &Fragment = D.getFragment();
462 if (Fragment)
463 HV = DenseMapInfo<FragmentInfo>::getHashValue(*Fragment);
464
465 return hash_combine(D.getVar(), HV, D.getInlinedAt());
466 }
467
468 static bool isEqual(const DV &A, const DV &B) { return A == B; }
469};
470
David Stenberg1278a192019-06-13 14:02:55 +0000471} // namespace llvm
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000472
Vikram TV859ad292015-12-16 11:09:48 +0000473//===----------------------------------------------------------------------===//
474// Implementation
475//===----------------------------------------------------------------------===//
476
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000477const DIExpression::FragmentInfo
478 LiveDebugValues::DebugVariable::DefaultFragment = {
479 std::numeric_limits<uint64_t>::max(),
480 std::numeric_limits<uint64_t>::min()};
481
Vikram TV859ad292015-12-16 11:09:48 +0000482char LiveDebugValues::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000483
Vikram TV859ad292015-12-16 11:09:48 +0000484char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000485
Matthias Braun1527baa2017-05-25 21:26:32 +0000486INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
Vikram TV859ad292015-12-16 11:09:48 +0000487 false, false)
488
489/// Default construct and initialize the pass.
490LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
491 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
492}
493
494/// Tell the pass manager which passes we depend on and what information we
495/// preserve.
496void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
Matt Arsenaultb1630a12016-06-08 05:18:01 +0000497 AU.setPreservesCFG();
Vikram TV859ad292015-12-16 11:09:48 +0000498 MachineFunctionPass::getAnalysisUsage(AU);
499}
500
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000501/// Erase a variable from the set of open ranges, and additionally erase any
502/// fragments that may overlap it.
503void LiveDebugValues::OpenRangesSet::erase(DebugVariable Var) {
504 // Erasure helper.
505 auto DoErase = [this](DebugVariable VarToErase) {
506 auto It = Vars.find(VarToErase);
507 if (It != Vars.end()) {
508 unsigned ID = It->second;
509 VarLocs.reset(ID);
510 Vars.erase(It);
511 }
512 };
513
514 // Erase the variable/fragment that ends here.
515 DoErase(Var);
516
517 // Extract the fragment. Interpret an empty fragment as one that covers all
518 // possible bits.
519 FragmentInfo ThisFragment = Var.getFragmentDefault();
520
521 // There may be fragments that overlap the designated fragment. Look them up
522 // in the pre-computed overlap map, and erase them too.
523 auto MapIt = OverlappingFragments.find({Var.getVar(), ThisFragment});
524 if (MapIt != OverlappingFragments.end()) {
525 for (auto Fragment : MapIt->second) {
526 LiveDebugValues::OptFragmentInfo FragmentHolder;
527 if (!DebugVariable::isFragmentDefault(Fragment))
528 FragmentHolder = LiveDebugValues::OptFragmentInfo(Fragment);
529 DoErase({Var.getVar(), FragmentHolder, Var.getInlinedAt()});
530 }
531 }
532}
533
Vikram TV859ad292015-12-16 11:09:48 +0000534//===----------------------------------------------------------------------===//
535// Debug Range Extension Implementation
536//===----------------------------------------------------------------------===//
537
Matthias Braun194ded52017-01-28 06:53:55 +0000538#ifndef NDEBUG
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000539void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
540 const VarLocInMBB &V,
541 const VarLocMap &VarLocIDs,
542 const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000543 raw_ostream &Out) const {
Keith Walkerf83a19f2016-09-20 16:04:31 +0000544 Out << '\n' << msg << '\n';
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000545 for (const MachineBasicBlock &BB : MF) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000546 const VarLocSet &L = V.lookup(&BB);
547 if (L.empty())
548 continue;
549 Out << "MBB: " << BB.getNumber() << ":\n";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000550 for (unsigned VLL : L) {
551 const VarLoc &VL = VarLocIDs[VLL];
Adrian Prantl7509d542016-05-26 21:42:47 +0000552 Out << " Var: " << VL.Var.getVar()->getName();
Vikram TV859ad292015-12-16 11:09:48 +0000553 Out << " MI: ";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000554 VL.dump();
Vikram TV859ad292015-12-16 11:09:48 +0000555 }
556 }
557 Out << "\n";
558}
Matthias Braun194ded52017-01-28 06:53:55 +0000559#endif
Vikram TV859ad292015-12-16 11:09:48 +0000560
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000561LiveDebugValues::VarLoc::SpillLoc
562LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000563 assert(MI.hasOneMemOperand() &&
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000564 "Spill instruction does not have exactly one memory operand?");
565 auto MMOI = MI.memoperands_begin();
566 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
567 assert(PVal->kind() == PseudoSourceValue::FixedStack &&
568 "Inconsistent memory operand in spill instruction");
569 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
570 const MachineBasicBlock *MBB = MI.getParent();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000571 unsigned Reg;
572 int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
573 return {Reg, Offset};
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000574}
575
Vikram TV859ad292015-12-16 11:09:48 +0000576/// End all previous ranges related to @MI and start a new range from @MI
577/// if it is a DBG_VALUE instr.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000578void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000579 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000580 VarLocMap &VarLocIDs) {
Vikram TV859ad292015-12-16 11:09:48 +0000581 if (!MI.isDebugValue())
582 return;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000583 const DILocalVariable *Var = MI.getDebugVariable();
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000584 const DIExpression *Expr = MI.getDebugExpression();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000585 const DILocation *DebugLoc = MI.getDebugLoc();
586 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
587 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
Vikram TV859ad292015-12-16 11:09:48 +0000588 "Expected inlined-at fields to agree");
Vikram TV859ad292015-12-16 11:09:48 +0000589
590 // End all previous ranges of Var.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000591 DebugVariable V(Var, Expr, InlinedAt);
Adrian Prantl7509d542016-05-26 21:42:47 +0000592 OpenRanges.erase(V);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000593
594 // Add the VarLoc to OpenRanges from this DBG_VALUE.
Jeremy Morsebcff4172019-06-10 15:23:46 +0000595 unsigned ID;
Djordje Todorovic774eabd2019-06-27 18:12:04 +0000596 if (isDbgValueDescribedByReg(MI) || MI.getOperand(0).isImm() ||
597 MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) {
Jeremy Morsebcff4172019-06-10 15:23:46 +0000598 // Use normal VarLoc constructor for registers and immediates.
Djordje Todorovic774eabd2019-06-27 18:12:04 +0000599 VarLoc VL(MI, LS);
Jeremy Morsebcff4172019-06-10 15:23:46 +0000600 ID = VarLocIDs.insert(VL);
Adrian Prantl7509d542016-05-26 21:42:47 +0000601 OpenRanges.insert(ID, VL.Var);
Jeremy Morsebcff4172019-06-10 15:23:46 +0000602 } else if (MI.hasOneMemOperand()) {
Jeremy Morse8b593482019-08-16 10:04:17 +0000603 llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
Jeremy Morsebcff4172019-06-10 15:23:46 +0000604 } else {
605 // This must be an undefined location. We should leave OpenRanges closed.
606 assert(MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 &&
607 "Unexpected non-undef DBG_VALUE encountered");
Adrian Prantl7509d542016-05-26 21:42:47 +0000608 }
Vikram TV859ad292015-12-16 11:09:48 +0000609}
610
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000611void LiveDebugValues::emitEntryValues(MachineInstr &MI,
612 OpenRangesSet &OpenRanges,
613 VarLocMap &VarLocIDs,
614 TransferMap &Transfers,
615 DebugParamMap &DebugEntryVals,
616 SparseBitVector<> &KillSet) {
617 MachineFunction *MF = MI.getParent()->getParent();
618 for (unsigned ID : KillSet) {
619 if (!VarLocIDs[ID].Var.getVar()->isParameter())
620 continue;
621
622 const MachineInstr *CurrDebugInstr = &VarLocIDs[ID].MI;
623
624 // If parameter's DBG_VALUE is not in the map that means we can't
625 // generate parameter's entry value.
626 if (!DebugEntryVals.count(CurrDebugInstr->getDebugVariable()))
627 continue;
628
629 auto ParamDebugInstr = DebugEntryVals[CurrDebugInstr->getDebugVariable()];
630 DIExpression *NewExpr = DIExpression::prepend(
631 ParamDebugInstr->getDebugExpression(), DIExpression::EntryValue);
632 MachineInstr *EntryValDbgMI =
633 BuildMI(*MF, ParamDebugInstr->getDebugLoc(), ParamDebugInstr->getDesc(),
634 ParamDebugInstr->isIndirectDebugValue(),
635 ParamDebugInstr->getOperand(0).getReg(),
636 ParamDebugInstr->getDebugVariable(), NewExpr);
637
638 if (ParamDebugInstr->isIndirectDebugValue())
639 EntryValDbgMI->getOperand(1).setImm(
640 ParamDebugInstr->getOperand(1).getImm());
641
642 Transfers.push_back({&MI, EntryValDbgMI});
643 VarLoc VL(*EntryValDbgMI, LS);
644 unsigned EntryValLocID = VarLocIDs.insert(VL);
645 OpenRanges.insert(EntryValLocID, VL.Var);
646 }
647}
648
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000649/// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
650/// with \p OldVarID should be deleted form \p OpenRanges and replaced with
651/// new VarLoc. If \p NewReg is different than default zero value then the
652/// new location will be register location created by the copy like instruction,
653/// otherwise it is variable's location on the stack.
654void LiveDebugValues::insertTransferDebugPair(
655 MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000656 VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
657 unsigned NewReg) {
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000658 const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000659 MachineFunction *MF = MI.getParent()->getParent();
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000660 MachineInstr *NewDebugInstr;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000661
Nikola Prica2d0106a2019-06-03 09:48:29 +0000662 auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &DebugInstr,
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000663 &VarLocIDs](VarLoc &VL, MachineInstr *NewDebugInstr) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000664 unsigned LocId = VarLocIDs.insert(VL);
Nikola Prica2d0106a2019-06-03 09:48:29 +0000665
666 // Close this variable's previous location range.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000667 DebugVariable V(*DebugInstr);
Nikola Prica2d0106a2019-06-03 09:48:29 +0000668 OpenRanges.erase(V);
669
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000670 OpenRanges.insert(LocId, VL.Var);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000671 // The newly created DBG_VALUE instruction NewDebugInstr must be inserted
672 // after MI. Keep track of the pairing.
673 TransferDebugPair MIP = {&MI, NewDebugInstr};
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000674 Transfers.push_back(MIP);
675 };
676
677 // End all previous ranges of Var.
678 OpenRanges.erase(VarLocIDs[OldVarID].Var);
679 switch (Kind) {
680 case TransferKind::TransferCopy: {
681 assert(NewReg &&
682 "No register supplied when handling a copy of a debug value");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000683 // Create a DBG_VALUE instruction to describe the Var in its new
684 // register location.
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000685 NewDebugInstr = BuildMI(
686 *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(),
687 DebugInstr->isIndirectDebugValue(), NewReg,
688 DebugInstr->getDebugVariable(), DebugInstr->getDebugExpression());
689 if (DebugInstr->isIndirectDebugValue())
690 NewDebugInstr->getOperand(1).setImm(DebugInstr->getOperand(1).getImm());
691 VarLoc VL(*NewDebugInstr, LS);
692 ProcessVarLoc(VL, NewDebugInstr);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000693 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
Craig Topper78c794a2019-06-02 01:36:48 +0000694 NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
695 /*SkipOpers*/false, /*SkipDebugLoc*/false,
696 /*AddNewLine*/true, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000697 return;
698 }
699 case TransferKind::TransferSpill: {
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000700 // Create a DBG_VALUE instruction to describe the Var in its spilled
701 // location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000702 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000703 auto *SpillExpr = DIExpression::prepend(DebugInstr->getDebugExpression(),
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000704 DIExpression::ApplyOffset,
705 SpillLocation.SpillOffset);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000706 NewDebugInstr = BuildMI(
707 *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), true,
708 SpillLocation.SpillBase, DebugInstr->getDebugVariable(), SpillExpr);
709 VarLoc VL(*NewDebugInstr, SpillLocation.SpillBase,
Jeremy Morse8b593482019-08-16 10:04:17 +0000710 SpillLocation.SpillOffset, LS, *DebugInstr);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000711 ProcessVarLoc(VL, NewDebugInstr);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000712 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
Craig Topper78c794a2019-06-02 01:36:48 +0000713 NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
714 /*SkipOpers*/false, /*SkipDebugLoc*/false,
715 /*AddNewLine*/true, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000716 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000717 }
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000718 case TransferKind::TransferRestore: {
719 assert(NewReg &&
720 "No register supplied when handling a restore of a debug value");
721 MachineFunction *MF = MI.getMF();
722 DIBuilder DIB(*const_cast<Function &>(MF->getFunction()).getParent());
Jeremy Morse8b593482019-08-16 10:04:17 +0000723 // DebugInstr refers to the pre-spill location, therefore we can reuse
724 // its expression.
725 NewDebugInstr = BuildMI(
726 *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), false, NewReg,
727 DebugInstr->getDebugVariable(), DebugInstr->getDebugExpression());
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000728 VarLoc VL(*NewDebugInstr, LS);
729 ProcessVarLoc(VL, NewDebugInstr);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000730 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register restore: ";
Craig Topper78c794a2019-06-02 01:36:48 +0000731 NewDebugInstr->print(dbgs(), /*IsStandalone*/false,
732 /*SkipOpers*/false, /*SkipDebugLoc*/false,
733 /*AddNewLine*/true, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000734 return;
735 }
736 }
737 llvm_unreachable("Invalid transfer kind");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000738}
739
Vikram TV859ad292015-12-16 11:09:48 +0000740/// A definition of a register may mark the end of a range.
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000741void LiveDebugValues::transferRegisterDef(
742 MachineInstr &MI, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
743 TransferMap &Transfers, DebugParamMap &DebugEntryVals) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +0000744 MachineFunction *MF = MI.getMF();
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000745 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
746 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000747 SparseBitVector<> KillSet;
Vikram TV859ad292015-12-16 11:09:48 +0000748 for (const MachineOperand &MO : MI.operands()) {
Adrian Prantlea8880b2017-03-03 01:08:25 +0000749 // Determine whether the operand is a register def. Assume that call
750 // instructions never clobber SP, because some backends (e.g., AArch64)
751 // never list SP in the regmask.
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000752 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000753 Register::isPhysicalRegister(MO.getReg()) &&
Adrian Prantlea8880b2017-03-03 01:08:25 +0000754 !(MI.isCall() && MO.getReg() == SP)) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000755 // Remove ranges of all aliased registers.
756 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
Adrian Prantl7509d542016-05-26 21:42:47 +0000757 for (unsigned ID : OpenRanges.getVarLocs())
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000758 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
759 KillSet.set(ID);
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000760 } else if (MO.isRegMask()) {
761 // Remove ranges of all clobbered registers. Register masks don't usually
762 // list SP as preserved. While the debug info may be off for an
763 // instruction or two around callee-cleanup calls, transferring the
764 // DEBUG_VALUE across the call is still a better user experience.
Adrian Prantl7509d542016-05-26 21:42:47 +0000765 for (unsigned ID : OpenRanges.getVarLocs()) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000766 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
767 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
768 KillSet.set(ID);
769 }
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000770 }
Vikram TV859ad292015-12-16 11:09:48 +0000771 }
Adrian Prantl7509d542016-05-26 21:42:47 +0000772 OpenRanges.erase(KillSet, VarLocIDs);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +0000773
774 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
775 auto &TM = TPC->getTM<TargetMachine>();
776 if (TM.Options.EnableDebugEntryValues)
777 emitEntryValues(MI, OpenRanges, VarLocIDs, Transfers, DebugEntryVals,
778 KillSet);
779 }
Vikram TV859ad292015-12-16 11:09:48 +0000780}
781
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000782/// Decide if @MI is a spill instruction and return true if it is. We use 2
783/// criteria to make this decision:
784/// - Is this instruction a store to a spill slot?
785/// - Is there a register operand that is both used and killed?
786/// TODO: Store optimization can fold spills into other stores (including
787/// other spills). We do not handle this yet (more than one memory operand).
788bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
789 MachineFunction *MF, unsigned &Reg) {
Sander de Smalenc91b27d2018-09-05 08:59:50 +0000790 SmallVector<const MachineMemOperand*, 1> Accesses;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000791
Fangrui Songf78650a2018-07-30 19:41:25 +0000792 // TODO: Handle multiple stores folded into one.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000793 if (!MI.hasOneMemOperand())
794 return false;
795
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000796 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
797 return false; // This is not a spill instruction, since no valid size was
798 // returned from either function.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000799
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000800 auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
801 if (!MO.isReg() || !MO.isUse()) {
802 Reg = 0;
803 return false;
804 }
805 Reg = MO.getReg();
806 return MO.isKill();
807 };
808
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000809 for (const MachineOperand &MO : MI.operands()) {
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000810 // In a spill instruction generated by the InlineSpiller the spilled
811 // register has its kill flag set.
812 if (isKilledReg(MO, Reg))
813 return true;
814 if (Reg != 0) {
815 // Check whether next instruction kills the spilled register.
816 // FIXME: Current solution does not cover search for killed register in
817 // bundles and instructions further down the chain.
818 auto NextI = std::next(MI.getIterator());
819 // Skip next instruction that points to basic block end iterator.
820 if (MI.getParent()->end() == NextI)
821 continue;
822 unsigned RegNext;
823 for (const MachineOperand &MONext : NextI->operands()) {
824 // Return true if we came across the register from the
825 // previous spill instruction that is killed in NextI.
826 if (isKilledReg(MONext, RegNext) && RegNext == Reg)
827 return true;
828 }
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000829 }
830 }
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000831 // Return false if we didn't find spilled register.
832 return false;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000833}
834
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000835Optional<LiveDebugValues::VarLoc::SpillLoc>
836LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
837 MachineFunction *MF, unsigned &Reg) {
838 if (!MI.hasOneMemOperand())
839 return None;
840
841 // FIXME: Handle folded restore instructions with more than one memory
842 // operand.
843 if (MI.getRestoreSize(TII)) {
844 Reg = MI.getOperand(0).getReg();
845 return extractSpillBaseRegAndOffset(MI);
846 }
847 return None;
848}
849
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000850/// A spilled register may indicate that we have to end the current range of
851/// a variable and create a new one for the spill location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000852/// A restored register may indicate the reverse situation.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000853/// We don't want to insert any instructions in process(), so we just create
854/// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000855/// It will be inserted into the BB when we're done iterating over the
856/// instructions.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000857void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
858 OpenRangesSet &OpenRanges,
859 VarLocMap &VarLocIDs,
860 TransferMap &Transfers) {
Wolfgang Piebfacd0522019-01-30 20:37:14 +0000861 MachineFunction *MF = MI.getMF();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000862 TransferKind TKind;
863 unsigned Reg;
864 Optional<VarLoc::SpillLoc> Loc;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000865
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000866 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
867
868 if (isSpillInstruction(MI, MF, Reg)) {
869 TKind = TransferKind::TransferSpill;
870 LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
871 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
872 << "\n");
873 } else {
874 if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
875 return;
876 TKind = TransferKind::TransferRestore;
877 LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
878 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
879 << "\n");
880 }
881 // Check if the register or spill location is the location of a debug value.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000882 for (unsigned ID : OpenRanges.getVarLocs()) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000883 if (TKind == TransferKind::TransferSpill &&
Jeremy Morse8b593482019-08-16 10:04:17 +0000884 VarLocIDs[ID].isDescribedByReg() == Reg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000885 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
886 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000887 } else if (TKind == TransferKind::TransferRestore &&
Jeremy Morseca0e4b32019-08-29 11:20:54 +0000888 VarLocIDs[ID].Kind == VarLoc::SpillLocKind &&
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000889 VarLocIDs[ID].Loc.SpillLocation == *Loc) {
890 LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
891 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
892 } else
893 continue;
894 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
895 Reg);
896 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000897 }
898}
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000899
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000900/// If \p MI is a register copy instruction, that copies a previously tracked
901/// value from one register to another register that is callee saved, we
902/// create new DBG_VALUE instruction described with copy destination register.
903void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
904 OpenRangesSet &OpenRanges,
905 VarLocMap &VarLocIDs,
906 TransferMap &Transfers) {
907 const MachineOperand *SrcRegOp, *DestRegOp;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000908
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000909 if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
910 !DestRegOp->isDef())
911 return;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000912
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000913 auto isCalleSavedReg = [&](unsigned Reg) {
914 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
915 if (CalleeSavedRegs.test(*RAI))
916 return true;
917 return false;
918 };
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000919
Daniel Sanders0c476112019-08-15 19:22:08 +0000920 Register SrcReg = SrcRegOp->getReg();
921 Register DestReg = DestRegOp->getReg();
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000922
923 // We want to recognize instructions where destination register is callee
924 // saved register. If register that could be clobbered by the call is
925 // included, there would be a great chance that it is going to be clobbered
926 // soon. It is more likely that previous register location, which is callee
927 // saved, is going to stay unclobbered longer, even if it is killed.
928 if (!isCalleSavedReg(DestReg))
929 return;
930
931 for (unsigned ID : OpenRanges.getVarLocs()) {
932 if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
933 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000934 TransferKind::TransferCopy, DestReg);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000935 return;
936 }
937 }
938}
939
Vikram TV859ad292015-12-16 11:09:48 +0000940/// Terminate all open ranges at the end of the current basic block.
Jeremy Morse67443c32019-08-21 09:22:31 +0000941bool LiveDebugValues::transferTerminator(MachineBasicBlock *CurMBB,
942 OpenRangesSet &OpenRanges,
943 VarLocInMBB &OutLocs,
944 const VarLocMap &VarLocIDs) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000945 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000946
947 if (OpenRanges.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000948 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000949
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000950 LLVM_DEBUG(for (unsigned ID
951 : OpenRanges.getVarLocs()) {
952 // Copy OpenRanges to OutLocs, if not already present.
Vedant Kumar9b558382018-10-05 21:44:00 +0000953 dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000954 VarLocIDs[ID].dump();
955 });
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000956 VarLocSet &VLS = OutLocs[CurMBB];
Jeremy Morse0ae54982019-08-23 16:33:42 +0000957 Changed = VLS != OpenRanges.getVarLocs();
Nikola Prica2d0106a2019-06-03 09:48:29 +0000958 // New OutLocs set may be different due to spill, restore or register
959 // copy instruction processing.
960 if (Changed)
961 VLS = OpenRanges.getVarLocs();
Vikram TV859ad292015-12-16 11:09:48 +0000962 OpenRanges.clear();
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000963 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000964}
965
Jeremy Morsebf2b2f02019-06-13 12:51:57 +0000966/// Accumulate a mapping between each DILocalVariable fragment and other
967/// fragments of that DILocalVariable which overlap. This reduces work during
968/// the data-flow stage from "Find any overlapping fragments" to "Check if the
969/// known-to-overlap fragments are present".
970/// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
971/// fragment usage.
972/// \param SeenFragments Map from DILocalVariable to all fragments of that
973/// Variable which are known to exist.
974/// \param OverlappingFragments The overlap map being constructed, from one
975/// Var/Fragment pair to a vector of fragments known to overlap.
976void LiveDebugValues::accumulateFragmentMap(MachineInstr &MI,
977 VarToFragments &SeenFragments,
978 OverlapMap &OverlappingFragments) {
979 DebugVariable MIVar(MI);
980 FragmentInfo ThisFragment = MIVar.getFragmentDefault();
981
982 // If this is the first sighting of this variable, then we are guaranteed
983 // there are currently no overlapping fragments either. Initialize the set
984 // of seen fragments, record no overlaps for the current one, and return.
985 auto SeenIt = SeenFragments.find(MIVar.getVar());
986 if (SeenIt == SeenFragments.end()) {
987 SmallSet<FragmentInfo, 4> OneFragment;
988 OneFragment.insert(ThisFragment);
989 SeenFragments.insert({MIVar.getVar(), OneFragment});
990
991 OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
992 return;
993 }
994
995 // If this particular Variable/Fragment pair already exists in the overlap
996 // map, it has already been accounted for.
997 auto IsInOLapMap =
998 OverlappingFragments.insert({{MIVar.getVar(), ThisFragment}, {}});
999 if (!IsInOLapMap.second)
1000 return;
1001
1002 auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1003 auto &AllSeenFragments = SeenIt->second;
1004
1005 // Otherwise, examine all other seen fragments for this variable, with "this"
1006 // fragment being a previously unseen fragment. Record any pair of
1007 // overlapping fragments.
1008 for (auto &ASeenFragment : AllSeenFragments) {
1009 // Does this previously seen fragment overlap?
1010 if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1011 // Yes: Mark the current fragment as being overlapped.
1012 ThisFragmentsOverlaps.push_back(ASeenFragment);
1013 // Mark the previously seen fragment as being overlapped by the current
1014 // one.
1015 auto ASeenFragmentsOverlaps =
1016 OverlappingFragments.find({MIVar.getVar(), ASeenFragment});
1017 assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
1018 "Previously seen var fragment has no vector of overlaps");
1019 ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1020 }
1021 }
1022
1023 AllSeenFragments.insert(ThisFragment);
1024}
1025
Vikram TV859ad292015-12-16 11:09:48 +00001026/// This routine creates OpenRanges and OutLocs.
Jeremy Morse67443c32019-08-21 09:22:31 +00001027void LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001028 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001029 TransferMap &Transfers,
1030 DebugParamMap &DebugEntryVals,
Jeremy Morsed2cd9c22019-06-13 13:11:57 +00001031 OverlapMap &OverlapFragments,
1032 VarToFragments &SeenFragments) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001033 transferDebugValue(MI, OpenRanges, VarLocIDs);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001034 transferRegisterDef(MI, OpenRanges, VarLocIDs, Transfers,
1035 DebugEntryVals);
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001036 transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
1037 transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
Vikram TV859ad292015-12-16 11:09:48 +00001038}
1039
1040/// This routine joins the analysis results of all incoming edges in @MBB by
1041/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1042/// source variable in all the predecessors of @MBB reside in the same location.
Vedant Kumar8c466682018-10-05 21:44:15 +00001043bool LiveDebugValues::join(
1044 MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1045 const VarLocMap &VarLocIDs,
1046 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
Jeremy Morse67443c32019-08-21 09:22:31 +00001047 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks,
1048 VarLocInMBB &PendingInLocs) {
Vedant Kumar9b558382018-10-05 21:44:00 +00001049 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001050 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +00001051
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001052 VarLocSet InLocsT; // Temporary incoming locations.
Vikram TV859ad292015-12-16 11:09:48 +00001053
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001054 // For all predecessors of this MBB, find the set of VarLocs that
1055 // can be joined.
Keith Walker83ebef52016-09-27 16:46:07 +00001056 int NumVisited = 0;
Vikram TV859ad292015-12-16 11:09:48 +00001057 for (auto p : MBB.predecessors()) {
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001058 // Ignore backedges if we have not visited the predecessor yet. As the
1059 // predecessor hasn't yet had locations propagated into it, most locations
1060 // will not yet be valid, so treat them as all being uninitialized and
1061 // potentially valid. If a location guessed to be correct here is
1062 // invalidated later, we will remove it when we revisit this block.
Vedant Kumar9b558382018-10-05 21:44:00 +00001063 if (!Visited.count(p)) {
1064 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
1065 << "\n");
Keith Walker83ebef52016-09-27 16:46:07 +00001066 continue;
Vedant Kumar9b558382018-10-05 21:44:00 +00001067 }
Vikram TV859ad292015-12-16 11:09:48 +00001068 auto OL = OutLocs.find(p);
1069 // Join is null in case of empty OutLocs from any of the pred.
1070 if (OL == OutLocs.end())
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001071 return false;
Vikram TV859ad292015-12-16 11:09:48 +00001072
Keith Walker83ebef52016-09-27 16:46:07 +00001073 // Just copy over the Out locs to incoming locs for the first visited
1074 // predecessor, and for all other predecessors join the Out locs.
1075 if (!NumVisited)
Vikram TV859ad292015-12-16 11:09:48 +00001076 InLocsT = OL->second;
Keith Walker83ebef52016-09-27 16:46:07 +00001077 else
1078 InLocsT &= OL->second;
Vedant Kumar9b558382018-10-05 21:44:00 +00001079
1080 LLVM_DEBUG({
1081 if (!InLocsT.empty()) {
1082 for (auto ID : InLocsT)
1083 dbgs() << " gathered candidate incoming var: "
1084 << VarLocIDs[ID].Var.getVar()->getName() << "\n";
1085 }
1086 });
1087
Keith Walker83ebef52016-09-27 16:46:07 +00001088 NumVisited++;
Vikram TV859ad292015-12-16 11:09:48 +00001089 }
1090
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001091 // Filter out DBG_VALUES that are out of scope.
1092 VarLocSet KillSet;
Vedant Kumar8c466682018-10-05 21:44:15 +00001093 bool IsArtificial = ArtificialBlocks.count(&MBB);
1094 if (!IsArtificial) {
1095 for (auto ID : InLocsT) {
1096 if (!VarLocIDs[ID].dominates(MBB)) {
1097 KillSet.set(ID);
1098 LLVM_DEBUG({
1099 auto Name = VarLocIDs[ID].Var.getVar()->getName();
1100 dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
1101 });
1102 }
Vedant Kumar9b558382018-10-05 21:44:00 +00001103 }
1104 }
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001105 InLocsT.intersectWithComplement(KillSet);
1106
Keith Walker83ebef52016-09-27 16:46:07 +00001107 // As we are processing blocks in reverse post-order we
1108 // should have processed at least one predecessor, unless it
1109 // is the entry block which has no predecessor.
1110 assert((NumVisited || MBB.pred_empty()) &&
1111 "Should have processed at least one predecessor");
Vikram TV859ad292015-12-16 11:09:48 +00001112
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001113 VarLocSet &ILS = InLocs[&MBB];
Jeremy Morse67443c32019-08-21 09:22:31 +00001114 VarLocSet &Pending = PendingInLocs[&MBB];
Vikram TV859ad292015-12-16 11:09:48 +00001115
Jeremy Morse67443c32019-08-21 09:22:31 +00001116 // New locations will have DBG_VALUE insts inserted at the start of the
1117 // block, after location propagation has finished. Record the insertions
1118 // that we need to perform in the Pending set.
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001119 VarLocSet Diff = InLocsT;
1120 Diff.intersectWithComplement(ILS);
1121 for (auto ID : Diff) {
Jeremy Morse67443c32019-08-21 09:22:31 +00001122 Pending.set(ID);
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001123 ILS.set(ID);
1124 ++NumInserted;
1125 Changed = true;
Vikram TV859ad292015-12-16 11:09:48 +00001126 }
Jeremy Morse0ae54982019-08-23 16:33:42 +00001127
1128 // We may have lost locations by learning about a predecessor that either
1129 // loses or moves a variable. Find any locations in ILS that are not in the
1130 // new in-locations, and delete those.
1131 VarLocSet Removed = ILS;
1132 Removed.intersectWithComplement(InLocsT);
1133 for (auto ID : Removed) {
1134 Pending.reset(ID);
1135 ILS.reset(ID);
1136 ++NumRemoved;
1137 Changed = true;
1138 }
1139
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001140 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +00001141}
1142
Jeremy Morse67443c32019-08-21 09:22:31 +00001143void LiveDebugValues::flushPendingLocs(VarLocInMBB &PendingInLocs,
1144 VarLocMap &VarLocIDs) {
1145 // PendingInLocs records all locations propagated into blocks, which have
1146 // not had DBG_VALUE insts created. Go through and create those insts now.
1147 for (auto &Iter : PendingInLocs) {
1148 // Map is keyed on a constant pointer, unwrap it so we can insert insts.
1149 auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
1150 VarLocSet &Pending = Iter.second;
1151
1152 for (unsigned ID : Pending) {
1153 // The ID location is live-in to MBB -- work out what kind of machine
1154 // location it is and create a DBG_VALUE.
1155 const VarLoc &DiffIt = VarLocIDs[ID];
1156 const MachineInstr *DebugInstr = &DiffIt.MI;
1157 MachineInstr *MI = nullptr;
1158
1159 if (DiffIt.isConstant()) {
1160 MachineOperand MO(DebugInstr->getOperand(0));
1161 MI = BuildMI(MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
1162 DebugInstr->getDesc(), false, MO,
1163 DebugInstr->getDebugVariable(),
1164 DebugInstr->getDebugExpression());
1165 } else {
1166 auto *DebugExpr = DebugInstr->getDebugExpression();
1167 Register Reg = DebugInstr->getOperand(0).getReg();
1168 bool IsIndirect = DebugInstr->isIndirectDebugValue();
1169
1170 if (DiffIt.Kind == VarLoc::SpillLocKind) {
1171 // This is is a spilt location; DebugInstr refers to the unspilt
1172 // location. We need to rebuild the spilt location expression and
1173 // point the DBG_VALUE at the frame register.
1174 DebugExpr = DIExpression::prepend(
1175 DebugInstr->getDebugExpression(), DIExpression::ApplyOffset,
1176 DiffIt.Loc.SpillLocation.SpillOffset);
1177 Reg = TRI->getFrameRegister(*DebugInstr->getMF());
1178 IsIndirect = true;
1179 }
1180
1181 MI = BuildMI(MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
1182 DebugInstr->getDesc(), IsIndirect, Reg,
1183 DebugInstr->getDebugVariable(), DebugExpr);
1184 }
Jeremy Morsec8c5f2a2019-09-04 10:18:03 +00001185 (void)MI;
Jeremy Morse67443c32019-08-21 09:22:31 +00001186 LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
1187 }
1188 }
1189}
1190
Vikram TV859ad292015-12-16 11:09:48 +00001191/// Calculate the liveness information for the given machine function and
1192/// extend ranges across basic blocks.
1193bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001194 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
Vikram TV859ad292015-12-16 11:09:48 +00001195
1196 bool Changed = false;
Daniel Berlinca4d93a2016-01-10 03:25:42 +00001197 bool OLChanged = false;
1198 bool MBBJoined = false;
Vikram TV859ad292015-12-16 11:09:48 +00001199
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001200 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
1201 OverlapMap OverlapFragments; // Map of overlapping variable fragments
1202 OpenRangesSet OpenRanges(OverlapFragments);
1203 // Ranges that are open until end of bb.
1204 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
1205 VarLocInMBB InLocs; // Ranges that are incoming after joining.
1206 TransferMap Transfers; // DBG_VALUEs associated with spills.
Jeremy Morse67443c32019-08-21 09:22:31 +00001207 VarLocInMBB PendingInLocs; // Ranges that are incoming after joining, but
1208 // that we have deferred creating DBG_VALUE insts
1209 // for immediately.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001210
1211 VarToFragments SeenFragments;
Vikram TV859ad292015-12-16 11:09:48 +00001212
Vedant Kumar8c466682018-10-05 21:44:15 +00001213 // Blocks which are artificial, i.e. blocks which exclusively contain
1214 // instructions without locations, or with line 0 locations.
1215 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1216
Daniel Berlin72560592016-01-10 18:08:32 +00001217 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1218 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1219 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001220 std::greater<unsigned int>>
1221 Worklist;
Daniel Berlin72560592016-01-10 18:08:32 +00001222 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001223 std::greater<unsigned int>>
1224 Pending;
1225
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001226 // Besides parameter's modification, check whether a DBG_VALUE is inlined
1227 // in order to deduce whether the variable that it tracks comes from
1228 // a different function. If that is the case we can't track its entry value.
1229 auto IsUnmodifiedFuncParam = [&](const MachineInstr &MI) {
1230 auto *DIVar = MI.getDebugVariable();
1231 return DIVar->isParameter() && DIVar->isNotModified() &&
1232 !MI.getDebugLoc()->getInlinedAt();
1233 };
1234
1235 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
1236 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Daniel Sanders0c476112019-08-15 19:22:08 +00001237 Register FP = TRI->getFrameRegister(MF);
Djordje Todorovic12aca5d2019-07-09 08:36:34 +00001238 auto IsRegOtherThanSPAndFP = [&](const MachineOperand &Op) -> bool {
1239 return Op.isReg() && Op.getReg() != SP && Op.getReg() != FP;
1240 };
1241
1242 // Working set of currently collected debug variables mapped to DBG_VALUEs
1243 // representing candidates for production of debug entry values.
1244 DebugParamMap DebugEntryVals;
1245
1246 MachineBasicBlock &First_MBB = *(MF.begin());
1247 // Only in the case of entry MBB collect DBG_VALUEs representing
1248 // function parameters in order to generate debug entry values for them.
1249 // Currently, we generate debug entry values only for parameters that are
1250 // unmodified throughout the function and located in a register.
1251 // TODO: Add support for parameters that are described as fragments.
1252 // TODO: Add support for modified arguments that can be expressed
1253 // by using its entry value.
1254 // TODO: Add support for local variables that are expressed in terms of
1255 // parameters entry values.
1256 for (auto &MI : First_MBB)
1257 if (MI.isDebugValue() && IsUnmodifiedFuncParam(MI) &&
1258 !MI.isIndirectDebugValue() && IsRegOtherThanSPAndFP(MI.getOperand(0)) &&
1259 !DebugEntryVals.count(MI.getDebugVariable()) &&
1260 !MI.getDebugExpression()->isFragment())
1261 DebugEntryVals[MI.getDebugVariable()] = &MI;
1262
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001263 // Initialize per-block structures and scan for fragment overlaps.
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001264 for (auto &MBB : MF) {
Jeremy Morse67443c32019-08-21 09:22:31 +00001265 PendingInLocs[&MBB] = VarLocSet();
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001266
1267 for (auto &MI : MBB) {
1268 if (MI.isDebugValue())
1269 accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
1270 }
Jeremy Morsebf2b2f02019-06-13 12:51:57 +00001271 }
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001272
Vedant Kumar8c466682018-10-05 21:44:15 +00001273 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
1274 if (const DebugLoc &DL = MI.getDebugLoc())
1275 return DL.getLine() != 0;
1276 return false;
1277 };
1278 for (auto &MBB : MF)
1279 if (none_of(MBB.instrs(), hasNonArtificialLocation))
1280 ArtificialBlocks.insert(&MBB);
1281
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001282 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1283 "OutLocs after initialization", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001284
Daniel Berlin72560592016-01-10 18:08:32 +00001285 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1286 unsigned int RPONumber = 0;
1287 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
1288 OrderToBB[RPONumber] = *RI;
1289 BBToOrder[*RI] = RPONumber;
1290 Worklist.push(RPONumber);
1291 ++RPONumber;
1292 }
Daniel Berlin72560592016-01-10 18:08:32 +00001293 // This is a standard "union of predecessor outs" dataflow problem.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001294 // To solve it, we perform join() and process() using the two worklist method
Daniel Berlin72560592016-01-10 18:08:32 +00001295 // until the ranges converge.
1296 // Ranges have converged when both worklists are empty.
Keith Walker83ebef52016-09-27 16:46:07 +00001297 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
Daniel Berlin72560592016-01-10 18:08:32 +00001298 while (!Worklist.empty() || !Pending.empty()) {
1299 // We track what is on the pending worklist to avoid inserting the same
1300 // thing twice. We could avoid this with a custom priority queue, but this
1301 // is probably not worth it.
1302 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001303 LLVM_DEBUG(dbgs() << "Processing Worklist\n");
Daniel Berlin72560592016-01-10 18:08:32 +00001304 while (!Worklist.empty()) {
1305 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
1306 Worklist.pop();
Jeremy Morse67443c32019-08-21 09:22:31 +00001307 MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
1308 ArtificialBlocks, PendingInLocs);
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001309 MBBJoined |= Visited.insert(MBB).second;
Daniel Berlin72560592016-01-10 18:08:32 +00001310 if (MBBJoined) {
1311 MBBJoined = false;
1312 Changed = true;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001313 // Now that we have started to extend ranges across BBs we need to
1314 // examine spill instructions to see whether they spill registers that
1315 // correspond to user variables.
Jeremy Morse67443c32019-08-21 09:22:31 +00001316 // First load any pending inlocs.
1317 OpenRanges.insertFromLocSet(PendingInLocs[MBB], VarLocIDs);
Daniel Berlin72560592016-01-10 18:08:32 +00001318 for (auto &MI : *MBB)
Jeremy Morsed2cd9c22019-06-13 13:11:57 +00001319 process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
Jeremy Morse313d2ce2019-08-29 10:53:29 +00001320 DebugEntryVals, OverlapFragments, SeenFragments);
Jeremy Morse67443c32019-08-21 09:22:31 +00001321 OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001322
1323 // Add any DBG_VALUE instructions necessitated by spills.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001324 for (auto &TR : Transfers)
David Stenbergb35d4692019-08-30 09:06:50 +00001325 MBB->insertAfterBundle(TR.TransferInst->getIterator(), TR.DebugInst);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001326 Transfers.clear();
Adrian Prantl6ee02c72016-05-25 22:21:12 +00001327
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001328 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1329 "OutLocs after propagating", dbgs()));
1330 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
1331 "InLocs after propagating", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001332
Daniel Berlin72560592016-01-10 18:08:32 +00001333 if (OLChanged) {
1334 OLChanged = false;
1335 for (auto s : MBB->successors())
Benjamin Kramer4dea8f52016-06-17 18:59:41 +00001336 if (OnPending.insert(s).second) {
Daniel Berlin72560592016-01-10 18:08:32 +00001337 Pending.push(BBToOrder[s]);
1338 }
1339 }
Vikram TV859ad292015-12-16 11:09:48 +00001340 }
1341 }
Daniel Berlin72560592016-01-10 18:08:32 +00001342 Worklist.swap(Pending);
1343 // At this point, pending must be empty, since it was just the empty
1344 // worklist
1345 assert(Pending.empty() && "Pending should be empty");
Vikram TV859ad292015-12-16 11:09:48 +00001346 }
Daniel Berlin72560592016-01-10 18:08:32 +00001347
Jeremy Morse67443c32019-08-21 09:22:31 +00001348 // Deferred inlocs will not have had any DBG_VALUE insts created; do
1349 // that now.
1350 flushPendingLocs(PendingInLocs, VarLocIDs);
1351
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001352 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
1353 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +00001354 return Changed;
1355}
1356
1357bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001358 if (!MF.getFunction().getSubprogram())
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001359 // LiveDebugValues will already have removed all DBG_VALUEs.
1360 return false;
1361
Wolfgang Piebe018bbd2017-07-19 19:36:40 +00001362 // Skip functions from NoDebug compilation units.
Matthias Braunf1caa282017-12-15 22:22:58 +00001363 if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
Wolfgang Piebe018bbd2017-07-19 19:36:40 +00001364 DICompileUnit::NoDebug)
1365 return false;
1366
Vikram TV859ad292015-12-16 11:09:48 +00001367 TRI = MF.getSubtarget().getRegisterInfo();
1368 TII = MF.getSubtarget().getInstrInfo();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +00001369 TFI = MF.getSubtarget().getFrameLowering();
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +00001370 TFI->determineCalleeSaves(MF, CalleeSavedRegs,
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001371 std::make_unique<RegScavenger>().get());
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001372 LS.initialize(MF);
Vikram TV859ad292015-12-16 11:09:48 +00001373
Adrian Prantl7f5866c2016-09-28 17:51:14 +00001374 bool Changed = ExtendRanges(MF);
Vikram TV859ad292015-12-16 11:09:48 +00001375 return Changed;
1376}