blob: d0d889782a358e9c6e4c37eddd313ffabb238559 [file] [log] [blame]
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +00001//===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveDebugVariables analysis.
11//
12// Remove all DBG_VALUE instructions referencing virtual registers and replace
13// them with a data structure tracking where live user variables are kept - in a
14// virtual register or in a stack slot.
15//
16// Allow the data structure to be updated during register allocation when values
17// are moved between registers and stack slots. Finally emit new DBG_VALUE
18// instructions after register allocation is complete.
19//
20//===----------------------------------------------------------------------===//
21
22#include "LiveDebugVariables.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000023#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseMap.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000025#include "llvm/ADT/IntervalMap.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000026#include "llvm/ADT/STLExtras.h"
Robert Lougherb587c9e2017-08-03 11:54:02 +000027#include "llvm/ADT/SmallSet.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000028#include "llvm/ADT/SmallVector.h"
Devang Patelad90d3a2011-08-04 18:45:38 +000029#include "llvm/ADT/Statistic.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000030#include "llvm/ADT/StringRef.h"
Robert Lougherb587c9e2017-08-03 11:54:02 +000031#include "llvm/CodeGen/LexicalScopes.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000032#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunfa621d22017-12-13 02:51:04 +000033#include "llvm/CodeGen/LiveIntervals.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000034#include "llvm/CodeGen/MachineBasicBlock.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000035#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +000036#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000037#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +000038#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000039#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +000040#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000041#include "llvm/CodeGen/SlotIndexes.h"
David Blaikie48319232017-11-08 01:01:31 +000042#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000043#include "llvm/CodeGen/TargetOpcodes.h"
44#include "llvm/CodeGen/TargetRegisterInfo.h"
45#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000046#include "llvm/CodeGen/VirtRegMap.h"
Nico Weber0f38c602018-04-30 14:59:11 +000047#include "llvm/Config/llvm-config.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000048#include "llvm/IR/DebugInfoMetadata.h"
49#include "llvm/IR/DebugLoc.h"
50#include "llvm/IR/Function.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000051#include "llvm/IR/Metadata.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000052#include "llvm/MC/MCRegisterInfo.h"
53#include "llvm/Pass.h"
54#include "llvm/Support/Casting.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000055#include "llvm/Support/CommandLine.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000056#include "llvm/Support/Compiler.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000057#include "llvm/Support/Debug.h"
Benjamin Kramer1bfcd1f2015-03-23 19:32:43 +000058#include "llvm/Support/raw_ostream.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000059#include <algorithm>
60#include <cassert>
61#include <iterator>
David Blaikie864c5312014-04-21 20:37:07 +000062#include <memory>
Benjamin Kramer14aae012016-05-27 14:27:24 +000063#include <utility>
David Blaikie864c5312014-04-21 20:37:07 +000064
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000065using namespace llvm;
66
Matthias Braun94c49042017-05-25 21:26:32 +000067#define DEBUG_TYPE "livedebugvars"
Chandler Carruth8677f2f2014-04-22 02:02:50 +000068
Devang Patel51a666f2011-01-07 22:33:41 +000069static cl::opt<bool>
Jakob Stoklund Olesen25dc2262011-01-12 23:36:21 +000070EnableLDV("live-debug-variables", cl::init(true),
Devang Patel51a666f2011-01-07 22:33:41 +000071 cl::desc("Enable the live debug variables pass"), cl::Hidden);
72
Devang Patelad90d3a2011-08-04 18:45:38 +000073STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
Eugene Zelenko2de563a2017-08-24 21:21:39 +000074
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000075char LiveDebugVariables::ID = 0;
76
Matthias Braun94c49042017-05-25 21:26:32 +000077INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000078 "Debug Variable Analysis", false, false)
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000079INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000080INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun94c49042017-05-25 21:26:32 +000081INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000082 "Debug Variable Analysis", false, false)
83
84void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000085 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000086 AU.addRequiredTransitive<LiveIntervals>();
87 AU.setPreservesAll();
88 MachineFunctionPass::getAnalysisUsage(AU);
89}
90
Eugene Zelenko2de563a2017-08-24 21:21:39 +000091LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000092 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
93}
94
Reid Klecknerf6c62f92017-10-03 17:59:02 +000095enum : unsigned { UndefLocNo = ~0U };
96
97/// Describes a location by number along with some flags about the original
98/// usage of the location.
99class DbgValueLocation {
100public:
101 DbgValueLocation(unsigned LocNo, bool WasIndirect)
102 : LocNo(LocNo), WasIndirect(WasIndirect) {
103 static_assert(sizeof(*this) == sizeof(unsigned), "bad bitfield packing");
104 assert(locNo() == LocNo && "location truncation");
105 }
106
107 DbgValueLocation() : LocNo(0), WasIndirect(0) {}
108
109 unsigned locNo() const {
110 // Fix up the undef location number, which gets truncated.
111 return LocNo == INT_MAX ? UndefLocNo : LocNo;
112 }
113 bool wasIndirect() const { return WasIndirect; }
114 bool isUndef() const { return locNo() == UndefLocNo; }
115
116 DbgValueLocation changeLocNo(unsigned NewLocNo) const {
117 return DbgValueLocation(NewLocNo, WasIndirect);
118 }
119
Reid Kleckner3aeae942017-10-03 18:30:11 +0000120 friend inline bool operator==(const DbgValueLocation &LHS,
121 const DbgValueLocation &RHS) {
122 return LHS.LocNo == RHS.LocNo && LHS.WasIndirect == RHS.WasIndirect;
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000123 }
Reid Kleckner3aeae942017-10-03 18:30:11 +0000124
125 friend inline bool operator!=(const DbgValueLocation &LHS,
126 const DbgValueLocation &RHS) {
127 return !(LHS == RHS);
128 }
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000129
130private:
131 unsigned LocNo : 31;
132 unsigned WasIndirect : 1;
133};
134
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000135/// Map of where a user value is live, and its location.
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000136using LocMap = IntervalMap<SlotIndex, DbgValueLocation, 4>;
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000137
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000138/// Map of stack slot offsets for spilled locations.
David Stenberg66586cc2018-09-07 13:54:07 +0000139/// Non-spilled locations are not added to the map.
140using SpillOffsetMap = DenseMap<unsigned, unsigned>;
141
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000142namespace {
143
144class LDVImpl;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000145
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000146/// A user value is a part of a debug info user variable.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000147///
148/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
149/// holds part of a user variable. The part is identified by a byte offset.
150///
151/// UserValues are grouped into equivalence classes for easier searching. Two
152/// user values are related if they refer to the same variable, or if they are
153/// held by the same virtual register. The equivalence class is the transitive
154/// closure of that relation.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000155class UserValue {
Reid Klecknerca187632017-09-20 18:19:08 +0000156 const DILocalVariable *Variable; ///< The debug info variable we are part of.
157 const DIExpression *Expression; ///< Any complex address expression.
Devang Patelf827cd72011-02-04 01:43:25 +0000158 DebugLoc dl; ///< The debug location for the variable. This is
159 ///< used by dwarf writer to find lexical scope.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000160 UserValue *leader; ///< Equivalence class leader.
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000161 UserValue *next = nullptr; ///< Next value in equivalence class, or null.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000162
163 /// Numbered locations referenced by locmap.
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000164 SmallVector<MachineOperand, 4> locations;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000165
166 /// Map of slot indices where this value is live.
167 LocMap locInts;
168
Robert Lougherb587c9e2017-08-03 11:54:02 +0000169 /// Set of interval start indexes that have been trimmed to the
170 /// lexical scope.
171 SmallSet<SlotIndex, 2> trimmedDefs;
172
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000173 /// Insert a DBG_VALUE into MBB at Idx for LocNo.
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +0000174 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
David Stenberg66586cc2018-09-07 13:54:07 +0000175 SlotIndex StopIdx, DbgValueLocation Loc, bool Spilled,
176 unsigned SpillOffset, LiveIntervals &LIS,
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +0000177 const TargetInstrInfo &TII,
178 const TargetRegisterInfo &TRI);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000179
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000180 /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000181 /// is live. Returns true if any changes were made.
Mark Lacey1feb5852013-08-14 23:50:04 +0000182 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
183 LiveIntervals &LIS);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000184
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000185public:
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000186 /// Create a new UserValue.
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000187 UserValue(const DILocalVariable *var, const DIExpression *expr, DebugLoc L,
188 LocMap::Allocator &alloc)
189 : Variable(var), Expression(expr), dl(std::move(L)), leader(this),
190 locInts(alloc) {}
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000191
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000192 /// Get the leader of this value's equivalence class.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000193 UserValue *getLeader() {
194 UserValue *l = leader;
195 while (l != l->leader)
196 l = l->leader;
197 return leader = l;
198 }
199
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000200 /// Return the next UserValue in the equivalence class.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000201 UserValue *getNext() const { return next; }
202
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000203 /// Does this UserValue match the parameters?
Reid Klecknerca187632017-09-20 18:19:08 +0000204 bool match(const DILocalVariable *Var, const DIExpression *Expr,
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000205 const DILocation *IA) const {
206 // FIXME: The fragment should be part of the equivalence class, but not
207 // other things in the expression like stack values.
208 return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000209 }
210
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000211 /// Merge equivalence classes.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000212 static UserValue *merge(UserValue *L1, UserValue *L2) {
213 L2 = L2->getLeader();
214 if (!L1)
215 return L2;
216 L1 = L1->getLeader();
217 if (L1 == L2)
218 return L1;
219 // Splice L2 before L1's members.
220 UserValue *End = L2;
Richard Trieu1b96cbe2016-02-18 22:09:30 +0000221 while (End->next) {
222 End->leader = L1;
223 End = End->next;
224 }
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000225 End->leader = L1;
226 End->next = L1->next;
227 L1->next = L2;
228 return L1;
229 }
230
Mikael Holmen57db0172018-06-21 07:02:46 +0000231 /// Return the location number that matches Loc.
232 ///
233 /// For undef values we always return location number UndefLocNo without
234 /// inserting anything in locations. Since locations is a vector and the
235 /// location number is the position in the vector and UndefLocNo is ~0,
236 /// we would need a very big vector to put the value at the right position.
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000237 unsigned getLocationNo(const MachineOperand &LocMO) {
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000238 if (LocMO.isReg()) {
239 if (LocMO.getReg() == 0)
Reid Kleckner5461cbf2017-09-15 22:08:50 +0000240 return UndefLocNo;
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000241 // For register locations we dont care about use/def and other flags.
242 for (unsigned i = 0, e = locations.size(); i != e; ++i)
243 if (locations[i].isReg() &&
244 locations[i].getReg() == LocMO.getReg() &&
245 locations[i].getSubReg() == LocMO.getSubReg())
246 return i;
247 } else
248 for (unsigned i = 0, e = locations.size(); i != e; ++i)
249 if (LocMO.isIdenticalTo(locations[i]))
250 return i;
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000251 locations.push_back(LocMO);
252 // We are storing a MachineOperand outside a MachineInstr.
253 locations.back().clearParent();
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000254 // Don't store def operands.
Geoff Berry39064342017-12-29 21:01:09 +0000255 if (locations.back().isReg()) {
256 if (locations.back().isDef())
257 locations.back().setIsDead(false);
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000258 locations.back().setIsUse();
Geoff Berry39064342017-12-29 21:01:09 +0000259 }
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000260 return locations.size() - 1;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000261 }
262
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000263 /// Ensure that all virtual register locations are mapped.
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000264 void mapVirtRegs(LDVImpl *LDV);
265
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000266 /// Add a definition point to this value.
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000267 void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect) {
268 DbgValueLocation Loc(getLocationNo(LocMO), IsIndirect);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000269 // Add a singular (Idx,Idx) -> Loc mapping.
270 LocMap::iterator I = locInts.find(Idx);
271 if (!I.valid() || I.start() != Idx)
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000272 I.insert(Idx, Idx.getNextSlot(), Loc);
Jakob Stoklund Olesen79513ed2011-08-03 23:44:31 +0000273 else
274 // A later DBG_VALUE at the same SlotIndex overrides the old location.
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000275 I.setValue(Loc);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000276 }
277
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000278 /// Extend the current definition as far as possible down.
279 ///
Adrian Prantl07aadc22016-09-28 21:34:23 +0000280 /// Stop when meeting an existing def or when leaving the live
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000281 /// range of VNI. End points where VNI is no longer live are added to Kills.
282 ///
283 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
284 /// data-flow analysis to propagate them beyond basic block boundaries.
285 ///
286 /// \param Idx Starting point for the definition.
287 /// \param Loc Location number to propagate.
288 /// \param LR Restrict liveness to where LR has the value VNI. May be null.
289 /// \param VNI When LR is not null, this is the value to restrict to.
290 /// \param [out] Kills Append end points of VNI's live range to Kills.
291 /// \param LIS Live intervals analysis.
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000292 void extendDef(SlotIndex Idx, DbgValueLocation Loc,
Matthias Braun4f3b5e82013-10-10 21:29:02 +0000293 LiveRange *LR, const VNInfo *VNI,
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000294 SmallVectorImpl<SlotIndex> *Kills,
Adrian Prantl07aadc22016-09-28 21:34:23 +0000295 LiveIntervals &LIS);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000296
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000297 /// The value in LI/LocNo may be copies to other registers. Determine if
298 /// any of the copies are available at the kill points, and add defs if
299 /// possible.
300 ///
301 /// \param LI Scan for copies of the value in LI->reg.
302 /// \param LocNo Location number of LI->reg.
303 /// \param WasIndirect Indicates if the original use of LI->reg was indirect
304 /// \param Kills Points where the range of LocNo could be extended.
305 /// \param [in,out] NewDefs Append (Idx, LocNo) of inserted defs here.
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000306 void addDefsFromCopies(
307 LiveInterval *LI, unsigned LocNo, bool WasIndirect,
308 const SmallVectorImpl<SlotIndex> &Kills,
309 SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
310 MachineRegisterInfo &MRI, LiveIntervals &LIS);
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000311
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000312 /// Compute the live intervals of all locations after collecting all their
313 /// def points.
Jakob Stoklund Olesene8a0a122012-06-22 17:15:32 +0000314 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
Robert Lougherb587c9e2017-08-03 11:54:02 +0000315 LiveIntervals &LIS, LexicalScopes &LS);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000316
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000317 /// Replace OldReg ranges with NewRegs ranges where NewRegs is
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000318 /// live. Returns true if any changes were made.
Fangrui Song7d882862018-07-16 18:51:40 +0000319 bool splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
Mark Lacey1feb5852013-08-14 23:50:04 +0000320 LiveIntervals &LIS);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000321
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000322 /// Rewrite virtual register locations according to the provided virtual
323 /// register map. Record the stack slot offsets for the locations that
324 /// were spilled.
David Stenberg66586cc2018-09-07 13:54:07 +0000325 void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
326 const TargetInstrInfo &TII,
327 const TargetRegisterInfo &TRI,
328 SpillOffsetMap &SpillOffsets);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000329
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000330 /// Recreate DBG_VALUE instruction from data structures.
Reid Klecknerca187632017-09-20 18:19:08 +0000331 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +0000332 const TargetInstrInfo &TII,
333 const TargetRegisterInfo &TRI,
David Stenberg66586cc2018-09-07 13:54:07 +0000334 const SpillOffsetMap &SpillOffsets);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000335
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000336 /// Return DebugLoc of this UserValue.
Devang Patel3a2d80d2011-09-13 18:40:53 +0000337 DebugLoc getDebugLoc() { return dl;}
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000338
Eric Christopher9656d2d2015-02-27 00:11:34 +0000339 void print(raw_ostream &, const TargetRegisterInfo *);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000340};
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000341
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000342/// Implementation of the LiveDebugVariables pass.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000343class LDVImpl {
344 LiveDebugVariables &pass;
345 LocMap::Allocator allocator;
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000346 MachineFunction *MF = nullptr;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000347 LiveIntervals *LIS;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000348 const TargetRegisterInfo *TRI;
349
Manman Renf0986202013-02-13 20:23:48 +0000350 /// Whether emitDebugValues is called.
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000351 bool EmitDone = false;
352
Manman Renf0986202013-02-13 20:23:48 +0000353 /// Whether the machine function is modified during the pass.
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000354 bool ModifiedMF = false;
Manman Renf0986202013-02-13 20:23:48 +0000355
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000356 /// All allocated UserValue instances.
David Blaikie864c5312014-04-21 20:37:07 +0000357 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000358
359 /// Map virtual register to eq class leader.
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000360 using VRMap = DenseMap<unsigned, UserValue *>;
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000361 VRMap virtRegToEqClass;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000362
363 /// Map user variable to eq class leader.
Reid Klecknerca187632017-09-20 18:19:08 +0000364 using UVMap = DenseMap<const DILocalVariable *, UserValue *>;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000365 UVMap userVarMap;
366
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000367 /// Find or create a UserValue.
Reid Klecknerca187632017-09-20 18:19:08 +0000368 UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr,
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000369 const DebugLoc &DL);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000370
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000371 /// Find the EC leader for VirtReg or null.
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000372 UserValue *lookupVirtReg(unsigned VirtReg);
373
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000374 /// Add DBG_VALUE instruction to our maps.
375 ///
376 /// \param MI DBG_VALUE instruction
377 /// \param Idx Last valid SLotIndex before instruction.
378 ///
379 /// \returns True if the DBG_VALUE instruction should be deleted.
Duncan P. N. Exon Smith8a1fda12016-06-30 23:13:38 +0000380 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000381
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000382 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
383 /// for each instruction.
384 ///
385 /// \param mf MachineFunction to be scanned.
386 ///
387 /// \returns True if any debug values were found.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000388 bool collectDebugValues(MachineFunction &mf);
389
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000390 /// Compute the live intervals of all user values after collecting all
391 /// their def points.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000392 void computeIntervals();
393
394public:
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000395 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
396
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000397 bool runOnMachineFunction(MachineFunction &mf);
398
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000399 /// Release all memory.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000400 void clear() {
David Blaikiee27d5a02014-07-25 16:10:16 +0000401 MF = nullptr;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000402 userValues.clear();
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000403 virtRegToEqClass.clear();
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000404 userVarMap.clear();
Manman Renf0986202013-02-13 20:23:48 +0000405 // Make sure we call emitDebugValues if the machine function was modified.
406 assert((!ModifiedMF || EmitDone) &&
407 "Dbg values are not emitted in LDV");
408 EmitDone = false;
409 ModifiedMF = false;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000410 }
411
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000412 /// Map virtual register to an equivalence class.
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000413 void mapVirtReg(unsigned VirtReg, UserValue *EC);
414
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000415 /// Replace all references to OldReg with NewRegs.
Mark Lacey1feb5852013-08-14 23:50:04 +0000416 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000417
Hsiangkai Wang5f388802018-11-30 08:07:24 +0000418 /// Recreate DBG_VALUE instruction from data structures.
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000419 void emitDebugValues(VirtRegMap *VRM);
420
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000421 void print(raw_ostream&);
422};
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000423
424} // end anonymous namespace
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000425
Aaron Ballman1d03d382017-10-15 14:32:27 +0000426#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Krameraf18e012016-06-12 15:39:02 +0000427static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
Duncan P. N. Exon Smith79666c22015-04-14 02:09:32 +0000428 const LLVMContext &Ctx) {
429 if (!DL)
430 return;
431
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +0000432 auto *Scope = cast<DIScope>(DL.getScope());
Duncan P. N. Exon Smith79666c22015-04-14 02:09:32 +0000433 // Omit the directory, because it's likely to be long and uninteresting.
Duncan P. N. Exon Smith9c1aa1c2015-04-16 01:37:00 +0000434 CommentOS << Scope->getFilename();
Duncan P. N. Exon Smith79666c22015-04-14 02:09:32 +0000435 CommentOS << ':' << DL.getLine();
436 if (DL.getCol() != 0)
437 CommentOS << ':' << DL.getCol();
438
439 DebugLoc InlinedAtDL = DL.getInlinedAt();
440 if (!InlinedAtDL)
441 return;
442
443 CommentOS << " @[ ";
444 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
445 CommentOS << " ]";
446}
447
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +0000448static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
449 const DILocation *DL) {
Duncan P. N. Exon Smith79666c22015-04-14 02:09:32 +0000450 const LLVMContext &Ctx = V->getContext();
451 StringRef Res = V->getName();
452 if (!Res.empty())
453 OS << Res << "," << V->getLine();
Duncan P. N. Exon Smith88e419d2015-04-15 22:29:27 +0000454 if (auto *InlinedAt = DL->getInlinedAt()) {
Duncan P. N. Exon Smith79666c22015-04-14 02:09:32 +0000455 if (DebugLoc InlinedAtDL = InlinedAt) {
456 OS << " @[";
457 printDebugLoc(InlinedAtDL, OS, Ctx);
458 OS << "]";
459 }
460 }
461}
462
Eric Christopher9656d2d2015-02-27 00:11:34 +0000463void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +0000464 auto *DV = cast<DILocalVariable>(Variable);
Frederic Riss7d05a0f2014-08-07 20:04:00 +0000465 OS << "!\"";
Duncan P. N. Exon Smith88e419d2015-04-15 22:29:27 +0000466 printExtendedName(OS, DV, dl);
Duncan P. N. Exon Smith79666c22015-04-14 02:09:32 +0000467
Devang Patela2b552d2011-08-09 01:03:35 +0000468 OS << "\"\t";
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000469 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
470 OS << " [" << I.start() << ';' << I.stop() << "):";
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000471 if (I.value().isUndef())
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000472 OS << "undef";
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000473 else {
474 OS << I.value().locNo();
475 if (I.value().wasIndirect())
476 OS << " ind";
477 }
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000478 }
Jakob Stoklund Olesene77150b2011-05-06 17:59:59 +0000479 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
480 OS << " Loc" << i << '=';
Eric Christopher9656d2d2015-02-27 00:11:34 +0000481 locations[i].print(OS, TRI);
Jakob Stoklund Olesene77150b2011-05-06 17:59:59 +0000482 }
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000483 OS << '\n';
484}
485
486void LDVImpl::print(raw_ostream &OS) {
487 OS << "********** DEBUG VARIABLES **********\n";
488 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
Eric Christopher9656d2d2015-02-27 00:11:34 +0000489 userValues[i]->print(OS, TRI);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000490}
Florian Hahn8b712792017-07-31 10:07:49 +0000491#endif
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000492
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000493void UserValue::mapVirtRegs(LDVImpl *LDV) {
494 for (unsigned i = 0, e = locations.size(); i != e; ++i)
495 if (locations[i].isReg() &&
496 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
497 LDV->mapVirtReg(locations[i].getReg(), this);
498}
499
Reid Klecknerca187632017-09-20 18:19:08 +0000500UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000501 const DIExpression *Expr, const DebugLoc &DL) {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000502 UserValue *&Leader = userVarMap[Var];
503 if (Leader) {
504 UserValue *UV = Leader->getLeader();
505 Leader = UV;
506 for (; UV; UV = UV->getNext())
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000507 if (UV->match(Var, Expr, DL->getInlinedAt()))
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000508 return UV;
509 }
510
David Blaikie864c5312014-04-21 20:37:07 +0000511 userValues.push_back(
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000512 llvm::make_unique<UserValue>(Var, Expr, DL, allocator));
David Blaikie864c5312014-04-21 20:37:07 +0000513 UserValue *UV = userValues.back().get();
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000514 Leader = UserValue::merge(Leader, UV);
515 return UV;
516}
517
518void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
519 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000520 UserValue *&Leader = virtRegToEqClass[VirtReg];
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000521 Leader = UserValue::merge(Leader, EC);
522}
523
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000524UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000525 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000526 return UV->getLeader();
Craig Topper4ba84432014-04-14 00:51:57 +0000527 return nullptr;
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000528}
529
Duncan P. N. Exon Smith8a1fda12016-06-30 23:13:38 +0000530bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000531 // DBG_VALUE loc, offset, variable
Duncan P. N. Exon Smith8a1fda12016-06-30 23:13:38 +0000532 if (MI.getNumOperands() != 4 ||
533 !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
534 !MI.getOperand(2).isMetadata()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000535 LLVM_DEBUG(dbgs() << "Can't handle " << MI);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000536 return false;
537 }
538
Bjorn Pettersson783006e2018-03-06 08:47:07 +0000539 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
540 // register that hasn't been defined yet. If we do not remove those here, then
541 // the re-insertion of the DBG_VALUE instruction after register allocation
542 // will be incorrect.
543 // TODO: If earlier passes are corrected to generate sane debug information
544 // (and if the machine verifier is improved to catch this), then these checks
545 // could be removed or replaced by asserts.
546 bool Discard = false;
547 if (MI.getOperand(0).isReg() &&
548 TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg())) {
549 const unsigned Reg = MI.getOperand(0).getReg();
550 if (!LIS->hasInterval(Reg)) {
551 // The DBG_VALUE is described by a virtual register that does not have a
552 // live interval. Discard the DBG_VALUE.
553 Discard = true;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000554 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
555 << " " << MI);
Bjorn Pettersson783006e2018-03-06 08:47:07 +0000556 } else {
557 // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
558 // is defined dead at Idx (where Idx is the slot index for the instruction
559 // preceeding the DBG_VALUE).
560 const LiveInterval &LI = LIS->getInterval(Reg);
561 LiveQueryResult LRQ = LI.Query(Idx);
562 if (!LRQ.valueOutOrDead()) {
563 // We have found a DBG_VALUE with the value in a virtual register that
564 // is not live. Discard the DBG_VALUE.
565 Discard = true;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000566 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
567 << " " << MI);
Bjorn Pettersson783006e2018-03-06 08:47:07 +0000568 }
569 }
570 }
571
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000572 // Get or create the UserValue for (variable,offset) here.
Reid Klecknerca187632017-09-20 18:19:08 +0000573 bool IsIndirect = MI.getOperand(1).isImm();
Adrian Prantl24019d62017-07-28 23:06:50 +0000574 if (IsIndirect)
575 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
Reid Klecknerca187632017-09-20 18:19:08 +0000576 const DILocalVariable *Var = MI.getDebugVariable();
577 const DIExpression *Expr = MI.getDebugExpression();
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000578 UserValue *UV =
579 getUserValue(Var, Expr, MI.getDebugLoc());
Bjorn Pettersson783006e2018-03-06 08:47:07 +0000580 if (!Discard)
581 UV->addDef(Idx, MI.getOperand(0), IsIndirect);
Bjorn Pettersson866cf8f2018-03-06 13:23:28 +0000582 else {
583 MachineOperand MO = MachineOperand::CreateReg(0U, false);
584 MO.setIsDebug();
585 UV->addDef(Idx, MO, false);
586 }
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000587 return true;
588}
589
590bool LDVImpl::collectDebugValues(MachineFunction &mf) {
591 bool Changed = false;
592 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
593 ++MFI) {
Duncan P. N. Exon Smith3f2c43f2015-10-09 19:13:58 +0000594 MachineBasicBlock *MBB = &*MFI;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000595 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
596 MBBI != MBBE;) {
Hsiangkai Wang10377f62018-09-05 05:58:53 +0000597 // Use the first debug instruction in the sequence to get a SlotIndex
598 // for following consecutive debug instructions.
599 if (!MBBI->isDebugInstr()) {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000600 ++MBBI;
601 continue;
602 }
Hsiangkai Wang10377f62018-09-05 05:58:53 +0000603 // Debug instructions has no slot index. Use the previous
604 // non-debug instruction's SlotIndex as its SlotIndex.
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000605 SlotIndex Idx =
606 MBBI == MBB->begin()
607 ? LIS->getMBBStartIdx(MBB)
608 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
Hsiangkai Wang10377f62018-09-05 05:58:53 +0000609 // Handle consecutive debug instructions with the same slot index.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000610 do {
Hsiangkai Wang10377f62018-09-05 05:58:53 +0000611 // Only handle DBG_VALUE in handleDebugValue(). Skip all other
612 // kinds of debug instructions.
613 if (MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000614 MBBI = MBB->erase(MBBI);
615 Changed = true;
616 } else
617 ++MBBI;
Hsiangkai Wang10377f62018-09-05 05:58:53 +0000618 } while (MBBI != MBBE && MBBI->isDebugInstr());
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000619 }
620 }
621 return Changed;
622}
623
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000624void UserValue::extendDef(SlotIndex Idx, DbgValueLocation Loc, LiveRange *LR,
Adrian Prantl9e02fe52015-12-21 20:03:00 +0000625 const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
Adrian Prantl07aadc22016-09-28 21:34:23 +0000626 LiveIntervals &LIS) {
Adrian Prantl9e02fe52015-12-21 20:03:00 +0000627 SlotIndex Start = Idx;
628 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
629 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
630 LocMap::iterator I = locInts.find(Start);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000631
Adrian Prantl9e02fe52015-12-21 20:03:00 +0000632 // Limit to VNI's live range.
633 bool ToEnd = true;
634 if (LR && VNI) {
635 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
636 if (!Segment || Segment->valno != VNI) {
637 if (Kills)
638 Kills->push_back(Start);
639 return;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000640 }
Richard Trieu1b96cbe2016-02-18 22:09:30 +0000641 if (Segment->end < Stop) {
642 Stop = Segment->end;
643 ToEnd = false;
644 }
Adrian Prantl9e02fe52015-12-21 20:03:00 +0000645 }
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000646
Adrian Prantl9e02fe52015-12-21 20:03:00 +0000647 // There could already be a short def at Start.
648 if (I.valid() && I.start() <= Start) {
649 // Stop when meeting a different location or an already extended interval.
650 Start = Start.getNextSlot();
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000651 if (I.value() != Loc || I.stop() != Start)
Adrian Prantl9e02fe52015-12-21 20:03:00 +0000652 return;
653 // This is a one-slot placeholder. Just skip it.
654 ++I;
655 }
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000656
Adrian Prantl9e02fe52015-12-21 20:03:00 +0000657 // Limited by the next def.
Richard Trieu1b96cbe2016-02-18 22:09:30 +0000658 if (I.valid() && I.start() < Stop) {
659 Stop = I.start();
660 ToEnd = false;
661 }
Adrian Prantl9e02fe52015-12-21 20:03:00 +0000662 // Limited by VNI's live range.
663 else if (!ToEnd && Kills)
664 Kills->push_back(Stop);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000665
Adrian Prantl9e02fe52015-12-21 20:03:00 +0000666 if (Start < Stop)
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000667 I.insert(Start, Stop, Loc);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000668}
669
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000670void UserValue::addDefsFromCopies(
671 LiveInterval *LI, unsigned LocNo, bool WasIndirect,
672 const SmallVectorImpl<SlotIndex> &Kills,
673 SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
674 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000675 if (Kills.empty())
676 return;
677 // Don't track copies from physregs, there are too many uses.
678 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
679 return;
680
681 // Collect all the (vreg, valno) pairs that are copies of LI.
682 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
Owen Anderson92fca732014-03-17 19:36:09 +0000683 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
684 MachineInstr *MI = MO.getParent();
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000685 // Copies of the full value.
Owen Anderson92fca732014-03-17 19:36:09 +0000686 if (MO.getSubReg() || !MI->isCopy())
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000687 continue;
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000688 unsigned DstReg = MI->getOperand(0).getReg();
689
Jakob Stoklund Olesen28cf1152011-03-22 22:33:08 +0000690 // Don't follow copies to physregs. These are usually setting up call
691 // arguments, and the argument registers are always call clobbered. We are
692 // better off in the source register which could be a callee-saved register,
693 // or it could be spilled.
694 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
695 continue;
696
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000697 // Is LocNo extended to reach this copy? If not, another def may be blocking
698 // it, or we are looking at a wrong value of LI.
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000699 SlotIndex Idx = LIS.getInstructionIndex(*MI);
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000700 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000701 if (!I.valid() || I.value().locNo() != LocNo)
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000702 continue;
703
704 if (!LIS.hasInterval(DstReg))
705 continue;
706 LiveInterval *DstLI = &LIS.getInterval(DstReg);
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000707 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
708 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000709 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
710 }
711
712 if (CopyValues.empty())
713 return;
714
Nicola Zaghen0818e782018-05-14 12:53:11 +0000715 LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI
716 << '\n');
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000717
718 // Try to add defs of the copied values for each kill point.
719 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
720 SlotIndex Idx = Kills[i];
721 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
722 LiveInterval *DstLI = CopyValues[j].first;
723 const VNInfo *DstVNI = CopyValues[j].second;
724 if (DstLI->getVNInfoAt(Idx) != DstVNI)
725 continue;
726 // Check that there isn't already a def at Idx
727 LocMap::iterator I = locInts.find(Idx);
728 if (I.valid() && I.start() <= Idx)
729 continue;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000730 LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
731 << DstVNI->id << " in " << *DstLI << '\n');
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000732 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
733 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
734 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000735 DbgValueLocation NewLoc(LocNo, WasIndirect);
736 I.insert(Idx, Idx.getNextSlot(), NewLoc);
737 NewDefs.push_back(std::make_pair(Idx, NewLoc));
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000738 break;
739 }
740 }
741}
742
Robert Lougherb587c9e2017-08-03 11:54:02 +0000743void UserValue::computeIntervals(MachineRegisterInfo &MRI,
744 const TargetRegisterInfo &TRI,
745 LiveIntervals &LIS, LexicalScopes &LS) {
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000746 SmallVector<std::pair<SlotIndex, DbgValueLocation>, 16> Defs;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000747
748 // Collect all defs to be extended (Skipping undefs).
749 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000750 if (!I.value().isUndef())
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000751 Defs.push_back(std::make_pair(I.start(), I.value()));
752
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000753 // Extend all defs, and possibly add new ones along the way.
754 for (unsigned i = 0; i != Defs.size(); ++i) {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000755 SlotIndex Idx = Defs[i].first;
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000756 DbgValueLocation Loc = Defs[i].second;
757 const MachineOperand &LocMO = locations[Loc.locNo()];
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000758
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000759 if (!LocMO.isReg()) {
760 extendDef(Idx, Loc, nullptr, nullptr, nullptr, LIS);
Jakob Stoklund Olesene8a0a122012-06-22 17:15:32 +0000761 continue;
762 }
763
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000764 // Register locations are constrained to where the register value is live.
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000765 if (TargetRegisterInfo::isVirtualRegister(LocMO.getReg())) {
Craig Topper4ba84432014-04-14 00:51:57 +0000766 LiveInterval *LI = nullptr;
767 const VNInfo *VNI = nullptr;
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000768 if (LIS.hasInterval(LocMO.getReg())) {
769 LI = &LIS.getInterval(LocMO.getReg());
Jakob Stoklund Olesenb1509302012-06-22 18:51:35 +0000770 VNI = LI->getVNInfoAt(Idx);
771 }
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000772 SmallVector<SlotIndex, 16> Kills;
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000773 extendDef(Idx, Loc, LI, VNI, &Kills, LIS);
Bjorn Pettersson48bfbb52018-08-25 10:02:03 +0000774 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
775 // if the original location for example is %vreg0:sub_hi, and we find a
776 // full register copy in addDefsFromCopies (at the moment it only handles
777 // full register copies), then we must add the sub1 sub-register index to
778 // the new location. However, that is only possible if the new virtual
779 // register is of the same regclass (or if there is an equivalent
780 // sub-register in that regclass). For now, simply skip handling copies if
781 // a sub-register is involved.
782 if (LI && !LocMO.getSubReg())
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000783 addDefsFromCopies(LI, Loc.locNo(), Loc.wasIndirect(), Kills, Defs, MRI,
784 LIS);
Jakob Stoklund Olesene8a0a122012-06-22 17:15:32 +0000785 continue;
786 }
787
Bjorn Pettersson4b8314b2017-09-28 13:10:06 +0000788 // For physregs, we only mark the start slot idx. DwarfDebug will see it
789 // as if the DBG_VALUE is valid up until the end of the basic block, or
790 // the next def of the physical register. So we do not need to extend the
791 // range. It might actually happen that the DBG_VALUE is the last use of
792 // the physical register (e.g. if this is an unused input argument to a
793 // function).
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000794 }
795
Robert Lougherb587c9e2017-08-03 11:54:02 +0000796 // The computed intervals may extend beyond the range of the debug
797 // location's lexical scope. In this case, splitting of an interval
798 // can result in an interval outside of the scope being created,
799 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
800 // this, trim the intervals to the lexical scope.
801
802 LexicalScope *Scope = LS.findLexicalScope(dl);
803 if (!Scope)
804 return;
805
806 SlotIndex PrevEnd;
807 LocMap::iterator I = locInts.begin();
808
809 // Iterate over the lexical scope ranges. Each time round the loop
810 // we check the intervals for overlap with the end of the previous
811 // range and the start of the next. The first range is handled as
812 // a special case where there is no PrevEnd.
813 for (const InsnRange &Range : Scope->getRanges()) {
814 SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
815 SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
816
817 // At the start of each iteration I has been advanced so that
818 // I.stop() >= PrevEnd. Check for overlap.
819 if (PrevEnd && I.start() < PrevEnd) {
820 SlotIndex IStop = I.stop();
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000821 DbgValueLocation Loc = I.value();
Robert Lougherb587c9e2017-08-03 11:54:02 +0000822
823 // Stop overlaps previous end - trim the end of the interval to
824 // the scope range.
825 I.setStopUnchecked(PrevEnd);
826 ++I;
827
828 // If the interval also overlaps the start of the "next" (i.e.
829 // current) range create a new interval for the remainder (which
830 // may be further trimmed).
831 if (RStart < IStop)
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000832 I.insert(RStart, IStop, Loc);
Robert Lougherb587c9e2017-08-03 11:54:02 +0000833 }
834
835 // Advance I so that I.stop() >= RStart, and check for overlap.
836 I.advanceTo(RStart);
837 if (!I.valid())
838 return;
839
840 if (I.start() < RStart) {
841 // Interval start overlaps range - trim to the scope range.
842 I.setStartUnchecked(RStart);
843 // Remember that this interval was trimmed.
844 trimmedDefs.insert(RStart);
845 }
846
847 // The end of a lexical scope range is the last instruction in the
848 // range. To convert to an interval we need the index of the
849 // instruction after it.
850 REnd = REnd.getNextIndex();
851
852 // Advance I to first interval outside current range.
853 I.advanceTo(REnd);
854 if (!I.valid())
855 return;
856
857 PrevEnd = REnd;
858 }
859
860 // Check for overlap with end of final range.
861 if (PrevEnd && I.start() < PrevEnd)
862 I.setStopUnchecked(PrevEnd);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000863}
864
865void LDVImpl::computeIntervals() {
Robert Lougherb587c9e2017-08-03 11:54:02 +0000866 LexicalScopes LS;
867 LS.initialize(*MF);
868
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000869 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
Robert Lougherb587c9e2017-08-03 11:54:02 +0000870 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000871 userValues[i]->mapVirtRegs(this);
872 }
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000873}
874
875bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
David Blaikiee27d5a02014-07-25 16:10:16 +0000876 clear();
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000877 MF = &mf;
878 LIS = &pass.getAnalysis<LiveIntervals>();
Eric Christopher60355182014-08-05 02:39:49 +0000879 TRI = mf.getSubtarget().getRegisterInfo();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000880 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
881 << mf.getName() << " **********\n");
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000882
883 bool Changed = collectDebugValues(mf);
884 computeIntervals();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000885 LLVM_DEBUG(print(dbgs()));
Manman Renf0986202013-02-13 20:23:48 +0000886 ModifiedMF = Changed;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000887 return Changed;
888}
889
David Blaikiee27d5a02014-07-25 16:10:16 +0000890static void removeDebugValues(MachineFunction &mf) {
891 for (MachineBasicBlock &MBB : mf) {
892 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
893 if (!MBBI->isDebugValue()) {
894 ++MBBI;
895 continue;
896 }
897 MBBI = MBB.erase(MBBI);
898 }
899 }
900}
901
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +0000902bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
Devang Patel51a666f2011-01-07 22:33:41 +0000903 if (!EnableLDV)
904 return false;
Matthias Braund3181392017-12-15 22:22:58 +0000905 if (!mf.getFunction().getSubprogram()) {
David Blaikiee27d5a02014-07-25 16:10:16 +0000906 removeDebugValues(mf);
907 return false;
908 }
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000909 if (!pImpl)
910 pImpl = new LDVImpl(this);
Manman Renf0986202013-02-13 20:23:48 +0000911 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000912}
913
914void LiveDebugVariables::releaseMemory() {
Manman Renf0986202013-02-13 20:23:48 +0000915 if (pImpl)
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000916 static_cast<LDVImpl*>(pImpl)->clear();
917}
918
919LiveDebugVariables::~LiveDebugVariables() {
920 if (pImpl)
921 delete static_cast<LDVImpl*>(pImpl);
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +0000922}
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000923
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000924//===----------------------------------------------------------------------===//
925// Live Range Splitting
926//===----------------------------------------------------------------------===//
927
928bool
Mark Lacey1feb5852013-08-14 23:50:04 +0000929UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
930 LiveIntervals& LIS) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000931 LLVM_DEBUG({
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000932 dbgs() << "Splitting Loc" << OldLocNo << '\t';
Craig Topper4ba84432014-04-14 00:51:57 +0000933 print(dbgs(), nullptr);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000934 });
935 bool DidChange = false;
936 LocMap::iterator LocMapI;
937 LocMapI.setMap(locInts);
938 for (unsigned i = 0; i != NewRegs.size(); ++i) {
Mark Lacey1feb5852013-08-14 23:50:04 +0000939 LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000940 if (LI->empty())
941 continue;
942
943 // Don't allocate the new LocNo until it is needed.
Reid Kleckner5461cbf2017-09-15 22:08:50 +0000944 unsigned NewLocNo = UndefLocNo;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000945
946 // Iterate over the overlaps between locInts and LI.
947 LocMapI.find(LI->beginIndex());
948 if (!LocMapI.valid())
949 continue;
950 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
951 LiveInterval::iterator LIE = LI->end();
952 while (LocMapI.valid() && LII != LIE) {
953 // At this point, we know that LocMapI.stop() > LII->start.
954 LII = LI->advanceTo(LII, LocMapI.start());
955 if (LII == LIE)
956 break;
957
958 // Now LII->end > LocMapI.start(). Do we have an overlap?
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000959 if (LocMapI.value().locNo() == OldLocNo && LII->start < LocMapI.stop()) {
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000960 // Overlapping correct location. Allocate NewLocNo now.
Reid Kleckner5461cbf2017-09-15 22:08:50 +0000961 if (NewLocNo == UndefLocNo) {
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000962 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
963 MO.setSubReg(locations[OldLocNo].getSubReg());
964 NewLocNo = getLocationNo(MO);
965 DidChange = true;
966 }
967
968 SlotIndex LStart = LocMapI.start();
969 SlotIndex LStop = LocMapI.stop();
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000970 DbgValueLocation OldLoc = LocMapI.value();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000971
972 // Trim LocMapI down to the LII overlap.
973 if (LStart < LII->start)
974 LocMapI.setStartUnchecked(LII->start);
975 if (LStop > LII->end)
976 LocMapI.setStopUnchecked(LII->end);
977
978 // Change the value in the overlap. This may trigger coalescing.
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000979 LocMapI.setValue(OldLoc.changeLocNo(NewLocNo));
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000980
981 // Re-insert any removed OldLocNo ranges.
982 if (LStart < LocMapI.start()) {
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000983 LocMapI.insert(LStart, LocMapI.start(), OldLoc);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000984 ++LocMapI;
985 assert(LocMapI.valid() && "Unexpected coalescing");
986 }
987 if (LStop > LocMapI.stop()) {
988 ++LocMapI;
Reid Klecknerf6c62f92017-10-03 17:59:02 +0000989 LocMapI.insert(LII->end, LStop, OldLoc);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000990 --LocMapI;
991 }
992 }
993
994 // Advance to the next overlap.
995 if (LII->end < LocMapI.stop()) {
996 if (++LII == LIE)
997 break;
998 LocMapI.advanceTo(LII->start);
999 } else {
1000 ++LocMapI;
1001 if (!LocMapI.valid())
1002 break;
1003 LII = LI->advanceTo(LII, LocMapI.start());
1004 }
1005 }
1006 }
1007
1008 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
1009 locations.erase(locations.begin() + OldLocNo);
1010 LocMapI.goToBegin();
1011 while (LocMapI.valid()) {
Reid Klecknerf6c62f92017-10-03 17:59:02 +00001012 DbgValueLocation v = LocMapI.value();
1013 if (v.locNo() == OldLocNo) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001014 LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
1015 << LocMapI.stop() << ")\n");
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001016 LocMapI.erase();
1017 } else {
Mikael Holmen57db0172018-06-21 07:02:46 +00001018 // Undef values always have location number UndefLocNo, so don't change
1019 // locNo in that case. See getLocationNo().
1020 if (!v.isUndef() && v.locNo() > OldLocNo)
Reid Klecknerf6c62f92017-10-03 17:59:02 +00001021 LocMapI.setValueUnchecked(v.changeLocNo(v.locNo() - 1));
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001022 ++LocMapI;
1023 }
1024 }
1025
Nicola Zaghen0818e782018-05-14 12:53:11 +00001026 LLVM_DEBUG({
1027 dbgs() << "Split result: \t";
1028 print(dbgs(), nullptr);
1029 });
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001030 return DidChange;
1031}
1032
1033bool
Mark Lacey1feb5852013-08-14 23:50:04 +00001034UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
1035 LiveIntervals &LIS) {
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001036 bool DidChange = false;
Jakob Stoklund Olesen6212f9a2011-05-06 19:31:19 +00001037 // Split locations referring to OldReg. Iterate backwards so splitLocation can
Eric Christopher7cc51772012-03-15 21:33:35 +00001038 // safely erase unused locations.
Jakob Stoklund Olesen6212f9a2011-05-06 19:31:19 +00001039 for (unsigned i = locations.size(); i ; --i) {
1040 unsigned LocNo = i-1;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001041 const MachineOperand *Loc = &locations[LocNo];
1042 if (!Loc->isReg() || Loc->getReg() != OldReg)
1043 continue;
Mark Lacey1feb5852013-08-14 23:50:04 +00001044 DidChange |= splitLocation(LocNo, NewRegs, LIS);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001045 }
1046 return DidChange;
1047}
1048
Mark Lacey1feb5852013-08-14 23:50:04 +00001049void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001050 bool DidChange = false;
1051 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
Mark Lacey1feb5852013-08-14 23:50:04 +00001052 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001053
1054 if (!DidChange)
1055 return;
1056
1057 // Map all of the new virtual registers.
1058 UserValue *UV = lookupVirtReg(OldReg);
1059 for (unsigned i = 0; i != NewRegs.size(); ++i)
Mark Lacey1feb5852013-08-14 23:50:04 +00001060 mapVirtReg(NewRegs[i], UV);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001061}
1062
1063void LiveDebugVariables::
Mark Lacey1feb5852013-08-14 23:50:04 +00001064splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001065 if (pImpl)
1066 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
1067}
1068
David Stenberg66586cc2018-09-07 13:54:07 +00001069void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1070 const TargetInstrInfo &TII,
1071 const TargetRegisterInfo &TRI,
1072 SpillOffsetMap &SpillOffsets) {
Reid Klecknercf0cb492017-09-20 17:32:54 +00001073 // Build a set of new locations with new numbers so we can coalesce our
1074 // IntervalMap if two vreg intervals collapse to the same physical location.
1075 // Use MapVector instead of SetVector because MapVector::insert returns the
Reid Klecknerca187632017-09-20 18:19:08 +00001076 // position of the previously or newly inserted element. The boolean value
1077 // tracks if the location was produced by a spill.
1078 // FIXME: This will be problematic if we ever support direct and indirect
1079 // frame index locations, i.e. expressing both variables in memory and
1080 // 'int x, *px = &x'. The "spilled" bit must become part of the location.
David Stenberg66586cc2018-09-07 13:54:07 +00001081 MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
Reid Klecknercf0cb492017-09-20 17:32:54 +00001082 SmallVector<unsigned, 4> LocNoMap(locations.size());
1083 for (unsigned I = 0, E = locations.size(); I != E; ++I) {
Reid Klecknerca187632017-09-20 18:19:08 +00001084 bool Spilled = false;
David Stenberg66586cc2018-09-07 13:54:07 +00001085 unsigned SpillOffset = 0;
Reid Klecknercf0cb492017-09-20 17:32:54 +00001086 MachineOperand Loc = locations[I];
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001087 // Only virtual registers are rewritten.
Reid Klecknercf0cb492017-09-20 17:32:54 +00001088 if (Loc.isReg() && Loc.getReg() &&
1089 TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
1090 unsigned VirtReg = Loc.getReg();
1091 if (VRM.isAssignedReg(VirtReg) &&
1092 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
1093 // This can create a %noreg operand in rare cases when the sub-register
1094 // index is no longer available. That means the user value is in a
1095 // non-existent sub-register, and %noreg is exactly what we want.
1096 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1097 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
David Stenberg66586cc2018-09-07 13:54:07 +00001098 // Retrieve the stack slot offset.
1099 unsigned SpillSize;
1100 const MachineRegisterInfo &MRI = MF.getRegInfo();
1101 const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
1102 bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
1103 SpillOffset, MF);
1104
1105 // FIXME: Invalidate the location if the offset couldn't be calculated.
1106 (void)Success;
1107
Reid Klecknercf0cb492017-09-20 17:32:54 +00001108 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
Reid Klecknerca187632017-09-20 18:19:08 +00001109 Spilled = true;
Reid Klecknercf0cb492017-09-20 17:32:54 +00001110 } else {
1111 Loc.setReg(0);
1112 Loc.setSubReg(0);
1113 }
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001114 }
Reid Klecknercf0cb492017-09-20 17:32:54 +00001115
1116 // Insert this location if it doesn't already exist and record a mapping
1117 // from the old number to the new number.
David Stenberg66586cc2018-09-07 13:54:07 +00001118 auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
Reid Klecknerca187632017-09-20 18:19:08 +00001119 unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1120 LocNoMap[I] = NewLocNo;
Reid Klecknercf0cb492017-09-20 17:32:54 +00001121 }
1122
David Stenberg66586cc2018-09-07 13:54:07 +00001123 // Rewrite the locations and record the stack slot offsets for spills.
Reid Klecknercf0cb492017-09-20 17:32:54 +00001124 locations.clear();
David Stenberg66586cc2018-09-07 13:54:07 +00001125 SpillOffsets.clear();
Reid Klecknerca187632017-09-20 18:19:08 +00001126 for (auto &Pair : NewLocations) {
David Stenberg66586cc2018-09-07 13:54:07 +00001127 bool Spilled;
1128 unsigned SpillOffset;
1129 std::tie(Spilled, SpillOffset) = Pair.second;
Reid Klecknercf0cb492017-09-20 17:32:54 +00001130 locations.push_back(Pair.first);
David Stenberg66586cc2018-09-07 13:54:07 +00001131 if (Spilled) {
Reid Klecknerca187632017-09-20 18:19:08 +00001132 unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
David Stenberg66586cc2018-09-07 13:54:07 +00001133 SpillOffsets[NewLocNo] = SpillOffset;
Reid Klecknerca187632017-09-20 18:19:08 +00001134 }
1135 }
Reid Klecknercf0cb492017-09-20 17:32:54 +00001136
1137 // Update the interval map, but only coalesce left, since intervals to the
1138 // right use the old location numbers. This should merge two contiguous
1139 // DBG_VALUE intervals with different vregs that were allocated to the same
1140 // physical register.
1141 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
Reid Klecknerf6c62f92017-10-03 17:59:02 +00001142 DbgValueLocation Loc = I.value();
Mikael Holmen57db0172018-06-21 07:02:46 +00001143 // Undef values don't exist in locations (and thus not in LocNoMap either)
1144 // so skip over them. See getLocationNo().
1145 if (Loc.isUndef())
1146 continue;
Reid Klecknerf6c62f92017-10-03 17:59:02 +00001147 unsigned NewLocNo = LocNoMap[Loc.locNo()];
1148 I.setValueUnchecked(Loc.changeLocNo(NewLocNo));
Reid Klecknercf0cb492017-09-20 17:32:54 +00001149 I.setStart(I.start());
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001150 }
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001151}
1152
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +00001153/// Find an iterator for inserting a DBG_VALUE instruction.
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001154static MachineBasicBlock::iterator
Devang Patelf827cd72011-02-04 01:43:25 +00001155findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001156 LiveIntervals &LIS) {
1157 SlotIndex Start = LIS.getMBBStartIdx(MBB);
1158 Idx = Idx.getBaseIndex();
1159
1160 // Try to find an insert location by going backwards from Idx.
1161 MachineInstr *MI;
1162 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1163 // We've reached the beginning of MBB.
1164 if (Idx == Start) {
Keith Walker7435b282016-09-16 14:07:29 +00001165 MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001166 return I;
1167 }
1168 Idx = Idx.getPrevIndex();
1169 }
Devang Patelf827cd72011-02-04 01:43:25 +00001170
Jakob Stoklund Oleseneea666f2011-01-13 23:35:53 +00001171 // Don't insert anything after the first terminator, though.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001172 return MI->isTerminator() ? MBB->getFirstTerminator() :
Benjamin Kramerd628f192014-03-02 12:27:27 +00001173 std::next(MachineBasicBlock::iterator(MI));
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001174}
1175
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +00001176/// Find an iterator for inserting the next DBG_VALUE instruction
1177/// (or end if no more insert locations found).
1178static MachineBasicBlock::iterator
1179findNextInsertLocation(MachineBasicBlock *MBB,
1180 MachineBasicBlock::iterator I,
1181 SlotIndex StopIdx, MachineOperand &LocMO,
1182 LiveIntervals &LIS,
1183 const TargetRegisterInfo &TRI) {
1184 if (!LocMO.isReg())
1185 return MBB->instr_end();
1186 unsigned Reg = LocMO.getReg();
1187
1188 // Find the next instruction in the MBB that define the register Reg.
Stefan Maksimovic3d785e72018-02-09 14:03:26 +00001189 while (I != MBB->end() && !I->isTerminator()) {
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +00001190 if (!LIS.isNotInMIMap(*I) &&
1191 SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
1192 break;
1193 if (I->definesRegister(Reg, &TRI))
1194 // The insert location is directly after the instruction/bundle.
1195 return std::next(I);
1196 ++I;
1197 }
1198 return MBB->end();
1199}
1200
1201void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
David Stenberg66586cc2018-09-07 13:54:07 +00001202 SlotIndex StopIdx, DbgValueLocation Loc,
1203 bool Spilled, unsigned SpillOffset,
1204 LiveIntervals &LIS, const TargetInstrInfo &TII,
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +00001205 const TargetRegisterInfo &TRI) {
1206 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1207 // Only search within the current MBB.
1208 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1209 MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS);
Mikael Holmen57db0172018-06-21 07:02:46 +00001210 // Undef values don't exist in locations so create new "noreg" register MOs
1211 // for them. See getLocationNo().
1212 MachineOperand MO = !Loc.isUndef() ?
1213 locations[Loc.locNo()] :
1214 MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false,
1215 /* isKill */ false, /* isDead */ false,
1216 /* isUndef */ false, /* isEarlyClobber */ false,
1217 /* SubReg */ 0, /* isDebug */ true);
1218
Devang Pateld9f3fc72011-08-04 20:42:11 +00001219 ++NumInsertedDebugValues;
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001220
Duncan P. N. Exon Smithe56023a2015-04-29 16:38:44 +00001221 assert(cast<DILocalVariable>(Variable)
Duncan P. N. Exon Smith04770452015-04-06 23:27:40 +00001222 ->isValidLocationForIntrinsic(getDebugLoc()) &&
Duncan P. N. Exon Smithf4f021c2015-04-03 19:20:26 +00001223 "Expected inlined-at fields to agree");
Reid Klecknerca187632017-09-20 18:19:08 +00001224
1225 // If the location was spilled, the new DBG_VALUE will be indirect. If the
1226 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
David Stenberg66586cc2018-09-07 13:54:07 +00001227 // that the original virtual register was a pointer. Also, add the stack slot
1228 // offset for the spilled register to the expression.
Reid Klecknerca187632017-09-20 18:19:08 +00001229 const DIExpression *Expr = Expression;
Reid Klecknerf6c62f92017-10-03 17:59:02 +00001230 bool IsIndirect = Loc.wasIndirect();
1231 if (Spilled) {
David Stenberg66586cc2018-09-07 13:54:07 +00001232 auto Deref = IsIndirect ? DIExpression::WithDeref : DIExpression::NoDeref;
1233 Expr =
1234 DIExpression::prepend(Expr, DIExpression::NoDeref, SpillOffset, Deref);
Reid Klecknerf6c62f92017-10-03 17:59:02 +00001235 IsIndirect = true;
1236 }
Reid Klecknerca187632017-09-20 18:19:08 +00001237
Reid Klecknerf6c62f92017-10-03 17:59:02 +00001238 assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
Reid Klecknerca187632017-09-20 18:19:08 +00001239
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +00001240 do {
Mikael Holmenb16b4ba2018-06-21 10:03:34 +00001241 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
1242 IsIndirect, MO, Variable, Expr);
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +00001243
1244 // Continue and insert DBG_VALUES after every redefinition of register
1245 // associated with the debug value within the range
1246 I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
1247 } while (I != MBB->end());
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001248}
1249
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001250void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
Reid Klecknerca187632017-09-20 18:19:08 +00001251 const TargetInstrInfo &TII,
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +00001252 const TargetRegisterInfo &TRI,
David Stenberg66586cc2018-09-07 13:54:07 +00001253 const SpillOffsetMap &SpillOffsets) {
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001254 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1255
1256 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1257 SlotIndex Start = I.start();
1258 SlotIndex Stop = I.stop();
Reid Klecknerf6c62f92017-10-03 17:59:02 +00001259 DbgValueLocation Loc = I.value();
David Stenberg66586cc2018-09-07 13:54:07 +00001260 auto SpillIt =
1261 !Loc.isUndef() ? SpillOffsets.find(Loc.locNo()) : SpillOffsets.end();
1262 bool Spilled = SpillIt != SpillOffsets.end();
1263 unsigned SpillOffset = Spilled ? SpillIt->second : 0;
Robert Lougherb587c9e2017-08-03 11:54:02 +00001264
1265 // If the interval start was trimmed to the lexical scope insert the
1266 // DBG_VALUE at the previous index (otherwise it appears after the
1267 // first instruction in the range).
1268 if (trimmedDefs.count(Start))
1269 Start = Start.getPrevIndex();
1270
Nicola Zaghen0818e782018-05-14 12:53:11 +00001271 LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << Loc.locNo());
Duncan P. N. Exon Smith3f2c43f2015-10-09 19:13:58 +00001272 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1273 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001274
Nicola Zaghen0818e782018-05-14 12:53:11 +00001275 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
David Stenberg66586cc2018-09-07 13:54:07 +00001276 insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII,
1277 TRI);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001278 // This interval may span multiple basic blocks.
1279 // Insert a DBG_VALUE into each one.
Karl-Johan Karlssonb71dbea2017-10-05 08:37:31 +00001280 while (Stop > MBBEnd) {
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001281 // Move to the next block.
1282 Start = MBBEnd;
1283 if (++MBB == MFEnd)
1284 break;
Duncan P. N. Exon Smith3f2c43f2015-10-09 19:13:58 +00001285 MBBEnd = LIS.getMBBEndIdx(&*MBB);
Nicola Zaghen0818e782018-05-14 12:53:11 +00001286 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
David Stenberg66586cc2018-09-07 13:54:07 +00001287 insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII,
1288 TRI);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001289 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00001290 LLVM_DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001291 if (MBB == MFEnd)
1292 break;
1293
1294 ++I;
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001295 }
1296}
1297
1298void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001299 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
David Blaikiee27d5a02014-07-25 16:10:16 +00001300 if (!MF)
1301 return;
Eric Christopher60355182014-08-05 02:39:49 +00001302 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
David Stenberg66586cc2018-09-07 13:54:07 +00001303 SpillOffsetMap SpillOffsets;
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001304 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001305 LLVM_DEBUG(userValues[i]->print(dbgs(), TRI));
David Stenberg66586cc2018-09-07 13:54:07 +00001306 userValues[i]->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
1307 userValues[i]->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001308 }
Manman Renf0986202013-02-13 20:23:48 +00001309 EmitDone = true;
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001310}
1311
1312void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
Manman Renf0986202013-02-13 20:23:48 +00001313 if (pImpl)
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001314 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1315}
1316
David Blaikiee27d5a02014-07-25 16:10:16 +00001317bool LiveDebugVariables::doInitialization(Module &M) {
David Blaikiee27d5a02014-07-25 16:10:16 +00001318 return Pass::doInitialization(M);
1319}
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +00001320
Aaron Ballman1d03d382017-10-15 14:32:27 +00001321#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb2092062017-06-21 22:19:17 +00001322LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +00001323 if (pImpl)
1324 static_cast<LDVImpl*>(pImpl)->print(dbgs());
1325}
1326#endif