blob: e36694d2c5b3ade3d945a38c85b93ed9f0ec1565 [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,
Jeremy Morse055aee12019-04-29 09:13:16 +0000146 SpillLocKind,
147 ImmediateKind
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000148 } Kind = InvalidKind;
Vikram TV859ad292015-12-16 11:09:48 +0000149
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000150 /// The value location. Stored separately to avoid repeatedly
151 /// extracting it from MI.
152 union {
Adrian Prantl359846f2017-07-28 23:25:51 +0000153 uint64_t RegNo;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000154 SpillLoc SpillLocation;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000155 uint64_t Hash;
Jeremy Morse055aee12019-04-29 09:13:16 +0000156 int64_t Immediate;
157 const ConstantFP *FPImm;
158 const ConstantInt *CImm;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000159 } Loc;
160
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000161 VarLoc(const MachineInstr &MI, LexicalScopes &LS)
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000162 : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000163 UVS(MI.getDebugLoc(), LS) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000164 static_assert((sizeof(Loc) == sizeof(uint64_t)),
165 "hash does not cover all members of Loc");
166 assert(MI.isDebugValue() && "not a DBG_VALUE");
167 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
Adrian Prantl00698732016-05-25 22:37:29 +0000168 if (int RegNo = isDbgValueDescribedByReg(MI)) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000169 Kind = RegisterKind;
Adrian Prantl359846f2017-07-28 23:25:51 +0000170 Loc.RegNo = RegNo;
Jeremy Morse055aee12019-04-29 09:13:16 +0000171 } else if (MI.getOperand(0).isImm()) {
172 Kind = ImmediateKind;
173 Loc.Immediate = MI.getOperand(0).getImm();
174 } else if (MI.getOperand(0).isFPImm()) {
175 Kind = ImmediateKind;
176 Loc.FPImm = MI.getOperand(0).getFPImm();
177 } else if (MI.getOperand(0).isCImm()) {
178 Kind = ImmediateKind;
179 Loc.CImm = MI.getOperand(0).getCImm();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000180 }
181 }
182
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000183 /// The constructor for spill locations.
184 VarLoc(const MachineInstr &MI, unsigned SpillBase, int SpillOffset,
185 LexicalScopes &LS)
186 : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
187 UVS(MI.getDebugLoc(), LS) {
188 assert(MI.isDebugValue() && "not a DBG_VALUE");
189 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
190 Kind = SpillLocKind;
191 Loc.SpillLocation = {SpillBase, SpillOffset};
192 }
193
Jeremy Morse055aee12019-04-29 09:13:16 +0000194 // Is the Loc field a constant or constant object?
195 bool isConstant() const { return Kind == ImmediateKind; }
196
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000197 /// If this variable is described by a register, return it,
198 /// otherwise return 0.
199 unsigned isDescribedByReg() const {
200 if (Kind == RegisterKind)
Adrian Prantl359846f2017-07-28 23:25:51 +0000201 return Loc.RegNo;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000202 return 0;
203 }
204
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000205 /// Determine whether the lexical scope of this value's debug location
206 /// dominates MBB.
207 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
208
Aaron Ballman615eb472017-10-15 14:32:27 +0000209#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun194ded52017-01-28 06:53:55 +0000210 LLVM_DUMP_METHOD void dump() const { MI.dump(); }
211#endif
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000212
213 bool operator==(const VarLoc &Other) const {
Jeremy Morse055aee12019-04-29 09:13:16 +0000214 return Kind == Other.Kind && Var == Other.Var &&
215 Loc.Hash == Other.Loc.Hash;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000216 }
217
Adrian Prantl7509d542016-05-26 21:42:47 +0000218 /// This operator guarantees that VarLocs are sorted by Variable first.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000219 bool operator<(const VarLoc &Other) const {
220 if (Var == Other.Var)
221 return Loc.Hash < Other.Loc.Hash;
222 return Var < Other.Var;
223 }
Vikram TV859ad292015-12-16 11:09:48 +0000224 };
225
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000226 using VarLocMap = UniqueVector<VarLoc>;
227 using VarLocSet = SparseBitVector<>;
228 using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000229 struct TransferDebugPair {
230 MachineInstr *TransferInst;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000231 MachineInstr *DebugInst;
232 };
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000233 using TransferMap = SmallVector<TransferDebugPair, 4>;
Vikram TV859ad292015-12-16 11:09:48 +0000234
Adrian Prantl7509d542016-05-26 21:42:47 +0000235 /// This holds the working set of currently open ranges. For fast
236 /// access, this is done both as a set of VarLocIDs, and a map of
237 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
238 /// previous open ranges for the same variable.
239 class OpenRangesSet {
240 VarLocSet VarLocs;
241 SmallDenseMap<DebugVariableBase, unsigned, 8> Vars;
242
243 public:
244 const VarLocSet &getVarLocs() const { return VarLocs; }
245
246 /// Terminate all open ranges for Var by removing it from the set.
247 void erase(DebugVariable Var) {
248 auto It = Vars.find(Var);
249 if (It != Vars.end()) {
250 unsigned ID = It->second;
251 VarLocs.reset(ID);
252 Vars.erase(It);
253 }
254 }
255
256 /// Terminate all open ranges listed in \c KillSet by removing
257 /// them from the set.
258 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
259 VarLocs.intersectWithComplement(KillSet);
260 for (unsigned ID : KillSet)
261 Vars.erase(VarLocIDs[ID].Var);
262 }
263
264 /// Insert a new range into the set.
265 void insert(unsigned VarLocID, DebugVariableBase Var) {
266 VarLocs.set(VarLocID);
267 Vars.insert({Var, VarLocID});
268 }
269
270 /// Empty the set.
271 void clear() {
272 VarLocs.clear();
273 Vars.clear();
274 }
275
276 /// Return whether the set is empty or not.
277 bool empty() const {
278 assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
279 return VarLocs.empty();
280 }
281 };
282
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000283 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
284 unsigned &Reg);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000285 /// If a given instruction is identified as a spill, return the spill location
286 /// and set \p Reg to the spilled register.
287 Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
288 MachineFunction *MF,
289 unsigned &Reg);
290 /// Given a spill instruction, extract the register and offset used to
291 /// address the spill location in a target independent way.
292 VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000293 void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
294 TransferMap &Transfers, VarLocMap &VarLocIDs,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000295 unsigned OldVarID, TransferKind Kind,
296 unsigned NewReg = 0);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000297
Adrian Prantl7509d542016-05-26 21:42:47 +0000298 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000299 VarLocMap &VarLocIDs);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000300 void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
301 VarLocMap &VarLocIDs, TransferMap &Transfers);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000302 void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
303 VarLocMap &VarLocIDs, TransferMap &Transfers);
Adrian Prantl7509d542016-05-26 21:42:47 +0000304 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000305 const VarLocMap &VarLocIDs);
Adrian Prantl7509d542016-05-26 21:42:47 +0000306 bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000307 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000308 bool process(MachineInstr &MI, OpenRangesSet &OpenRanges,
309 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
310 TransferMap &Transfers, bool transferChanges);
Vikram TV859ad292015-12-16 11:09:48 +0000311
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000312 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
Keith Walker83ebef52016-09-27 16:46:07 +0000313 const VarLocMap &VarLocIDs,
Vedant Kumar8c466682018-10-05 21:44:15 +0000314 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
315 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
Vikram TV859ad292015-12-16 11:09:48 +0000316
317 bool ExtendRanges(MachineFunction &MF);
318
319public:
320 static char ID;
321
322 /// Default construct and initialize the pass.
323 LiveDebugValues();
324
325 /// Tell the pass manager which passes we depend on and what
326 /// information we preserve.
327 void getAnalysisUsage(AnalysisUsage &AU) const override;
328
Derek Schuffad154c82016-03-28 17:05:30 +0000329 MachineFunctionProperties getRequiredProperties() const override {
330 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000331 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000332 }
333
Vikram TV859ad292015-12-16 11:09:48 +0000334 /// Print to ostream with a message.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000335 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
336 const VarLocMap &VarLocIDs, const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000337 raw_ostream &Out) const;
338
339 /// Calculate the liveness information for the given machine function.
340 bool runOnMachineFunction(MachineFunction &MF) override;
341};
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000342
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000343} // end anonymous namespace
Vikram TV859ad292015-12-16 11:09:48 +0000344
345//===----------------------------------------------------------------------===//
346// Implementation
347//===----------------------------------------------------------------------===//
348
349char LiveDebugValues::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000350
Vikram TV859ad292015-12-16 11:09:48 +0000351char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000352
Matthias Braun1527baa2017-05-25 21:26:32 +0000353INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
Vikram TV859ad292015-12-16 11:09:48 +0000354 false, false)
355
356/// Default construct and initialize the pass.
357LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
358 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
359}
360
361/// Tell the pass manager which passes we depend on and what information we
362/// preserve.
363void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
Matt Arsenaultb1630a12016-06-08 05:18:01 +0000364 AU.setPreservesCFG();
Vikram TV859ad292015-12-16 11:09:48 +0000365 MachineFunctionPass::getAnalysisUsage(AU);
366}
367
Vikram TV859ad292015-12-16 11:09:48 +0000368//===----------------------------------------------------------------------===//
369// Debug Range Extension Implementation
370//===----------------------------------------------------------------------===//
371
Matthias Braun194ded52017-01-28 06:53:55 +0000372#ifndef NDEBUG
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000373void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
374 const VarLocInMBB &V,
375 const VarLocMap &VarLocIDs,
376 const char *msg,
Vikram TV859ad292015-12-16 11:09:48 +0000377 raw_ostream &Out) const {
Keith Walkerf83a19f2016-09-20 16:04:31 +0000378 Out << '\n' << msg << '\n';
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000379 for (const MachineBasicBlock &BB : MF) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000380 const VarLocSet &L = V.lookup(&BB);
381 if (L.empty())
382 continue;
383 Out << "MBB: " << BB.getNumber() << ":\n";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000384 for (unsigned VLL : L) {
385 const VarLoc &VL = VarLocIDs[VLL];
Adrian Prantl7509d542016-05-26 21:42:47 +0000386 Out << " Var: " << VL.Var.getVar()->getName();
Vikram TV859ad292015-12-16 11:09:48 +0000387 Out << " MI: ";
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000388 VL.dump();
Vikram TV859ad292015-12-16 11:09:48 +0000389 }
390 }
391 Out << "\n";
392}
Matthias Braun194ded52017-01-28 06:53:55 +0000393#endif
Vikram TV859ad292015-12-16 11:09:48 +0000394
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000395LiveDebugValues::VarLoc::SpillLoc
396LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000397 assert(MI.hasOneMemOperand() &&
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000398 "Spill instruction does not have exactly one memory operand?");
399 auto MMOI = MI.memoperands_begin();
400 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
401 assert(PVal->kind() == PseudoSourceValue::FixedStack &&
402 "Inconsistent memory operand in spill instruction");
403 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
404 const MachineBasicBlock *MBB = MI.getParent();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000405 unsigned Reg;
406 int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
407 return {Reg, Offset};
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000408}
409
Vikram TV859ad292015-12-16 11:09:48 +0000410/// End all previous ranges related to @MI and start a new range from @MI
411/// if it is a DBG_VALUE instr.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000412void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000413 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000414 VarLocMap &VarLocIDs) {
Vikram TV859ad292015-12-16 11:09:48 +0000415 if (!MI.isDebugValue())
416 return;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000417 const DILocalVariable *Var = MI.getDebugVariable();
418 const DILocation *DebugLoc = MI.getDebugLoc();
419 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
420 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
Vikram TV859ad292015-12-16 11:09:48 +0000421 "Expected inlined-at fields to agree");
Vikram TV859ad292015-12-16 11:09:48 +0000422
423 // End all previous ranges of Var.
Adrian Prantl7509d542016-05-26 21:42:47 +0000424 DebugVariable V(Var, InlinedAt);
425 OpenRanges.erase(V);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000426
427 // Add the VarLoc to OpenRanges from this DBG_VALUE.
Jeremy Morse055aee12019-04-29 09:13:16 +0000428 unsigned ID;
429 if (isDbgValueDescribedByReg(MI) || MI.getOperand(0).isImm() ||
430 MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) {
431 // Use normal VarLoc constructor for registers and immediates.
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000432 VarLoc VL(MI, LS);
Jeremy Morse055aee12019-04-29 09:13:16 +0000433 ID = VarLocIDs.insert(VL);
Adrian Prantl7509d542016-05-26 21:42:47 +0000434 OpenRanges.insert(ID, VL.Var);
Jeremy Morse055aee12019-04-29 09:13:16 +0000435 } else if (MI.hasOneMemOperand()) {
436 // It's a stack spill -- fetch spill base and offset.
437 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
438 VarLoc VL(MI, SpillLocation.SpillBase, SpillLocation.SpillOffset, LS);
439 ID = VarLocIDs.insert(VL);
440 OpenRanges.insert(ID, VL.Var);
441 } else {
442 // This must be an undefined location. We should leave OpenRanges closed.
443 assert(MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 &&
444 "Unexpected non-undef DBG_VALUE encountered");
Adrian Prantl7509d542016-05-26 21:42:47 +0000445 }
Vikram TV859ad292015-12-16 11:09:48 +0000446}
447
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000448/// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
449/// with \p OldVarID should be deleted form \p OpenRanges and replaced with
450/// new VarLoc. If \p NewReg is different than default zero value then the
451/// new location will be register location created by the copy like instruction,
452/// otherwise it is variable's location on the stack.
453void LiveDebugValues::insertTransferDebugPair(
454 MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000455 VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
456 unsigned NewReg) {
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000457 const MachineInstr *DMI = &VarLocIDs[OldVarID].MI;
458 MachineFunction *MF = MI.getParent()->getParent();
459 MachineInstr *NewDMI;
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000460
461 auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers,
462 &VarLocIDs](VarLoc &VL, MachineInstr *NewDMI) {
463 unsigned LocId = VarLocIDs.insert(VL);
464 OpenRanges.insert(LocId, VL.Var);
465 // The newly created DBG_VALUE instruction NewDMI must be inserted after
466 // MI. Keep track of the pairing.
467 TransferDebugPair MIP = {&MI, NewDMI};
468 Transfers.push_back(MIP);
469 };
470
471 // End all previous ranges of Var.
472 OpenRanges.erase(VarLocIDs[OldVarID].Var);
473 switch (Kind) {
474 case TransferKind::TransferCopy: {
475 assert(NewReg &&
476 "No register supplied when handling a copy of a debug value");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000477 // Create a DBG_VALUE instruction to describe the Var in its new
478 // register location.
479 NewDMI = BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(),
480 DMI->isIndirectDebugValue(), NewReg,
481 DMI->getDebugVariable(), DMI->getDebugExpression());
482 if (DMI->isIndirectDebugValue())
483 NewDMI->getOperand(1).setImm(DMI->getOperand(1).getImm());
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000484 VarLoc VL(*NewDMI, LS);
485 ProcessVarLoc(VL, NewDMI);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000486 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
487 NewDMI->print(dbgs(), false, false, false, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000488 return;
489 }
490 case TransferKind::TransferSpill: {
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000491 // Create a DBG_VALUE instruction to describe the Var in its spilled
492 // location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000493 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
494 auto *SpillExpr =
495 DIExpression::prepend(DMI->getDebugExpression(), DIExpression::NoDeref,
496 SpillLocation.SpillOffset);
497 NewDMI =
498 BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), true,
499 SpillLocation.SpillBase, DMI->getDebugVariable(), SpillExpr);
500 VarLoc VL(*NewDMI, SpillLocation.SpillBase, SpillLocation.SpillOffset, LS);
501 ProcessVarLoc(VL, NewDMI);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000502 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
503 NewDMI->print(dbgs(), false, false, false, TII));
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000504 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000505 }
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000506 case TransferKind::TransferRestore: {
507 assert(NewReg &&
508 "No register supplied when handling a restore of a debug value");
509 MachineFunction *MF = MI.getMF();
510 DIBuilder DIB(*const_cast<Function &>(MF->getFunction()).getParent());
511 NewDMI = BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), false, NewReg,
512 DMI->getDebugVariable(), DIB.createExpression());
513 VarLoc VL(*NewDMI, LS);
514 ProcessVarLoc(VL, NewDMI);
515 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register restore: ";
516 NewDMI->print(dbgs(), false, false, false, TII));
517 return;
518 }
519 }
520 llvm_unreachable("Invalid transfer kind");
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000521}
522
Vikram TV859ad292015-12-16 11:09:48 +0000523/// A definition of a register may mark the end of a range.
524void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000525 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000526 const VarLocMap &VarLocIDs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +0000527 MachineFunction *MF = MI.getMF();
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000528 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
529 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000530 SparseBitVector<> KillSet;
Vikram TV859ad292015-12-16 11:09:48 +0000531 for (const MachineOperand &MO : MI.operands()) {
Adrian Prantlea8880b2017-03-03 01:08:25 +0000532 // Determine whether the operand is a register def. Assume that call
533 // instructions never clobber SP, because some backends (e.g., AArch64)
534 // never list SP in the regmask.
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000535 if (MO.isReg() && MO.isDef() && MO.getReg() &&
Adrian Prantlea8880b2017-03-03 01:08:25 +0000536 TRI->isPhysicalRegister(MO.getReg()) &&
537 !(MI.isCall() && MO.getReg() == SP)) {
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000538 // Remove ranges of all aliased registers.
539 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
Adrian Prantl7509d542016-05-26 21:42:47 +0000540 for (unsigned ID : OpenRanges.getVarLocs())
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000541 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
542 KillSet.set(ID);
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000543 } else if (MO.isRegMask()) {
544 // Remove ranges of all clobbered registers. Register masks don't usually
545 // list SP as preserved. While the debug info may be off for an
546 // instruction or two around callee-cleanup calls, transferring the
547 // DEBUG_VALUE across the call is still a better user experience.
Adrian Prantl7509d542016-05-26 21:42:47 +0000548 for (unsigned ID : OpenRanges.getVarLocs()) {
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000549 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
550 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
551 KillSet.set(ID);
552 }
Reid Klecknerf6f04f82016-03-25 17:54:46 +0000553 }
Vikram TV859ad292015-12-16 11:09:48 +0000554 }
Adrian Prantl7509d542016-05-26 21:42:47 +0000555 OpenRanges.erase(KillSet, VarLocIDs);
Vikram TV859ad292015-12-16 11:09:48 +0000556}
557
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000558/// Decide if @MI is a spill instruction and return true if it is. We use 2
559/// criteria to make this decision:
560/// - Is this instruction a store to a spill slot?
561/// - Is there a register operand that is both used and killed?
562/// TODO: Store optimization can fold spills into other stores (including
563/// other spills). We do not handle this yet (more than one memory operand).
564bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
565 MachineFunction *MF, unsigned &Reg) {
Sander de Smalenc91b27d2018-09-05 08:59:50 +0000566 SmallVector<const MachineMemOperand*, 1> Accesses;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000567
Fangrui Songf78650a2018-07-30 19:41:25 +0000568 // TODO: Handle multiple stores folded into one.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000569 if (!MI.hasOneMemOperand())
570 return false;
571
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000572 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
573 return false; // This is not a spill instruction, since no valid size was
574 // returned from either function.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000575
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000576 auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
577 if (!MO.isReg() || !MO.isUse()) {
578 Reg = 0;
579 return false;
580 }
581 Reg = MO.getReg();
582 return MO.isKill();
583 };
584
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000585 for (const MachineOperand &MO : MI.operands()) {
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000586 // In a spill instruction generated by the InlineSpiller the spilled
587 // register has its kill flag set.
588 if (isKilledReg(MO, Reg))
589 return true;
590 if (Reg != 0) {
591 // Check whether next instruction kills the spilled register.
592 // FIXME: Current solution does not cover search for killed register in
593 // bundles and instructions further down the chain.
594 auto NextI = std::next(MI.getIterator());
595 // Skip next instruction that points to basic block end iterator.
596 if (MI.getParent()->end() == NextI)
597 continue;
598 unsigned RegNext;
599 for (const MachineOperand &MONext : NextI->operands()) {
600 // Return true if we came across the register from the
601 // previous spill instruction that is killed in NextI.
602 if (isKilledReg(MONext, RegNext) && RegNext == Reg)
603 return true;
604 }
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000605 }
606 }
Petar Jovanovic0b464e42018-01-16 14:46:05 +0000607 // Return false if we didn't find spilled register.
608 return false;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000609}
610
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000611Optional<LiveDebugValues::VarLoc::SpillLoc>
612LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
613 MachineFunction *MF, unsigned &Reg) {
614 if (!MI.hasOneMemOperand())
615 return None;
616
617 // FIXME: Handle folded restore instructions with more than one memory
618 // operand.
619 if (MI.getRestoreSize(TII)) {
620 Reg = MI.getOperand(0).getReg();
621 return extractSpillBaseRegAndOffset(MI);
622 }
623 return None;
624}
625
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000626/// A spilled register may indicate that we have to end the current range of
627/// a variable and create a new one for the spill location.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000628/// A restored register may indicate the reverse situation.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000629/// We don't want to insert any instructions in process(), so we just create
630/// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000631/// It will be inserted into the BB when we're done iterating over the
632/// instructions.
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000633void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
634 OpenRangesSet &OpenRanges,
635 VarLocMap &VarLocIDs,
636 TransferMap &Transfers) {
Wolfgang Piebfacd0522019-01-30 20:37:14 +0000637 MachineFunction *MF = MI.getMF();
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000638 TransferKind TKind;
639 unsigned Reg;
640 Optional<VarLoc::SpillLoc> Loc;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000641
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000642 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
643
644 if (isSpillInstruction(MI, MF, Reg)) {
645 TKind = TransferKind::TransferSpill;
646 LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
647 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
648 << "\n");
649 } else {
650 if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
651 return;
652 TKind = TransferKind::TransferRestore;
653 LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
654 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
655 << "\n");
656 }
657 // Check if the register or spill location is the location of a debug value.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000658 for (unsigned ID : OpenRanges.getVarLocs()) {
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000659 if (TKind == TransferKind::TransferSpill &&
660 VarLocIDs[ID].isDescribedByReg() == Reg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000661 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
662 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000663 } else if (TKind == TransferKind::TransferRestore &&
664 VarLocIDs[ID].Loc.SpillLocation == *Loc) {
665 LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
666 << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
667 } else
668 continue;
669 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
670 Reg);
671 return;
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000672 }
673}
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000674
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000675/// If \p MI is a register copy instruction, that copies a previously tracked
676/// value from one register to another register that is callee saved, we
677/// create new DBG_VALUE instruction described with copy destination register.
678void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
679 OpenRangesSet &OpenRanges,
680 VarLocMap &VarLocIDs,
681 TransferMap &Transfers) {
682 const MachineOperand *SrcRegOp, *DestRegOp;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000683
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000684 if (!TII->isCopyInstr(MI, SrcRegOp, DestRegOp) || !SrcRegOp->isKill() ||
685 !DestRegOp->isDef())
686 return;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000687
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000688 auto isCalleSavedReg = [&](unsigned Reg) {
689 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
690 if (CalleeSavedRegs.test(*RAI))
691 return true;
692 return false;
693 };
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000694
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000695 unsigned SrcReg = SrcRegOp->getReg();
696 unsigned DestReg = DestRegOp->getReg();
697
698 // We want to recognize instructions where destination register is callee
699 // saved register. If register that could be clobbered by the call is
700 // included, there would be a great chance that it is going to be clobbered
701 // soon. It is more likely that previous register location, which is callee
702 // saved, is going to stay unclobbered longer, even if it is killed.
703 if (!isCalleSavedReg(DestReg))
704 return;
705
706 for (unsigned ID : OpenRanges.getVarLocs()) {
707 if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
708 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000709 TransferKind::TransferCopy, DestReg);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000710 return;
711 }
712 }
713}
714
Vikram TV859ad292015-12-16 11:09:48 +0000715/// Terminate all open ranges at the end of the current basic block.
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000716bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
Adrian Prantl7509d542016-05-26 21:42:47 +0000717 OpenRangesSet &OpenRanges,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000718 VarLocInMBB &OutLocs,
719 const VarLocMap &VarLocIDs) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000720 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000721 const MachineBasicBlock *CurMBB = MI.getParent();
Petar Jovanovice9500ba2018-01-08 18:21:15 +0000722 if (!(MI.isTerminator() || (&MI == &CurMBB->back())))
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000723 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000724
725 if (OpenRanges.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000726 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000727
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000728 LLVM_DEBUG(for (unsigned ID
729 : OpenRanges.getVarLocs()) {
730 // Copy OpenRanges to OutLocs, if not already present.
Vedant Kumar9b558382018-10-05 21:44:00 +0000731 dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000732 VarLocIDs[ID].dump();
733 });
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000734 VarLocSet &VLS = OutLocs[CurMBB];
Adrian Prantl7509d542016-05-26 21:42:47 +0000735 Changed = VLS |= OpenRanges.getVarLocs();
Vikram TV859ad292015-12-16 11:09:48 +0000736 OpenRanges.clear();
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000737 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000738}
739
740/// This routine creates OpenRanges and OutLocs.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000741bool LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
742 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
743 TransferMap &Transfers, bool transferChanges) {
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000744 bool Changed = false;
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000745 transferDebugValue(MI, OpenRanges, VarLocIDs);
746 transferRegisterDef(MI, OpenRanges, VarLocIDs);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000747 if (transferChanges) {
748 transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
Wolfgang Pieb90d856c2019-02-04 20:42:45 +0000749 transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000750 }
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000751 Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000752 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000753}
754
755/// This routine joins the analysis results of all incoming edges in @MBB by
756/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
757/// source variable in all the predecessors of @MBB reside in the same location.
Vedant Kumar8c466682018-10-05 21:44:15 +0000758bool LiveDebugValues::join(
759 MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
760 const VarLocMap &VarLocIDs,
761 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
762 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
Vedant Kumar9b558382018-10-05 21:44:00 +0000763 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000764 bool Changed = false;
Vikram TV859ad292015-12-16 11:09:48 +0000765
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000766 VarLocSet InLocsT; // Temporary incoming locations.
Vikram TV859ad292015-12-16 11:09:48 +0000767
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000768 // For all predecessors of this MBB, find the set of VarLocs that
769 // can be joined.
Keith Walker83ebef52016-09-27 16:46:07 +0000770 int NumVisited = 0;
Vikram TV859ad292015-12-16 11:09:48 +0000771 for (auto p : MBB.predecessors()) {
Keith Walker83ebef52016-09-27 16:46:07 +0000772 // Ignore unvisited predecessor blocks. As we are processing
773 // the blocks in reverse post-order any unvisited block can
774 // be considered to not remove any incoming values.
Vedant Kumar9b558382018-10-05 21:44:00 +0000775 if (!Visited.count(p)) {
776 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
777 << "\n");
Keith Walker83ebef52016-09-27 16:46:07 +0000778 continue;
Vedant Kumar9b558382018-10-05 21:44:00 +0000779 }
Vikram TV859ad292015-12-16 11:09:48 +0000780 auto OL = OutLocs.find(p);
781 // Join is null in case of empty OutLocs from any of the pred.
782 if (OL == OutLocs.end())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000783 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000784
Keith Walker83ebef52016-09-27 16:46:07 +0000785 // Just copy over the Out locs to incoming locs for the first visited
786 // predecessor, and for all other predecessors join the Out locs.
787 if (!NumVisited)
Vikram TV859ad292015-12-16 11:09:48 +0000788 InLocsT = OL->second;
Keith Walker83ebef52016-09-27 16:46:07 +0000789 else
790 InLocsT &= OL->second;
Vedant Kumar9b558382018-10-05 21:44:00 +0000791
792 LLVM_DEBUG({
793 if (!InLocsT.empty()) {
794 for (auto ID : InLocsT)
795 dbgs() << " gathered candidate incoming var: "
796 << VarLocIDs[ID].Var.getVar()->getName() << "\n";
797 }
798 });
799
Keith Walker83ebef52016-09-27 16:46:07 +0000800 NumVisited++;
Vikram TV859ad292015-12-16 11:09:48 +0000801 }
802
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000803 // Filter out DBG_VALUES that are out of scope.
804 VarLocSet KillSet;
Vedant Kumar8c466682018-10-05 21:44:15 +0000805 bool IsArtificial = ArtificialBlocks.count(&MBB);
806 if (!IsArtificial) {
807 for (auto ID : InLocsT) {
808 if (!VarLocIDs[ID].dominates(MBB)) {
809 KillSet.set(ID);
810 LLVM_DEBUG({
811 auto Name = VarLocIDs[ID].Var.getVar()->getName();
812 dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
813 });
814 }
Vedant Kumar9b558382018-10-05 21:44:00 +0000815 }
816 }
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000817 InLocsT.intersectWithComplement(KillSet);
818
Keith Walker83ebef52016-09-27 16:46:07 +0000819 // As we are processing blocks in reverse post-order we
820 // should have processed at least one predecessor, unless it
821 // is the entry block which has no predecessor.
822 assert((NumVisited || MBB.pred_empty()) &&
823 "Should have processed at least one predecessor");
Vikram TV859ad292015-12-16 11:09:48 +0000824 if (InLocsT.empty())
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000825 return false;
Vikram TV859ad292015-12-16 11:09:48 +0000826
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000827 VarLocSet &ILS = InLocs[&MBB];
Vikram TV859ad292015-12-16 11:09:48 +0000828
829 // Insert DBG_VALUE instructions, if not already inserted.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000830 VarLocSet Diff = InLocsT;
831 Diff.intersectWithComplement(ILS);
832 for (auto ID : Diff) {
833 // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
834 // new range is started for the var from the mbb's beginning by inserting
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000835 // a new DBG_VALUE. process() will end this range however appropriate.
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000836 const VarLoc &DiffIt = VarLocIDs[ID];
837 const MachineInstr *DMI = &DiffIt.MI;
Jeremy Morse055aee12019-04-29 09:13:16 +0000838 MachineInstr *MI = nullptr;
839 if (DiffIt.isConstant()) {
840 MachineOperand MO(DMI->getOperand(0));
841 MI = BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
842 false, MO, DMI->getDebugVariable(),
843 DMI->getDebugExpression());
844 } else {
845 MI = BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
846 DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(),
847 DMI->getDebugVariable(), DMI->getDebugExpression());
848 if (DMI->isIndirectDebugValue())
849 MI->getOperand(1).setImm(DMI->getOperand(1).getImm());
850 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000851 LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000852 ILS.set(ID);
853 ++NumInserted;
854 Changed = true;
Vikram TV859ad292015-12-16 11:09:48 +0000855 }
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000856 return Changed;
Vikram TV859ad292015-12-16 11:09:48 +0000857}
858
859/// Calculate the liveness information for the given machine function and
860/// extend ranges across basic blocks.
861bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000862 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
Vikram TV859ad292015-12-16 11:09:48 +0000863
864 bool Changed = false;
Daniel Berlinca4d93a2016-01-10 03:25:42 +0000865 bool OLChanged = false;
866 bool MBBJoined = false;
Vikram TV859ad292015-12-16 11:09:48 +0000867
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000868 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
Adrian Prantl7509d542016-05-26 21:42:47 +0000869 OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000870 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
871 VarLocInMBB InLocs; // Ranges that are incoming after joining.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000872 TransferMap Transfers; // DBG_VALUEs associated with spills.
Vikram TV859ad292015-12-16 11:09:48 +0000873
Vedant Kumar8c466682018-10-05 21:44:15 +0000874 // Blocks which are artificial, i.e. blocks which exclusively contain
875 // instructions without locations, or with line 0 locations.
876 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
877
Daniel Berlin72560592016-01-10 18:08:32 +0000878 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
879 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
880 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000881 std::greater<unsigned int>>
882 Worklist;
Daniel Berlin72560592016-01-10 18:08:32 +0000883 std::priority_queue<unsigned int, std::vector<unsigned int>,
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000884 std::greater<unsigned int>>
885 Pending;
886
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000887 enum : bool { dontTransferChanges = false, transferChanges = true };
888
Vikram TV859ad292015-12-16 11:09:48 +0000889 // Initialize every mbb with OutLocs.
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000890 // We are not looking at any spill instructions during the initial pass
891 // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
892 // instructions for spills of registers that are known to be user variables
893 // within the BB in which the spill occurs.
Vikram TV859ad292015-12-16 11:09:48 +0000894 for (auto &MBB : MF)
895 for (auto &MI : MBB)
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000896 process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
897 dontTransferChanges);
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000898
Vedant Kumar8c466682018-10-05 21:44:15 +0000899 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
900 if (const DebugLoc &DL = MI.getDebugLoc())
901 return DL.getLine() != 0;
902 return false;
903 };
904 for (auto &MBB : MF)
905 if (none_of(MBB.instrs(), hasNonArtificialLocation))
906 ArtificialBlocks.insert(&MBB);
907
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000908 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
909 "OutLocs after initialization", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000910
Daniel Berlin72560592016-01-10 18:08:32 +0000911 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
912 unsigned int RPONumber = 0;
913 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
914 OrderToBB[RPONumber] = *RI;
915 BBToOrder[*RI] = RPONumber;
916 Worklist.push(RPONumber);
917 ++RPONumber;
918 }
Daniel Berlin72560592016-01-10 18:08:32 +0000919 // This is a standard "union of predecessor outs" dataflow problem.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000920 // To solve it, we perform join() and process() using the two worklist method
Daniel Berlin72560592016-01-10 18:08:32 +0000921 // until the ranges converge.
922 // Ranges have converged when both worklists are empty.
Keith Walker83ebef52016-09-27 16:46:07 +0000923 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
Daniel Berlin72560592016-01-10 18:08:32 +0000924 while (!Worklist.empty() || !Pending.empty()) {
925 // We track what is on the pending worklist to avoid inserting the same
926 // thing twice. We could avoid this with a custom priority queue, but this
927 // is probably not worth it.
928 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000929 LLVM_DEBUG(dbgs() << "Processing Worklist\n");
Daniel Berlin72560592016-01-10 18:08:32 +0000930 while (!Worklist.empty()) {
931 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
932 Worklist.pop();
Vedant Kumar8c466682018-10-05 21:44:15 +0000933 MBBJoined =
934 join(*MBB, OutLocs, InLocs, VarLocIDs, Visited, ArtificialBlocks);
Keith Walker83ebef52016-09-27 16:46:07 +0000935 Visited.insert(MBB);
Daniel Berlin72560592016-01-10 18:08:32 +0000936 if (MBBJoined) {
937 MBBJoined = false;
938 Changed = true;
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000939 // Now that we have started to extend ranges across BBs we need to
940 // examine spill instructions to see whether they spill registers that
941 // correspond to user variables.
Daniel Berlin72560592016-01-10 18:08:32 +0000942 for (auto &MI : *MBB)
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000943 OLChanged |= process(MI, OpenRanges, OutLocs, VarLocIDs, Transfers,
944 transferChanges);
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000945
946 // Add any DBG_VALUE instructions necessitated by spills.
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000947 for (auto &TR : Transfers)
948 MBB->insertAfter(MachineBasicBlock::iterator(*TR.TransferInst),
949 TR.DebugInst);
950 Transfers.clear();
Adrian Prantl6ee02c72016-05-25 22:21:12 +0000951
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000952 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
953 "OutLocs after propagating", dbgs()));
954 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
955 "InLocs after propagating", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000956
Daniel Berlin72560592016-01-10 18:08:32 +0000957 if (OLChanged) {
958 OLChanged = false;
959 for (auto s : MBB->successors())
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000960 if (OnPending.insert(s).second) {
Daniel Berlin72560592016-01-10 18:08:32 +0000961 Pending.push(BBToOrder[s]);
962 }
963 }
Vikram TV859ad292015-12-16 11:09:48 +0000964 }
965 }
Daniel Berlin72560592016-01-10 18:08:32 +0000966 Worklist.swap(Pending);
967 // At this point, pending must be empty, since it was just the empty
968 // worklist
969 assert(Pending.empty() && "Pending should be empty");
Vikram TV859ad292015-12-16 11:09:48 +0000970 }
Daniel Berlin72560592016-01-10 18:08:32 +0000971
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000972 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
973 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
Vikram TV859ad292015-12-16 11:09:48 +0000974 return Changed;
975}
976
977bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000978 if (!MF.getFunction().getSubprogram())
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000979 // LiveDebugValues will already have removed all DBG_VALUEs.
980 return false;
981
Wolfgang Piebe018bbd2017-07-19 19:36:40 +0000982 // Skip functions from NoDebug compilation units.
Matthias Braunf1caa282017-12-15 22:22:58 +0000983 if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
Wolfgang Piebe018bbd2017-07-19 19:36:40 +0000984 DICompileUnit::NoDebug)
985 return false;
986
Vikram TV859ad292015-12-16 11:09:48 +0000987 TRI = MF.getSubtarget().getRegisterInfo();
988 TII = MF.getSubtarget().getInstrInfo();
Wolfgang Pieb399dcfa2017-02-14 19:08:45 +0000989 TFI = MF.getSubtarget().getFrameLowering();
Petar Jovanovicbe2e80a2018-07-13 08:24:26 +0000990 TFI->determineCalleeSaves(MF, CalleeSavedRegs,
991 make_unique<RegScavenger>().get());
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000992 LS.initialize(MF);
Vikram TV859ad292015-12-16 11:09:48 +0000993
Adrian Prantl7f5866c2016-09-28 17:51:14 +0000994 bool Changed = ExtendRanges(MF);
Vikram TV859ad292015-12-16 11:09:48 +0000995 return Changed;
996}