blob: 2ac3fe20fffb2ebc09f1e7c4342b0d46a1150644 [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
10/// information by inserting additional DBG_VALUE instructions into the machine
11/// instruction stream. The pass internally builds debug location liveness
12/// ranges to determine the points where additional DBG_VALUEs need to be
13/// inserted.
14///
15/// This is a separate pass from DbgValueHistoryCalculator to facilitate
16/// testing and improve modularity.
17///
18//===----------------------------------------------------------------------===//
19
Eugene Zelenko5df3d892017-08-24 21:21:39 +000020#include "llvm/ADT/DenseMap.h"
Daniel Berlin72560592016-01-10 18:08:32 +000021#include "llvm/ADT/PostOrderIterator.h"
22#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000023#include "llvm/ADT/SmallVector.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000024#include "llvm/ADT/SparseBitVector.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000025#include "llvm/ADT/Statistic.h"
Adrian Prantl6ee02c72016-05-25 22:21:12 +000026#include "llvm/ADT/UniqueVector.h"
Adrian Prantl7f5866c2016-09-28 17:51:14 +000027#include "llvm/CodeGen/LexicalScopes.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000028#include "llvm/CodeGen/MachineBasicBlock.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
Vikram TV859ad292015-12-16 11:09:48 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000032#include "llvm/CodeGen/MachineInstr.h"
Vikram TV859ad292015-12-16 11:09:48 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000034#include "llvm/CodeGen/MachineMemOperand.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000035#include "llvm/CodeGen/MachineOperand.h"
36#include "llvm/CodeGen/PseudoSourceValue.h"
Wolfgang Pieb90d856c2019-02-04 20:42:45 +000037#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000038#include "llvm/CodeGen/TargetFrameLowering.h"
39#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetLowering.h"
41#include "llvm/CodeGen/TargetRegisterInfo.h"
42#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000043#include "llvm/Config/llvm-config.h"
Wolfgang Pieb90d856c2019-02-04 20:42:45 +000044#include "llvm/IR/DIBuilder.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000045#include "llvm/IR/DebugInfoMetadata.h"
46#include "llvm/IR/DebugLoc.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/Module.h"
49#include "llvm/MC/MCRegisterInfo.h"
50#include "llvm/Pass.h"
51#include "llvm/Support/Casting.h"
52#include "llvm/Support/Compiler.h"
Vikram TV859ad292015-12-16 11:09:48 +000053#include "llvm/Support/Debug.h"
54#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000055#include <algorithm>
56#include <cassert>
57#include <cstdint>
58#include <functional>
Mehdi Aminib550cb12016-04-18 09:17:29 +000059#include <queue>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000060#include <utility>
61#include <vector>
Vikram TV859ad292015-12-16 11:09:48 +000062
63using namespace llvm;
64
Matthias Braun1527baa2017-05-25 21:26:32 +000065#define DEBUG_TYPE "livedebugvalues"
Vikram TV859ad292015-12-16 11:09:48 +000066
67STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
68
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000069// If @MI is a DBG_VALUE with debug value described by a defined
Adrian Prantl6ee02c72016-05-25 22:21:12 +000070// register, returns the number of this register. In the other case, returns 0.
Adrian Prantl00698732016-05-25 22:37:29 +000071static unsigned isDbgValueDescribedByReg(const MachineInstr &MI) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +000072 assert(MI.isDebugValue() && "expected a DBG_VALUE");
73 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
74 // If location of variable is described using a register (directly
75 // or indirectly), this register is always a first operand.
76 return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
77}
78
Eugene Zelenko5df3d892017-08-24 21:21:39 +000079namespace {
Vikram TV859ad292015-12-16 11:09:48 +000080
Eugene Zelenko5df3d892017-08-24 21:21:39 +000081class LiveDebugValues : public MachineFunctionPass {
Vikram TV859ad292015-12-16 11:09:48 +000082private:
83 const TargetRegisterInfo *TRI;
84 const TargetInstrInfo *TII;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +000085 const TargetFrameLowering *TFI;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +000086 BitVector CalleeSavedRegs;
Adrian Prantl7f5866c2016-09-28 17:51:14 +000087 LexicalScopes LS;
88
Wolfgang Pieb90d856c2019-02-04 20:42:45 +000089 enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
90
Adrian Prantl7f5866c2016-09-28 17:51:14 +000091 /// Keeps track of lexical scopes associated with a user value's source
92 /// location.
93 class UserValueScopes {
94 DebugLoc DL;
95 LexicalScopes &LS;
96 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
97
98 public:
99 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
100
101 /// Return true if current scope dominates at least one machine
102 /// instruction in a given machine basic block.
103 bool dominates(MachineBasicBlock *MBB) {
104 if (LBlocks.empty())
105 LS.getMachineBasicBlocks(DL, LBlocks);
106 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
107 }
108 };
Vikram TV859ad292015-12-16 11:09:48 +0000109
Adrian Prantl7509d542016-05-26 21:42:47 +0000110 /// Based on std::pair so it can be used as an index into a DenseMap.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000111 using DebugVariableBase =
112 std::pair<const DILocalVariable *, const DILocation *>;
Vikram TV859ad292015-12-16 11:09:48 +0000113 /// A potentially inlined instance of a variable.
Adrian Prantl7509d542016-05-26 21:42:47 +0000114 struct DebugVariable : public DebugVariableBase {
115 DebugVariable(const DILocalVariable *Var, const DILocation *InlinedAt)
116 : DebugVariableBase(Var, InlinedAt) {}
Vikram TV859ad292015-12-16 11:09:48 +0000117
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000118 const DILocalVariable *getVar() const { return this->first; }
119 const DILocation *getInlinedAt() const { return this->second; }
Vikram TV859ad292015-12-16 11:09:48 +0000120
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000121 bool operator<(const DebugVariable &DV) const {
Adrian Prantl7509d542016-05-26 21:42:47 +0000122 if (getVar() == DV.getVar())
123 return getInlinedAt() < DV.getInlinedAt();
124 return getVar() < DV.getVar();
Vikram TV859ad292015-12-16 11:09:48 +0000125 }
126 };
127
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000128 /// A pair of debug variable and value location.
Vikram TV859ad292015-12-16 11:09:48 +0000129 struct VarLoc {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000130 // The location at which a spilled variable resides. It consists of a
131 // register and an offset.
132 struct SpillLoc {
133 unsigned SpillBase;
134 int SpillOffset;
135 bool operator==(const SpillLoc &Other) const {
136 return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
137 }
138 };
139
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000140 const DebugVariable Var;
141 const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000142 mutable UserValueScopes UVS;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000143 enum VarLocKind {
144 InvalidKind = 0,
145 RegisterKind,
Eric Christopherc93f56d2019-05-08 23:54:03 +0000146 SpillLocKind
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000147 } Kind = InvalidKind;
Vikram TV859ad292015-12-16 11:09:48 +0000148
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000149 /// The value location. Stored separately to avoid repeatedly
150 /// extracting it from MI.
151 union {
Adrian Prantl359846f2017-07-28 23:25:51 +0000152 uint64_t RegNo;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000153 SpillLoc SpillLocation;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000154 uint64_t Hash;
155 } Loc;
156
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000157 VarLoc(const MachineInstr &MI, LexicalScopes &LS)
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000158 : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000159 UVS(MI.getDebugLoc(), LS) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000160 static_assert((sizeof(Loc) == sizeof(uint64_t)),
161 "hash does not cover all members of Loc");
162 assert(MI.isDebugValue() && "not a DBG_VALUE");
163 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
Adrian Prantl00698732016-05-25 22:37:29 +0000164 if (int RegNo = isDbgValueDescribedByReg(MI)) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000165 Kind = RegisterKind;
Adrian Prantl359846f2017-07-28 23:25:51 +0000166 Loc.RegNo = RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000167 }
168 }
169
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000170 /// The constructor for spill locations.
171 VarLoc(const MachineInstr &MI, unsigned SpillBase, int SpillOffset,
172 LexicalScopes &LS)
173 : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
174 UVS(MI.getDebugLoc(), LS) {
175 assert(MI.isDebugValue() && "not a DBG_VALUE");
176 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
177 Kind = SpillLocKind;
178 Loc.SpillLocation = {SpillBase, SpillOffset};
179 }
180
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000181 /// If this variable is described by a register, return it,
182 /// otherwise return 0.
183 unsigned isDescribedByReg() const {
184 if (Kind == RegisterKind)
Adrian Prantl359846f2017-07-28 23:25:51 +0000185 return Loc.RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000186 return 0;
187 }
188
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000189 /// Determine whether the lexical scope of this value's debug location
190 /// dominates MBB.
191 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
192
Aaron Ballman615eb472017-10-15 14:32:27 +0000193#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun194ded52017-01-28 06:53:55 +0000194 LLVM_DUMP_METHOD void dump() const { MI.dump(); }
195#endif
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000196
197 bool operator==(const VarLoc &Other) const {
Eric Christopherc93f56d2019-05-08 23:54:03 +0000198 return Var == Other.Var && Loc.Hash == Other.Loc.Hash;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000199 }
200
Adrian Prantl7509d542016-05-26 21:42:47 +0000201 /// This operator guarantees that VarLocs are sorted by Variable first.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000202 bool operator<(const VarLoc &Other) const {
203 if (Var == Other.Var)
204 return Loc.Hash < Other.Loc.Hash;
205 return Var < Other.Var;
206 }
Vikram TV859ad292015-12-16 11:09:48 +0000207 };
208
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000209 using VarLocMap = UniqueVector<VarLoc>;
210 using VarLocSet = SparseBitVector<>;
211 using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000212 struct TransferDebugPair {
213 MachineInstr *TransferInst;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000214 MachineInstr *DebugInst;
215 };
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000216 using TransferMap = SmallVector<TransferDebugPair, 4>;
Vikram TV859ad292015-12-16 11:09:48 +0000217
Adrian Prantl7509d542016-05-26 21:42:47 +0000218 /// This holds the working set of currently open ranges. For fast
219 /// access, this is done both as a set of VarLocIDs, and a map of
220 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
221 /// previous open ranges for the same variable.
222 class OpenRangesSet {
223 VarLocSet VarLocs;
224 SmallDenseMap<DebugVariableBase, unsigned, 8> Vars;
225
226 public:
227 const VarLocSet &getVarLocs() const { return VarLocs; }
228
229 /// Terminate all open ranges for Var by removing it from the set.
230 void erase(DebugVariable Var) {
231 auto It = Vars.find(Var);
232 if (It != Vars.end()) {
233 unsigned ID = It->second;
234 VarLocs.reset(ID);
235 Vars.erase(It);
236 }
237 }
238
239 /// Terminate all open ranges listed in \c KillSet by removing
240 /// them from the set.
241 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
242 VarLocs.intersectWithComplement(KillSet);
243 for (unsigned ID : KillSet)
244 Vars.erase(VarLocIDs[ID].Var);
245 }
246
247 /// Insert a new range into the set.
248 void insert(unsigned VarLocID, DebugVariableBase Var) {
249 VarLocs.set(VarLocID);
250 Vars.insert({Var, VarLocID});
251 }
252
253 /// Empty the set.
254 void clear() {
255 VarLocs.clear();
256 Vars.clear();
257 }
258
259 /// Return whether the set is empty or not.
260 bool empty() const {
261 assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
262 return VarLocs.empty();
263 }
264 };
265
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000266 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
267 unsigned &Reg);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000268 /// If a given instruction is identified as a spill, return the spill location
269 /// and set \p Reg to the spilled register.
270 Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
271 MachineFunction *MF,
272 unsigned &Reg);
273 /// Given a spill instruction, extract the register and offset used to
274 /// address the spill location in a target independent way.
275 VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000276 void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
277 TransferMap &Transfers, VarLocMap &VarLocIDs,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000278 unsigned OldVarID, TransferKind Kind,
279 unsigned NewReg = 0);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000280
Adrian Prantl7509d542016-05-26 21:42:47 +0000281 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000282 VarLocMap &VarLocIDs);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000283 void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
284 VarLocMap &VarLocIDs, TransferMap &Transfers);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000285 void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
286 VarLocMap &VarLocIDs, TransferMap &Transfers);
Adrian Prantl7509d542016-05-26 21:42:47 +0000287 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000288 const VarLocMap &VarLocIDs);
Adrian Prantl7509d542016-05-26 21:42:47 +0000289 bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000290 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
Nikola Prica441ad622019-05-27 13:51:30 +0000291
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000292 bool process(MachineInstr &MI, OpenRangesSet &OpenRanges,
293 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
294 TransferMap &Transfers, bool transferChanges);
Vikram TV859ad292015-12-16 11:09:48 +0000295
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000296 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000297 const VarLocMap &VarLocIDs,
Vedant Kumar8c466682018-10-05 21:44:15 +0000298 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
299 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
Vikram TV859ad292015-12-16 11:09:48 +0000300
301 bool ExtendRanges(MachineFunction &MF);
302
303public:
304 static char ID;
305
306 /// Default construct and initialize the pass.
307 LiveDebugValues();
308
309 /// Tell the pass manager which passes we depend on and what
310 /// information we preserve.
311 void getAnalysisUsage(AnalysisUsage &AU) const override;
312
Derek Schuffad154c82016-03-28 17:05:30 +0000313 MachineFunctionProperties getRequiredProperties() const override {
314 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000315 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000316 }
317
Vikram TV859ad292015-12-16 11:09:48 +0000318 /// Print to ostream with a message.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000319 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
320 const VarLocMap &VarLocIDs, const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000321 raw_ostream &Out) const;
322
323 /// Calculate the liveness information for the given machine function.
324 bool runOnMachineFunction(MachineFunction &MF) override;
325};
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000326
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000327} // end anonymous namespace
Vikram TV859ad292015-12-16 11:09:48 +0000328
329//===----------------------------------------------------------------------===//
330// Implementation
331//===----------------------------------------------------------------------===//
332
333char LiveDebugValues::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000334
Vikram TV859ad292015-12-16 11:09:48 +0000335char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000336
Matthias Braun1527baa2017-05-25 21:26:32 +0000337INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
Vikram TV859ad292015-12-16 11:09:48 +0000338 false, false)
339
340/// Default construct and initialize the pass.
341LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
342 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
343}
344
345/// Tell the pass manager which passes we depend on and what information we
346/// preserve.
347void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
Matt Arsenaultb1630a12016-06-08 05:18:01 +0000348 AU.setPreservesCFG();
Vikram TV859ad292015-12-16 11:09:48 +0000349 MachineFunctionPass::getAnalysisUsage(AU);
350}
351
Vikram TV859ad292015-12-16 11:09:48 +0000352//===----------------------------------------------------------------------===//
353// Debug Range Extension Implementation
354//===----------------------------------------------------------------------===//
355
Matthias Braun194ded52017-01-28 06:53:55 +0000356#ifndef NDEBUG
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000357void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
358 const VarLocInMBB &V,
359 const VarLocMap &VarLocIDs,
360 const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000361 raw_ostream &Out) const {
Keith Walkerf83a19f2016-09-20 16:04:31 +0000362 Out << '\n' << msg << '\n';
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000363 for (const MachineBasicBlock &BB : MF) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000364 const VarLocSet &L = V.lookup(&BB);
365 if (L.empty())
366 continue;
367 Out << "MBB: " << BB.getNumber() << ":\n";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000368 for (unsigned VLL : L) {
369 const VarLoc &VL = VarLocIDs[VLL];
Adrian Prantl7509d542016-05-26 21:42:47 +0000370 Out << " Var: " << VL.Var.getVar()->getName();
Vikram TV859ad292015-12-16 11:09:48 +0000371 Out << " MI: ";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000372 VL.dump();
Vikram TV859ad292015-12-16 11:09:48 +0000373 }
374 }
375 Out << "\n";
376}
Matthias Braun194ded52017-01-28 06:53:55 +0000377#endif
Vikram TV859ad292015-12-16 11:09:48 +0000378
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000379LiveDebugValues::VarLoc::SpillLoc
380LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000381 assert(MI.hasOneMemOperand() &&
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000382 "Spill instruction does not have exactly one memory operand?");
383 auto MMOI = MI.memoperands_begin();
384 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
385 assert(PVal->kind() == PseudoSourceValue::FixedStack &&
386 "Inconsistent memory operand in spill instruction");
387 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
388 const MachineBasicBlock *MBB = MI.getParent();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000389 unsigned Reg;
390 int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
391 return {Reg, Offset};
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000392}
393
Vikram TV859ad292015-12-16 11:09:48 +0000394/// End all previous ranges related to @MI and start a new range from @MI
395/// if it is a DBG_VALUE instr.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000396void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000397 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000398 VarLocMap &VarLocIDs) {
Vikram TV859ad292015-12-16 11:09:48 +0000399 if (!MI.isDebugValue())
400 return;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000401 const DILocalVariable *Var = MI.getDebugVariable();
402 const DILocation *DebugLoc = MI.getDebugLoc();
403 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
404 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
Vikram TV859ad292015-12-16 11:09:48 +0000405 "Expected inlined-at fields to agree");
Vikram TV859ad292015-12-16 11:09:48 +0000406
407 // End all previous ranges of Var.
Adrian Prantl7509d542016-05-26 21:42:47 +0000408 DebugVariable V(Var, InlinedAt);
409 OpenRanges.erase(V);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000410
411 // Add the VarLoc to OpenRanges from this DBG_VALUE.
Eric Christopherc93f56d2019-05-08 23:54:03 +0000412 // TODO: Currently handles DBG_VALUE which has only reg as location.
413 if (isDbgValueDescribedByReg(MI)) {
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000414 VarLoc VL(MI, LS);
Eric Christopherc93f56d2019-05-08 23:54:03 +0000415 unsigned ID = VarLocIDs.insert(VL);
Adrian Prantl7509d542016-05-26 21:42:47 +0000416 OpenRanges.insert(ID, VL.Var);
417 }
Vikram TV859ad292015-12-16 11:09:48 +0000418}
419
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000420/// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
421/// with \p OldVarID should be deleted form \p OpenRanges and replaced with
422/// new VarLoc. If \p NewReg is different than default zero value then the
423/// new location will be register location created by the copy like instruction,
424/// otherwise it is variable's location on the stack.
425void LiveDebugValues::insertTransferDebugPair(
426 MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000427 VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
428 unsigned NewReg) {
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000429 const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000430 MachineFunction *MF = MI.getParent()->getParent();
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000431 MachineInstr *NewDebugInstr;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000432
433 auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers,
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000434 &VarLocIDs](VarLoc &VL, MachineInstr *NewDebugInstr) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000435 unsigned LocId = VarLocIDs.insert(VL);
436 OpenRanges.insert(LocId, VL.Var);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000437 // The newly created DBG_VALUE instruction NewDebugInstr must be inserted
438 // after MI. Keep track of the pairing.
439 TransferDebugPair MIP = {&MI, NewDebugInstr};
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000440 Transfers.push_back(MIP);
441 };
442
443 // End all previous ranges of Var.
444 OpenRanges.erase(VarLocIDs[OldVarID].Var);
445 switch (Kind) {
446 case TransferKind::TransferCopy: {
447 assert(NewReg &&
448 "No register supplied when handling a copy of a debug value");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000449 // Create a DBG_VALUE instruction to describe the Var in its new
450 // register location.
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000451 NewDebugInstr = BuildMI(
452 *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(),
453 DebugInstr->isIndirectDebugValue(), NewReg,
454 DebugInstr->getDebugVariable(), DebugInstr->getDebugExpression());
455 if (DebugInstr->isIndirectDebugValue())
456 NewDebugInstr->getOperand(1).setImm(DebugInstr->getOperand(1).getImm());
457 VarLoc VL(*NewDebugInstr, LS);
458 ProcessVarLoc(VL, NewDebugInstr);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000459 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000460 NewDebugInstr->print(dbgs(), false, false, false, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000461 return;
462 }
463 case TransferKind::TransferSpill: {
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000464 // Create a DBG_VALUE instruction to describe the Var in its spilled
465 // location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000466 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000467 auto *SpillExpr = DIExpression::prepend(DebugInstr->getDebugExpression(),
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000468 DIExpression::ApplyOffset,
469 SpillLocation.SpillOffset);
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000470 NewDebugInstr = BuildMI(
471 *MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), true,
472 SpillLocation.SpillBase, DebugInstr->getDebugVariable(), SpillExpr);
473 VarLoc VL(*NewDebugInstr, SpillLocation.SpillBase,
474 SpillLocation.SpillOffset, LS);
475 ProcessVarLoc(VL, NewDebugInstr);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000476 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000477 NewDebugInstr->print(dbgs(), false, false, false, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000478 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000479 }
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000480 case TransferKind::TransferRestore: {
481 assert(NewReg &&
482 "No register supplied when handling a restore of a debug value");
483 MachineFunction *MF = MI.getMF();
484 DIBuilder DIB(*const_cast<Function &>(MF->getFunction()).getParent());
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000485 NewDebugInstr =
486 BuildMI(*MF, DebugInstr->getDebugLoc(), DebugInstr->getDesc(), false,
487 NewReg, DebugInstr->getDebugVariable(), DIB.createExpression());
488 VarLoc VL(*NewDebugInstr, LS);
489 ProcessVarLoc(VL, NewDebugInstr);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000490 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register restore: ";
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000491 NewDebugInstr->print(dbgs(), false, false, false, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000492 return;
493 }
494 }
495 llvm_unreachable("Invalid transfer kind");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000496}
497
Vikram TV859ad292015-12-16 11:09:48 +0000498/// A definition of a register may mark the end of a range.
499void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000500 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000501 const VarLocMap &VarLocIDs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +0000502 MachineFunction *MF = MI.getMF();
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000503 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
504 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000505 SparseBitVector<> KillSet;
Vikram TV859ad292015-12-16 11:09:48 +0000506 for (const MachineOperand &MO : MI.operands()) {
Adrian Prantlea8880b2017-03-03 01:08:25 +0000507 // Determine whether the operand is a register def. Assume that call
508 // instructions never clobber SP, because some backends (e.g., AArch64)
509 // never list SP in the regmask.
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000510 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Adrian Prantlea8880b2017-03-03 01:08:25 +0000511 TRI->isPhysicalRegister(MO.getReg()) &&
512 !(MI.isCall() && MO.getReg() == SP)) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000513 // Remove ranges of all aliased registers.
514 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
Adrian Prantl7509d542016-05-26 21:42:47 +0000515 for (unsigned ID : OpenRanges.getVarLocs())
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000516 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
517 KillSet.set(ID);
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000518 } else if (MO.isRegMask()) {
519 // Remove ranges of all clobbered registers. Register masks don't usually
520 // list SP as preserved. While the debug info may be off for an
521 // instruction or two around callee-cleanup calls, transferring the
522 // DEBUG_VALUE across the call is still a better user experience.
Adrian Prantl7509d542016-05-26 21:42:47 +0000523 for (unsigned ID : OpenRanges.getVarLocs()) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000524 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
525 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
526 KillSet.set(ID);
527 }
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000528 }
Vikram TV859ad292015-12-16 11:09:48 +0000529 }
Adrian Prantl7509d542016-05-26 21:42:47 +0000530 OpenRanges.erase(KillSet, VarLocIDs);
Vikram TV859ad292015-12-16 11:09:48 +0000531}
532
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000533/// Decide if @MI is a spill instruction and return true if it is. We use 2
534/// criteria to make this decision:
535/// - Is this instruction a store to a spill slot?
536/// - Is there a register operand that is both used and killed?
537/// TODO: Store optimization can fold spills into other stores (including
538/// other spills). We do not handle this yet (more than one memory operand).
539bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
540 MachineFunction *MF, unsigned &Reg) {
Sander de Smalenc91b27d2018-09-05 08:59:50 +0000541 SmallVector<const MachineMemOperand*, 1> Accesses;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000542
Fangrui Songf78650a2018-07-30 19:41:25 +0000543 // TODO: Handle multiple stores folded into one.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000544 if (!MI.hasOneMemOperand())
545 return false;
546
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000547 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
548 return false; // This is not a spill instruction, since no valid size was
549 // returned from either function.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000550
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000551 auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
552 if (!MO.isReg() || !MO.isUse()) {
553 Reg = 0;
554 return false;
555 }
556 Reg = MO.getReg();
557 return MO.isKill();
558 };
559
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000560 for (const MachineOperand &MO : MI.operands()) {
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000561 // In a spill instruction generated by the InlineSpiller the spilled
562 // register has its kill flag set.
563 if (isKilledReg(MO, Reg))
564 return true;
565 if (Reg != 0) {
566 // Check whether next instruction kills the spilled register.
567 // FIXME: Current solution does not cover search for killed register in
568 // bundles and instructions further down the chain.
569 auto NextI = std::next(MI.getIterator());
570 // Skip next instruction that points to basic block end iterator.
571 if (MI.getParent()->end() == NextI)
572 continue;
573 unsigned RegNext;
574 for (const MachineOperand &MONext : NextI->operands()) {
575 // Return true if we came across the register from the
576 // previous spill instruction that is killed in NextI.
577 if (isKilledReg(MONext, RegNext) && RegNext == Reg)
578 return true;
579 }
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000580 }
581 }
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000582 // Return false if we didn't find spilled register.
583 return false;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000584}
585
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000586Optional<LiveDebugValues::VarLoc::SpillLoc>
587LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
588 MachineFunction *MF, unsigned &Reg) {
589 if (!MI.hasOneMemOperand())
590 return None;
591
592 // FIXME: Handle folded restore instructions with more than one memory
593 // operand.
594 if (MI.getRestoreSize(TII)) {
595 Reg = MI.getOperand(0).getReg();
596 return extractSpillBaseRegAndOffset(MI);
597 }
598 return None;
599}
600
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000601/// A spilled register may indicate that we have to end the current range of
602/// a variable and create a new one for the spill location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000603/// A restored register may indicate the reverse situation.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000604/// We don't want to insert any instructions in process(), so we just create
605/// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000606/// It will be inserted into the BB when we're done iterating over the
607/// instructions.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000608void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
609 OpenRangesSet &OpenRanges,
610 VarLocMap &VarLocIDs,
611 TransferMap &Transfers) {
Wolfgang Piebfacd0522019-01-30 20:37:14 +0000612 MachineFunction *MF = MI.getMF();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000613 TransferKind TKind;
614 unsigned Reg;
615 Optional<VarLoc::SpillLoc> Loc;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000616
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000617 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
618
619 if (isSpillInstruction(MI, MF, Reg)) {
620 TKind = TransferKind::TransferSpill;
621 LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
622 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
623 << "\n");
624 } else {
625 if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
626 return;
627 TKind = TransferKind::TransferRestore;
628 LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
629 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
630 << "\n");
631 }
632 // Check if the register or spill location is the location of a debug value.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000633 for (unsigned ID : OpenRanges.getVarLocs()) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000634 if (TKind == TransferKind::TransferSpill &&
635 VarLocIDs[ID].isDescribedByReg() == Reg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000636 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
637 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000638 } else if (TKind == TransferKind::TransferRestore &&
639 VarLocIDs[ID].Loc.SpillLocation == *Loc) {
640 LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
641 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
642 } else
643 continue;
644 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
645 Reg);
646 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000647 }
648}
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000649
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000650/// If \p MI is a register copy instruction, that copies a previously tracked
651/// value from one register to another register that is callee saved, we
652/// create new DBG_VALUE instruction described with copy destination register.
653void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
654 OpenRangesSet &OpenRanges,
655 VarLocMap &VarLocIDs,
656 TransferMap &Transfers) {
657 const MachineOperand *SrcRegOp, *DestRegOp;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000658
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000659 if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
660 !DestRegOp->isDef())
661 return;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000662
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000663 auto isCalleSavedReg = [&](unsigned Reg) {
664 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
665 if (CalleeSavedRegs.test(*RAI))
666 return true;
667 return false;
668 };
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000669
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000670 unsigned SrcReg = SrcRegOp->getReg();
671 unsigned DestReg = DestRegOp->getReg();
672
673 // We want to recognize instructions where destination register is callee
674 // saved register. If register that could be clobbered by the call is
675 // included, there would be a great chance that it is going to be clobbered
676 // soon. It is more likely that previous register location, which is callee
677 // saved, is going to stay unclobbered longer, even if it is killed.
678 if (!isCalleSavedReg(DestReg))
679 return;
680
681 for (unsigned ID : OpenRanges.getVarLocs()) {
682 if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
683 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000684 TransferKind::TransferCopy, DestReg);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000685 return;
686 }
687 }
688}
689
Vikram TV859ad292015-12-16 11:09:48 +0000690/// Terminate all open ranges at the end of the current basic block.
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000691bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000692 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000693 VarLocInMBB &OutLocs,
694 const VarLocMap &VarLocIDs) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000695 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000696 const MachineBasicBlock *CurMBB = MI.getParent();
Petar Jovanovice9500ba2018-01-08 18:21:15 +0000697 if (!(MI.isTerminator() || (&MI == &CurMBB->back())))
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000698 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000699
700 if (OpenRanges.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000701 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000702
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000703 LLVM_DEBUG(for (unsigned ID
704 : OpenRanges.getVarLocs()) {
705 // Copy OpenRanges to OutLocs, if not already present.
Vedant Kumar9b558382018-10-05 21:44:00 +0000706 dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000707 VarLocIDs[ID].dump();
708 });
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000709 VarLocSet &VLS = OutLocs[CurMBB];
Adrian Prantl7509d542016-05-26 21:42:47 +0000710 Changed = VLS |= OpenRanges.getVarLocs();
Vikram TV859ad292015-12-16 11:09:48 +0000711 OpenRanges.clear();
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000712 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000713}
714
715/// This routine creates OpenRanges and OutLocs.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000716bool LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
717 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
718 TransferMap &Transfers, bool transferChanges) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000719 bool Changed = false;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000720 transferDebugValue(MI, OpenRanges, VarLocIDs);
721 transferRegisterDef(MI, OpenRanges, VarLocIDs);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000722 if (transferChanges) {
723 transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000724 transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000725 }
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000726 Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000727 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000728}
729
730/// This routine joins the analysis results of all incoming edges in @MBB by
731/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
732/// source variable in all the predecessors of @MBB reside in the same location.
Vedant Kumar8c466682018-10-05 21:44:15 +0000733bool LiveDebugValues::join(
734 MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
735 const VarLocMap &VarLocIDs,
736 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
737 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000738 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000739 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000740
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000741 VarLocSet InLocsT; // Temporary incoming locations.
Vikram TV859ad292015-12-16 11:09:48 +0000742
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000743 // For all predecessors of this MBB, find the set of VarLocs that
744 // can be joined.
Keith Walker83ebef52016-09-27 16:46:07 +0000745 int NumVisited = 0;
Vikram TV859ad292015-12-16 11:09:48 +0000746 for (auto p : MBB.predecessors()) {
Keith Walker83ebef52016-09-27 16:46:07 +0000747 // Ignore unvisited predecessor blocks. As we are processing
748 // the blocks in reverse post-order any unvisited block can
749 // be considered to not remove any incoming values.
Vedant Kumar9b558382018-10-05 21:44:00 +0000750 if (!Visited.count(p)) {
751 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
752 << "\n");
Keith Walker83ebef52016-09-27 16:46:07 +0000753 continue;
Vedant Kumar9b558382018-10-05 21:44:00 +0000754 }
Vikram TV859ad292015-12-16 11:09:48 +0000755 auto OL = OutLocs.find(p);
756 // Join is null in case of empty OutLocs from any of the pred.
757 if (OL == OutLocs.end())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000758 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000759
Keith Walker83ebef52016-09-27 16:46:07 +0000760 // Just copy over the Out locs to incoming locs for the first visited
761 // predecessor, and for all other predecessors join the Out locs.
762 if (!NumVisited)
Vikram TV859ad292015-12-16 11:09:48 +0000763 InLocsT = OL->second;
Keith Walker83ebef52016-09-27 16:46:07 +0000764 else
765 InLocsT &= OL->second;
Vedant Kumar9b558382018-10-05 21:44:00 +0000766
767 LLVM_DEBUG({
768 if (!InLocsT.empty()) {
769 for (auto ID : InLocsT)
770 dbgs() << " gathered candidate incoming var: "
771 << VarLocIDs[ID].Var.getVar()->getName() << "\n";
772 }
773 });
774
Keith Walker83ebef52016-09-27 16:46:07 +0000775 NumVisited++;
Vikram TV859ad292015-12-16 11:09:48 +0000776 }
777
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000778 // Filter out DBG_VALUES that are out of scope.
779 VarLocSet KillSet;
Vedant Kumar8c466682018-10-05 21:44:15 +0000780 bool IsArtificial = ArtificialBlocks.count(&MBB);
781 if (!IsArtificial) {
782 for (auto ID : InLocsT) {
783 if (!VarLocIDs[ID].dominates(MBB)) {
784 KillSet.set(ID);
785 LLVM_DEBUG({
786 auto Name = VarLocIDs[ID].Var.getVar()->getName();
787 dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
788 });
789 }
Vedant Kumar9b558382018-10-05 21:44:00 +0000790 }
791 }
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000792 InLocsT.intersectWithComplement(KillSet);
793
Keith Walker83ebef52016-09-27 16:46:07 +0000794 // As we are processing blocks in reverse post-order we
795 // should have processed at least one predecessor, unless it
796 // is the entry block which has no predecessor.
797 assert((NumVisited || MBB.pred_empty()) &&
798 "Should have processed at least one predecessor");
Vikram TV859ad292015-12-16 11:09:48 +0000799 if (InLocsT.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000800 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000801
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000802 VarLocSet &ILS = InLocs[&MBB];
Vikram TV859ad292015-12-16 11:09:48 +0000803
804 // Insert DBG_VALUE instructions, if not already inserted.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000805 VarLocSet Diff = InLocsT;
806 Diff.intersectWithComplement(ILS);
807 for (auto ID : Diff) {
808 // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
809 // new range is started for the var from the mbb's beginning by inserting
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000810 // a new DBG_VALUE. process() will end this range however appropriate.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000811 const VarLoc &DiffIt = VarLocIDs[ID];
Petar Jovanovicaa28b6d2019-05-23 13:49:06 +0000812 const MachineInstr *DebugInstr = &DiffIt.MI;
813 MachineInstr *MI = BuildMI(
814 MBB, MBB.instr_begin(), DebugInstr->getDebugLoc(),
815 DebugInstr->getDesc(), DebugInstr->isIndirectDebugValue(),
816 DebugInstr->getOperand(0).getReg(), DebugInstr->getDebugVariable(),
817 DebugInstr->getDebugExpression());
818 if (DebugInstr->isIndirectDebugValue())
819 MI->getOperand(1).setImm(DebugInstr->getOperand(1).getImm());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000820 LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000821 ILS.set(ID);
822 ++NumInserted;
823 Changed = true;
Vikram TV859ad292015-12-16 11:09:48 +0000824 }
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000825 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000826}
827
828/// Calculate the liveness information for the given machine function and
829/// extend ranges across basic blocks.
830bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000831 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
Vikram TV859ad292015-12-16 11:09:48 +0000832
833 bool Changed = false;
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000834 bool OLChanged = false;
835 bool MBBJoined = false;
Vikram TV859ad292015-12-16 11:09:48 +0000836
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000837 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
Adrian Prantl7509d542016-05-26 21:42:47 +0000838 OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000839 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
840 VarLocInMBB InLocs; // Ranges that are incoming after joining.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000841 TransferMap Transfers; // DBG_VALUEs associated with spills.
Vikram TV859ad292015-12-16 11:09:48 +0000842
Vedant Kumar8c466682018-10-05 21:44:15 +0000843 // Blocks which are artificial, i.e. blocks which exclusively contain
844 // instructions without locations, or with line 0 locations.
845 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
846
Daniel Berlin72560592016-01-10 18:08:32 +0000847 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
848 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
849 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000850 std::greater<unsigned int>>
851 Worklist;
Daniel Berlin72560592016-01-10 18:08:32 +0000852 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000853 std::greater<unsigned int>>
854 Pending;
855
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000856 enum : bool { dontTransferChanges = false, transferChanges = true };
857
Vikram TV859ad292015-12-16 11:09:48 +0000858 // Initialize every mbb with OutLocs.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000859 // We are not looking at any spill instructions during the initial pass
860 // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
861 // instructions for spills of registers that are known to be user variables
862 // within the BB in which the spill occurs.
Vikram TV859ad292015-12-16 11:09:48 +0000863 for (auto &MBB : MF)
864 for (auto &MI : MBB)
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000865 process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
866 dontTransferChanges);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000867
Vedant Kumar8c466682018-10-05 21:44:15 +0000868 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
869 if (const DebugLoc &DL = MI.getDebugLoc())
870 return DL.getLine() != 0;
871 return false;
872 };
873 for (auto &MBB : MF)
874 if (none_of(MBB.instrs(), hasNonArtificialLocation))
875 ArtificialBlocks.insert(&MBB);
876
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000877 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
878 "OutLocs after initialization", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000879
Daniel Berlin72560592016-01-10 18:08:32 +0000880 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
881 unsigned int RPONumber = 0;
882 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
883 OrderToBB[RPONumber] = *RI;
884 BBToOrder[*RI] = RPONumber;
885 Worklist.push(RPONumber);
886 ++RPONumber;
887 }
Daniel Berlin72560592016-01-10 18:08:32 +0000888 // This is a standard "union of predecessor outs" dataflow problem.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000889 // To solve it, we perform join() and process() using the two worklist method
Daniel Berlin72560592016-01-10 18:08:32 +0000890 // until the ranges converge.
891 // Ranges have converged when both worklists are empty.
Keith Walker83ebef52016-09-27 16:46:07 +0000892 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
Daniel Berlin72560592016-01-10 18:08:32 +0000893 while (!Worklist.empty() || !Pending.empty()) {
894 // We track what is on the pending worklist to avoid inserting the same
895 // thing twice. We could avoid this with a custom priority queue, but this
896 // is probably not worth it.
897 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000898 LLVM_DEBUG(dbgs() << "Processing Worklist\n");
Daniel Berlin72560592016-01-10 18:08:32 +0000899 while (!Worklist.empty()) {
900 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
901 Worklist.pop();
Vedant Kumar8c466682018-10-05 21:44:15 +0000902 MBBJoined =
903 join(*MBB, OutLocs, InLocs, VarLocIDs, Visited, ArtificialBlocks);
Keith Walker83ebef52016-09-27 16:46:07 +0000904 Visited.insert(MBB);
Daniel Berlin72560592016-01-10 18:08:32 +0000905 if (MBBJoined) {
906 MBBJoined = false;
907 Changed = true;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000908 // Now that we have started to extend ranges across BBs we need to
909 // examine spill instructions to see whether they spill registers that
910 // correspond to user variables.
Daniel Berlin72560592016-01-10 18:08:32 +0000911 for (auto &MI : *MBB)
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000912 OLChanged |= process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
913 transferChanges);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000914
915 // Add any DBG_VALUE instructions necessitated by spills.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000916 for (auto &TR : Transfers)
917 MBB->insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
918 TR.DebugInst);
919 Transfers.clear();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000920
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000921 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
922 "OutLocs after propagating", dbgs()));
923 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
924 "InLocs after propagating", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000925
Daniel Berlin72560592016-01-10 18:08:32 +0000926 if (OLChanged) {
927 OLChanged = false;
928 for (auto s : MBB->successors())
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000929 if (OnPending.insert(s).second) {
Daniel Berlin72560592016-01-10 18:08:32 +0000930 Pending.push(BBToOrder[s]);
931 }
932 }
Vikram TV859ad292015-12-16 11:09:48 +0000933 }
934 }
Daniel Berlin72560592016-01-10 18:08:32 +0000935 Worklist.swap(Pending);
936 // At this point, pending must be empty, since it was just the empty
937 // worklist
938 assert(Pending.empty() && "Pending should be empty");
Vikram TV859ad292015-12-16 11:09:48 +0000939 }
Daniel Berlin72560592016-01-10 18:08:32 +0000940
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000941 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
942 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000943 return Changed;
944}
945
946bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000947 if (!MF.getFunction().getSubprogram())
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000948 // LiveDebugValues will already have removed all DBG_VALUEs.
949 return false;
950
Wolfgang Piebe018bbd2017-07-19 19:36:40 +0000951 // Skip functions from NoDebug compilation units.
Matthias Braunf1caa282017-12-15 22:22:58 +0000952 if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
Wolfgang Piebe018bbd2017-07-19 19:36:40 +0000953 DICompileUnit::NoDebug)
954 return false;
955
Vikram TV859ad292015-12-16 11:09:48 +0000956 TRI = MF.getSubtarget().getRegisterInfo();
957 TII = MF.getSubtarget().getInstrInfo();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000958 TFI = MF.getSubtarget().getFrameLowering();
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000959 TFI->determineCalleeSaves(MF, CalleeSavedRegs,
960 make_unique<RegScavenger>().get());
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000961 LS.initialize(MF);
Vikram TV859ad292015-12-16 11:09:48 +0000962
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000963 bool Changed = ExtendRanges(MF);
Vikram TV859ad292015-12-16 11:09:48 +0000964 return Changed;
965}