blob: 0b6867cfbd8a73208f3c270f9a5c39f06a5f0807 [file] [log] [blame]
Jakob Stoklund Olesend4900a62010-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 Zelenko5df3d892017-08-24 21:21:39 +000023#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseMap.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000025#include "llvm/ADT/IntervalMap.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000026#include "llvm/ADT/STLExtras.h"
Robert Lougher10f740d2017-08-03 11:54:02 +000027#include "llvm/ADT/SmallSet.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000028#include "llvm/ADT/SmallVector.h"
Devang Patelb4568662011-08-04 18:45:38 +000029#include "llvm/ADT/Statistic.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000030#include "llvm/ADT/StringRef.h"
Robert Lougher10f740d2017-08-03 11:54:02 +000031#include "llvm/CodeGen/LexicalScopes.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000032#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunf8422972017-12-13 02:51:04 +000033#include "llvm/CodeGen/LiveIntervals.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000034#include "llvm/CodeGen/MachineBasicBlock.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000035#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +000036#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000037#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +000038#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000039#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +000040#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000041#include "llvm/CodeGen/SlotIndexes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000042#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-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 Olesen26c9d702012-11-28 19:13:06 +000046#include "llvm/CodeGen/VirtRegMap.h"
Nico Weber432a3882018-04-30 14:59:11 +000047#include "llvm/Config/llvm-config.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000048#include "llvm/IR/DebugInfoMetadata.h"
49#include "llvm/IR/DebugLoc.h"
50#include "llvm/IR/Function.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Metadata.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000052#include "llvm/MC/MCRegisterInfo.h"
53#include "llvm/Pass.h"
54#include "llvm/Support/Casting.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000055#include "llvm/Support/CommandLine.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000056#include "llvm/Support/Compiler.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000057#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000058#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000059#include <algorithm>
60#include <cassert>
61#include <iterator>
David Blaikie2b1dfa72014-04-21 20:37:07 +000062#include <memory>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000063#include <utility>
David Blaikie2b1dfa72014-04-21 20:37:07 +000064
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000065using namespace llvm;
66
Matthias Braun1527baa2017-05-25 21:26:32 +000067#define DEBUG_TYPE "livedebugvars"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000068
Devang Patelacbee0b2011-01-07 22:33:41 +000069static cl::opt<bool>
Jakob Stoklund Olesen74ded572011-01-12 23:36:21 +000070EnableLDV("live-debug-variables", cl::init(true),
Devang Patelacbee0b2011-01-07 22:33:41 +000071 cl::desc("Enable the live debug variables pass"), cl::Hidden);
72
Devang Patelb4568662011-08-04 18:45:38 +000073STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
Eugene Zelenko5df3d892017-08-24 21:21:39 +000074
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000075char LiveDebugVariables::ID = 0;
76
Matthias Braun1527baa2017-05-25 21:26:32 +000077INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000078 "Debug Variable Analysis", false, false)
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000079INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000080INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +000081INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000082 "Debug Variable Analysis", false, false)
83
84void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000085 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000086 AU.addRequiredTransitive<LiveIntervals>();
87 AU.setPreservesAll();
88 MachineFunctionPass::getAnalysisUsage(AU);
89}
90
Eugene Zelenko5df3d892017-08-24 21:21:39 +000091LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000092 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
93}
94
Reid Kleckner04e25e02017-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 Klecknerb4569de72017-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 Kleckner04e25e02017-10-03 17:59:02 +0000123 }
Reid Klecknerb4569de72017-10-03 18:30:11 +0000124
125 friend inline bool operator!=(const DbgValueLocation &LHS,
126 const DbgValueLocation &RHS) {
127 return !(LHS == RHS);
128 }
Reid Kleckner04e25e02017-10-03 17:59:02 +0000129
130private:
131 unsigned LocNo : 31;
132 unsigned WasIndirect : 1;
133};
134
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000135/// LocMap - Map of where a user value is live, and its location.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000136using LocMap = IntervalMap<SlotIndex, DbgValueLocation, 4>;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000137
138namespace {
139
140class LDVImpl;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000141
142/// UserValue - A user value is a part of a debug info user variable.
143///
144/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
145/// holds part of a user variable. The part is identified by a byte offset.
146///
147/// UserValues are grouped into equivalence classes for easier searching. Two
148/// user values are related if they refer to the same variable, or if they are
149/// held by the same virtual register. The equivalence class is the transitive
150/// closure of that relation.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000151class UserValue {
Reid Kleckner4e040282017-09-20 18:19:08 +0000152 const DILocalVariable *Variable; ///< The debug info variable we are part of.
153 const DIExpression *Expression; ///< Any complex address expression.
Devang Patel26ffa012011-02-04 01:43:25 +0000154 DebugLoc dl; ///< The debug location for the variable. This is
155 ///< used by dwarf writer to find lexical scope.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000156 UserValue *leader; ///< Equivalence class leader.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000157 UserValue *next = nullptr; ///< Next value in equivalence class, or null.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000158
159 /// Numbered locations referenced by locmap.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000160 SmallVector<MachineOperand, 4> locations;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000161
162 /// Map of slot indices where this value is live.
163 LocMap locInts;
164
Robert Lougher10f740d2017-08-03 11:54:02 +0000165 /// Set of interval start indexes that have been trimmed to the
166 /// lexical scope.
167 SmallSet<SlotIndex, 2> trimmedDefs;
168
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000169 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +0000170 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
171 SlotIndex StopIdx,
Reid Kleckner04e25e02017-10-03 17:59:02 +0000172 DbgValueLocation Loc, bool Spilled, LiveIntervals &LIS,
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +0000173 const TargetInstrInfo &TII,
174 const TargetRegisterInfo &TRI);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000175
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000176 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
177 /// is live. Returns true if any changes were made.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000178 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
179 LiveIntervals &LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000180
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000181public:
182 /// UserValue - Create a new UserValue.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000183 UserValue(const DILocalVariable *var, const DIExpression *expr, DebugLoc L,
184 LocMap::Allocator &alloc)
185 : Variable(var), Expression(expr), dl(std::move(L)), leader(this),
186 locInts(alloc) {}
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000187
188 /// getLeader - Get the leader of this value's equivalence class.
189 UserValue *getLeader() {
190 UserValue *l = leader;
191 while (l != l->leader)
192 l = l->leader;
193 return leader = l;
194 }
195
196 /// getNext - Return the next UserValue in the equivalence class.
197 UserValue *getNext() const { return next; }
198
Devang Patel338e4322011-07-06 23:09:51 +0000199 /// match - Does this UserValue match the parameters?
Reid Kleckner4e040282017-09-20 18:19:08 +0000200 bool match(const DILocalVariable *Var, const DIExpression *Expr,
Reid Kleckner04e25e02017-10-03 17:59:02 +0000201 const DILocation *IA) const {
202 // FIXME: The fragment should be part of the equivalence class, but not
203 // other things in the expression like stack values.
204 return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000205 }
206
207 /// merge - Merge equivalence classes.
208 static UserValue *merge(UserValue *L1, UserValue *L2) {
209 L2 = L2->getLeader();
210 if (!L1)
211 return L2;
212 L1 = L1->getLeader();
213 if (L1 == L2)
214 return L1;
215 // Splice L2 before L1's members.
216 UserValue *End = L2;
Richard Trieu7a083812016-02-18 22:09:30 +0000217 while (End->next) {
218 End->leader = L1;
219 End = End->next;
220 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000221 End->leader = L1;
222 End->next = L1->next;
223 L1->next = L2;
224 return L1;
225 }
226
Mikael Holmen57b33f62018-06-21 07:02:46 +0000227 /// Return the location number that matches Loc.
228 ///
229 /// For undef values we always return location number UndefLocNo without
230 /// inserting anything in locations. Since locations is a vector and the
231 /// location number is the position in the vector and UndefLocNo is ~0,
232 /// we would need a very big vector to put the value at the right position.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000233 unsigned getLocationNo(const MachineOperand &LocMO) {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000234 if (LocMO.isReg()) {
235 if (LocMO.getReg() == 0)
Reid Klecknereed09732017-09-15 22:08:50 +0000236 return UndefLocNo;
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000237 // For register locations we dont care about use/def and other flags.
238 for (unsigned i = 0, e = locations.size(); i != e; ++i)
239 if (locations[i].isReg() &&
240 locations[i].getReg() == LocMO.getReg() &&
241 locations[i].getSubReg() == LocMO.getSubReg())
242 return i;
243 } else
244 for (unsigned i = 0, e = locations.size(); i != e; ++i)
245 if (LocMO.isIdenticalTo(locations[i]))
246 return i;
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000247 locations.push_back(LocMO);
248 // We are storing a MachineOperand outside a MachineInstr.
249 locations.back().clearParent();
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000250 // Don't store def operands.
Geoff Berryb3d126d2017-12-29 21:01:09 +0000251 if (locations.back().isReg()) {
252 if (locations.back().isDef())
253 locations.back().setIsDead(false);
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000254 locations.back().setIsUse();
Geoff Berryb3d126d2017-12-29 21:01:09 +0000255 }
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000256 return locations.size() - 1;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000257 }
258
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000259 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
260 void mapVirtRegs(LDVImpl *LDV);
261
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000262 /// addDef - Add a definition point to this value.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000263 void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect) {
264 DbgValueLocation Loc(getLocationNo(LocMO), IsIndirect);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000265 // Add a singular (Idx,Idx) -> Loc mapping.
266 LocMap::iterator I = locInts.find(Idx);
267 if (!I.valid() || I.start() != Idx)
Reid Kleckner04e25e02017-10-03 17:59:02 +0000268 I.insert(Idx, Idx.getNextSlot(), Loc);
Jakob Stoklund Olesen2539af62011-08-03 23:44:31 +0000269 else
270 // A later DBG_VALUE at the same SlotIndex overrides the old location.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000271 I.setValue(Loc);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000272 }
273
Adrian Prantlf8d10ce2016-09-28 21:34:23 +0000274 /// extendDef - Extend the current definition as far as possible down.
275 /// Stop when meeting an existing def or when leaving the live
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000276 /// range of VNI.
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000277 /// End points where VNI is no longer live are added to Kills.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000278 /// @param Idx Starting point for the definition.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000279 /// @param Loc Location number to propagate.
Matthias Braun34e1be92013-10-10 21:29:02 +0000280 /// @param LR Restrict liveness to where LR has the value VNI. May be null.
281 /// @param VNI When LR is not null, this is the value to restrict to.
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000282 /// @param Kills Append end points of VNI's live range to Kills.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000283 /// @param LIS Live intervals analysis.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000284 void extendDef(SlotIndex Idx, DbgValueLocation Loc,
Matthias Braun34e1be92013-10-10 21:29:02 +0000285 LiveRange *LR, const VNInfo *VNI,
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000286 SmallVectorImpl<SlotIndex> *Kills,
Adrian Prantlf8d10ce2016-09-28 21:34:23 +0000287 LiveIntervals &LIS);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000288
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000289 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
290 /// registers. Determine if any of the copies are available at the kill
291 /// points, and add defs if possible.
292 /// @param LI Scan for copies of the value in LI->reg.
293 /// @param LocNo Location number of LI->reg.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000294 /// @param WasIndirect Indicates if the original use of LI->reg was indirect
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000295 /// @param Kills Points where the range of LocNo could be extended.
296 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000297 void addDefsFromCopies(
298 LiveInterval *LI, unsigned LocNo, bool WasIndirect,
299 const SmallVectorImpl<SlotIndex> &Kills,
300 SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
301 MachineRegisterInfo &MRI, LiveIntervals &LIS);
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000302
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000303 /// computeIntervals - Compute the live intervals of all locations after
304 /// collecting all their def points.
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000305 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
Robert Lougher10f740d2017-08-03 11:54:02 +0000306 LiveIntervals &LIS, LexicalScopes &LS);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000307
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000308 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
309 /// live. Returns true if any changes were made.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000310 bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
311 LiveIntervals &LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000312
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000313 /// rewriteLocations - Rewrite virtual register locations according to the
Reid Kleckner4e040282017-09-20 18:19:08 +0000314 /// provided virtual register map. Record which locations were spilled.
315 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI,
316 BitVector &SpilledLocations);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000317
Eric Christopherbc671702013-02-13 02:29:18 +0000318 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
Reid Kleckner4e040282017-09-20 18:19:08 +0000319 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +0000320 const TargetInstrInfo &TII,
321 const TargetRegisterInfo &TRI,
Reid Kleckner4e040282017-09-20 18:19:08 +0000322 const BitVector &SpilledLocations);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000323
Devang Patelf9e2ae92011-09-13 18:40:53 +0000324 /// getDebugLoc - Return DebugLoc of this UserValue.
325 DebugLoc getDebugLoc() { return dl;}
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000326
Eric Christopher1cdefae2015-02-27 00:11:34 +0000327 void print(raw_ostream &, const TargetRegisterInfo *);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000328};
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000329
330/// LDVImpl - Implementation of the LiveDebugVariables pass.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000331class LDVImpl {
332 LiveDebugVariables &pass;
333 LocMap::Allocator allocator;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000334 MachineFunction *MF = nullptr;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000335 LiveIntervals *LIS;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000336 const TargetRegisterInfo *TRI;
337
Manman Ren7a4c8a72013-02-13 20:23:48 +0000338 /// Whether emitDebugValues is called.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000339 bool EmitDone = false;
340
Manman Ren7a4c8a72013-02-13 20:23:48 +0000341 /// Whether the machine function is modified during the pass.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000342 bool ModifiedMF = false;
Manman Ren7a4c8a72013-02-13 20:23:48 +0000343
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000344 /// userValues - All allocated UserValue instances.
David Blaikie2b1dfa72014-04-21 20:37:07 +0000345 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000346
347 /// Map virtual register to eq class leader.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000348 using VRMap = DenseMap<unsigned, UserValue *>;
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000349 VRMap virtRegToEqClass;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000350
351 /// Map user variable to eq class leader.
Reid Kleckner4e040282017-09-20 18:19:08 +0000352 using UVMap = DenseMap<const DILocalVariable *, UserValue *>;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000353 UVMap userVarMap;
354
355 /// getUserValue - Find or create a UserValue.
Reid Kleckner4e040282017-09-20 18:19:08 +0000356 UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr,
Reid Kleckner04e25e02017-10-03 17:59:02 +0000357 const DebugLoc &DL);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000358
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000359 /// lookupVirtReg - Find the EC leader for VirtReg or null.
360 UserValue *lookupVirtReg(unsigned VirtReg);
361
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000362 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
363 /// @param MI DBG_VALUE instruction
364 /// @param Idx Last valid SLotIndex before instruction.
365 /// @return True if the DBG_VALUE instruction should be deleted.
Duncan P. N. Exon Smithfb612ac2016-06-30 23:13:38 +0000366 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000367
368 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
369 /// a UserValue def for each instruction.
370 /// @param mf MachineFunction to be scanned.
371 /// @return True if any debug values were found.
372 bool collectDebugValues(MachineFunction &mf);
373
374 /// computeIntervals - Compute the live intervals of all user values after
375 /// collecting all their def points.
376 void computeIntervals();
377
378public:
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000379 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
380
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000381 bool runOnMachineFunction(MachineFunction &mf);
382
Manman Ren7a4c8a72013-02-13 20:23:48 +0000383 /// clear - Release all memory.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000384 void clear() {
David Blaikie2f040112014-07-25 16:10:16 +0000385 MF = nullptr;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000386 userValues.clear();
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000387 virtRegToEqClass.clear();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000388 userVarMap.clear();
Manman Ren7a4c8a72013-02-13 20:23:48 +0000389 // Make sure we call emitDebugValues if the machine function was modified.
390 assert((!ModifiedMF || EmitDone) &&
391 "Dbg values are not emitted in LDV");
392 EmitDone = false;
393 ModifiedMF = false;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000394 }
395
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000396 /// mapVirtReg - Map virtual register to an equivalence class.
397 void mapVirtReg(unsigned VirtReg, UserValue *EC);
398
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000399 /// splitRegister - Replace all references to OldReg with NewRegs.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000400 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000401
Eric Christopherbc671702013-02-13 02:29:18 +0000402 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000403 void emitDebugValues(VirtRegMap *VRM);
404
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000405 void print(raw_ostream&);
406};
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000407
408} // end anonymous namespace
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000409
Aaron Ballman615eb472017-10-15 14:32:27 +0000410#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000411static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000412 const LLVMContext &Ctx) {
413 if (!DL)
414 return;
415
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000416 auto *Scope = cast<DIScope>(DL.getScope());
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000417 // Omit the directory, because it's likely to be long and uninteresting.
Duncan P. N. Exon Smithb273d062015-04-16 01:37:00 +0000418 CommentOS << Scope->getFilename();
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000419 CommentOS << ':' << DL.getLine();
420 if (DL.getCol() != 0)
421 CommentOS << ':' << DL.getCol();
422
423 DebugLoc InlinedAtDL = DL.getInlinedAt();
424 if (!InlinedAtDL)
425 return;
426
427 CommentOS << " @[ ";
428 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
429 CommentOS << " ]";
430}
431
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000432static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
433 const DILocation *DL) {
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000434 const LLVMContext &Ctx = V->getContext();
435 StringRef Res = V->getName();
436 if (!Res.empty())
437 OS << Res << "," << V->getLine();
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +0000438 if (auto *InlinedAt = DL->getInlinedAt()) {
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000439 if (DebugLoc InlinedAtDL = InlinedAt) {
440 OS << " @[";
441 printDebugLoc(InlinedAtDL, OS, Ctx);
442 OS << "]";
443 }
444 }
445}
446
Eric Christopher1cdefae2015-02-27 00:11:34 +0000447void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000448 auto *DV = cast<DILocalVariable>(Variable);
Frederic Risse6bb1872014-08-07 20:04:00 +0000449 OS << "!\"";
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +0000450 printExtendedName(OS, DV, dl);
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000451
Devang Patel6c1ed312011-08-09 01:03:35 +0000452 OS << "\"\t";
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000453 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
454 OS << " [" << I.start() << ';' << I.stop() << "):";
Reid Kleckner04e25e02017-10-03 17:59:02 +0000455 if (I.value().isUndef())
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000456 OS << "undef";
Reid Kleckner04e25e02017-10-03 17:59:02 +0000457 else {
458 OS << I.value().locNo();
459 if (I.value().wasIndirect())
460 OS << " ind";
461 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000462 }
Jakob Stoklund Olesenc86fe052011-05-06 17:59:59 +0000463 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
464 OS << " Loc" << i << '=';
Eric Christopher1cdefae2015-02-27 00:11:34 +0000465 locations[i].print(OS, TRI);
Jakob Stoklund Olesenc86fe052011-05-06 17:59:59 +0000466 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000467 OS << '\n';
468}
469
470void LDVImpl::print(raw_ostream &OS) {
471 OS << "********** DEBUG VARIABLES **********\n";
472 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
Eric Christopher1cdefae2015-02-27 00:11:34 +0000473 userValues[i]->print(OS, TRI);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000474}
Florian Hahn6b3216a2017-07-31 10:07:49 +0000475#endif
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000476
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000477void UserValue::mapVirtRegs(LDVImpl *LDV) {
478 for (unsigned i = 0, e = locations.size(); i != e; ++i)
479 if (locations[i].isReg() &&
480 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
481 LDV->mapVirtReg(locations[i].getReg(), this);
482}
483
Reid Kleckner4e040282017-09-20 18:19:08 +0000484UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
Reid Kleckner04e25e02017-10-03 17:59:02 +0000485 const DIExpression *Expr, const DebugLoc &DL) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000486 UserValue *&Leader = userVarMap[Var];
487 if (Leader) {
488 UserValue *UV = Leader->getLeader();
489 Leader = UV;
490 for (; UV; UV = UV->getNext())
Reid Kleckner04e25e02017-10-03 17:59:02 +0000491 if (UV->match(Var, Expr, DL->getInlinedAt()))
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000492 return UV;
493 }
494
David Blaikie2b1dfa72014-04-21 20:37:07 +0000495 userValues.push_back(
Reid Kleckner04e25e02017-10-03 17:59:02 +0000496 llvm::make_unique<UserValue>(Var, Expr, DL, allocator));
David Blaikie2b1dfa72014-04-21 20:37:07 +0000497 UserValue *UV = userValues.back().get();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000498 Leader = UserValue::merge(Leader, UV);
499 return UV;
500}
501
502void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
503 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000504 UserValue *&Leader = virtRegToEqClass[VirtReg];
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000505 Leader = UserValue::merge(Leader, EC);
506}
507
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000508UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000509 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000510 return UV->getLeader();
Craig Topperc0196b12014-04-14 00:51:57 +0000511 return nullptr;
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000512}
513
Duncan P. N. Exon Smithfb612ac2016-06-30 23:13:38 +0000514bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000515 // DBG_VALUE loc, offset, variable
Duncan P. N. Exon Smithfb612ac2016-06-30 23:13:38 +0000516 if (MI.getNumOperands() != 4 ||
517 !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
518 !MI.getOperand(2).isMetadata()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000519 LLVM_DEBUG(dbgs() << "Can't handle " << MI);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000520 return false;
521 }
522
Bjorn Petterssonbdf0c002018-03-06 08:47:07 +0000523 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
524 // register that hasn't been defined yet. If we do not remove those here, then
525 // the re-insertion of the DBG_VALUE instruction after register allocation
526 // will be incorrect.
527 // TODO: If earlier passes are corrected to generate sane debug information
528 // (and if the machine verifier is improved to catch this), then these checks
529 // could be removed or replaced by asserts.
530 bool Discard = false;
531 if (MI.getOperand(0).isReg() &&
532 TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg())) {
533 const unsigned Reg = MI.getOperand(0).getReg();
534 if (!LIS->hasInterval(Reg)) {
535 // The DBG_VALUE is described by a virtual register that does not have a
536 // live interval. Discard the DBG_VALUE.
537 Discard = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000538 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
539 << " " << MI);
Bjorn Petterssonbdf0c002018-03-06 08:47:07 +0000540 } else {
541 // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
542 // is defined dead at Idx (where Idx is the slot index for the instruction
543 // preceeding the DBG_VALUE).
544 const LiveInterval &LI = LIS->getInterval(Reg);
545 LiveQueryResult LRQ = LI.Query(Idx);
546 if (!LRQ.valueOutOrDead()) {
547 // We have found a DBG_VALUE with the value in a virtual register that
548 // is not live. Discard the DBG_VALUE.
549 Discard = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000550 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
551 << " " << MI);
Bjorn Petterssonbdf0c002018-03-06 08:47:07 +0000552 }
553 }
554 }
555
Reid Kleckner04e25e02017-10-03 17:59:02 +0000556 // Get or create the UserValue for (variable,offset) here.
Reid Kleckner4e040282017-09-20 18:19:08 +0000557 bool IsIndirect = MI.getOperand(1).isImm();
Adrian Prantlb2811e52017-07-28 23:06:50 +0000558 if (IsIndirect)
559 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
Reid Kleckner4e040282017-09-20 18:19:08 +0000560 const DILocalVariable *Var = MI.getDebugVariable();
561 const DIExpression *Expr = MI.getDebugExpression();
Reid Kleckner04e25e02017-10-03 17:59:02 +0000562 UserValue *UV =
563 getUserValue(Var, Expr, MI.getDebugLoc());
Bjorn Petterssonbdf0c002018-03-06 08:47:07 +0000564 if (!Discard)
565 UV->addDef(Idx, MI.getOperand(0), IsIndirect);
Bjorn Petterssone0050d72018-03-06 13:23:28 +0000566 else {
567 MachineOperand MO = MachineOperand::CreateReg(0U, false);
568 MO.setIsDebug();
569 UV->addDef(Idx, MO, false);
570 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000571 return true;
572}
573
574bool LDVImpl::collectDebugValues(MachineFunction &mf) {
575 bool Changed = false;
576 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
577 ++MFI) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000578 MachineBasicBlock *MBB = &*MFI;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000579 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
580 MBBI != MBBE;) {
581 if (!MBBI->isDebugValue()) {
582 ++MBBI;
583 continue;
584 }
585 // DBG_VALUE has no slot index, use the previous instruction instead.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000586 SlotIndex Idx =
587 MBBI == MBB->begin()
588 ? LIS->getMBBStartIdx(MBB)
589 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000590 // Handle consecutive DBG_VALUE instructions with the same slot index.
591 do {
Duncan P. N. Exon Smithfb612ac2016-06-30 23:13:38 +0000592 if (handleDebugValue(*MBBI, Idx)) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000593 MBBI = MBB->erase(MBBI);
594 Changed = true;
595 } else
596 ++MBBI;
597 } while (MBBI != MBBE && MBBI->isDebugValue());
598 }
599 }
600 return Changed;
601}
602
Adrian Prantlce858132015-12-21 20:03:00 +0000603/// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
604/// data-flow analysis to propagate them beyond basic block boundaries.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000605void UserValue::extendDef(SlotIndex Idx, DbgValueLocation Loc, LiveRange *LR,
Adrian Prantlce858132015-12-21 20:03:00 +0000606 const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
Adrian Prantlf8d10ce2016-09-28 21:34:23 +0000607 LiveIntervals &LIS) {
Adrian Prantlce858132015-12-21 20:03:00 +0000608 SlotIndex Start = Idx;
609 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
610 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
611 LocMap::iterator I = locInts.find(Start);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000612
Adrian Prantlce858132015-12-21 20:03:00 +0000613 // Limit to VNI's live range.
614 bool ToEnd = true;
615 if (LR && VNI) {
616 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
617 if (!Segment || Segment->valno != VNI) {
618 if (Kills)
619 Kills->push_back(Start);
620 return;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000621 }
Richard Trieu7a083812016-02-18 22:09:30 +0000622 if (Segment->end < Stop) {
623 Stop = Segment->end;
624 ToEnd = false;
625 }
Adrian Prantlce858132015-12-21 20:03:00 +0000626 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000627
Adrian Prantlce858132015-12-21 20:03:00 +0000628 // There could already be a short def at Start.
629 if (I.valid() && I.start() <= Start) {
630 // Stop when meeting a different location or an already extended interval.
631 Start = Start.getNextSlot();
Reid Kleckner04e25e02017-10-03 17:59:02 +0000632 if (I.value() != Loc || I.stop() != Start)
Adrian Prantlce858132015-12-21 20:03:00 +0000633 return;
634 // This is a one-slot placeholder. Just skip it.
635 ++I;
636 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000637
Adrian Prantlce858132015-12-21 20:03:00 +0000638 // Limited by the next def.
Richard Trieu7a083812016-02-18 22:09:30 +0000639 if (I.valid() && I.start() < Stop) {
640 Stop = I.start();
641 ToEnd = false;
642 }
Adrian Prantlce858132015-12-21 20:03:00 +0000643 // Limited by VNI's live range.
644 else if (!ToEnd && Kills)
645 Kills->push_back(Stop);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000646
Adrian Prantlce858132015-12-21 20:03:00 +0000647 if (Start < Stop)
Reid Kleckner04e25e02017-10-03 17:59:02 +0000648 I.insert(Start, Stop, Loc);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000649}
650
Reid Kleckner04e25e02017-10-03 17:59:02 +0000651void UserValue::addDefsFromCopies(
652 LiveInterval *LI, unsigned LocNo, bool WasIndirect,
653 const SmallVectorImpl<SlotIndex> &Kills,
654 SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
655 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000656 if (Kills.empty())
657 return;
658 // Don't track copies from physregs, there are too many uses.
659 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
660 return;
661
662 // Collect all the (vreg, valno) pairs that are copies of LI.
663 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
Owen Andersonb36376e2014-03-17 19:36:09 +0000664 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
665 MachineInstr *MI = MO.getParent();
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000666 // Copies of the full value.
Owen Andersonb36376e2014-03-17 19:36:09 +0000667 if (MO.getSubReg() || !MI->isCopy())
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000668 continue;
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000669 unsigned DstReg = MI->getOperand(0).getReg();
670
Jakob Stoklund Olesenec0ac3c2011-03-22 22:33:08 +0000671 // Don't follow copies to physregs. These are usually setting up call
672 // arguments, and the argument registers are always call clobbered. We are
673 // better off in the source register which could be a callee-saved register,
674 // or it could be spilled.
675 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
676 continue;
677
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000678 // Is LocNo extended to reach this copy? If not, another def may be blocking
679 // it, or we are looking at a wrong value of LI.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000680 SlotIndex Idx = LIS.getInstructionIndex(*MI);
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000681 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
Reid Kleckner04e25e02017-10-03 17:59:02 +0000682 if (!I.valid() || I.value().locNo() != LocNo)
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000683 continue;
684
685 if (!LIS.hasInterval(DstReg))
686 continue;
687 LiveInterval *DstLI = &LIS.getInterval(DstReg);
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000688 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
689 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000690 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
691 }
692
693 if (CopyValues.empty())
694 return;
695
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000696 LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI
697 << '\n');
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000698
699 // Try to add defs of the copied values for each kill point.
700 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
701 SlotIndex Idx = Kills[i];
702 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
703 LiveInterval *DstLI = CopyValues[j].first;
704 const VNInfo *DstVNI = CopyValues[j].second;
705 if (DstLI->getVNInfoAt(Idx) != DstVNI)
706 continue;
707 // Check that there isn't already a def at Idx
708 LocMap::iterator I = locInts.find(Idx);
709 if (I.valid() && I.start() <= Idx)
710 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000711 LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
712 << DstVNI->id << " in " << *DstLI << '\n');
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000713 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
714 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
715 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
Reid Kleckner04e25e02017-10-03 17:59:02 +0000716 DbgValueLocation NewLoc(LocNo, WasIndirect);
717 I.insert(Idx, Idx.getNextSlot(), NewLoc);
718 NewDefs.push_back(std::make_pair(Idx, NewLoc));
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000719 break;
720 }
721 }
722}
723
Robert Lougher10f740d2017-08-03 11:54:02 +0000724void UserValue::computeIntervals(MachineRegisterInfo &MRI,
725 const TargetRegisterInfo &TRI,
726 LiveIntervals &LIS, LexicalScopes &LS) {
Reid Kleckner04e25e02017-10-03 17:59:02 +0000727 SmallVector<std::pair<SlotIndex, DbgValueLocation>, 16> Defs;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000728
729 // Collect all defs to be extended (Skipping undefs).
730 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
Reid Kleckner04e25e02017-10-03 17:59:02 +0000731 if (!I.value().isUndef())
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000732 Defs.push_back(std::make_pair(I.start(), I.value()));
733
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000734 // Extend all defs, and possibly add new ones along the way.
735 for (unsigned i = 0; i != Defs.size(); ++i) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000736 SlotIndex Idx = Defs[i].first;
Reid Kleckner04e25e02017-10-03 17:59:02 +0000737 DbgValueLocation Loc = Defs[i].second;
738 const MachineOperand &LocMO = locations[Loc.locNo()];
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000739
Reid Kleckner04e25e02017-10-03 17:59:02 +0000740 if (!LocMO.isReg()) {
741 extendDef(Idx, Loc, nullptr, nullptr, nullptr, LIS);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000742 continue;
743 }
744
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000745 // Register locations are constrained to where the register value is live.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000746 if (TargetRegisterInfo::isVirtualRegister(LocMO.getReg())) {
Craig Topperc0196b12014-04-14 00:51:57 +0000747 LiveInterval *LI = nullptr;
748 const VNInfo *VNI = nullptr;
Reid Kleckner04e25e02017-10-03 17:59:02 +0000749 if (LIS.hasInterval(LocMO.getReg())) {
750 LI = &LIS.getInterval(LocMO.getReg());
Jakob Stoklund Olesen48a16472012-06-22 18:51:35 +0000751 VNI = LI->getVNInfoAt(Idx);
752 }
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000753 SmallVector<SlotIndex, 16> Kills;
Reid Kleckner04e25e02017-10-03 17:59:02 +0000754 extendDef(Idx, Loc, LI, VNI, &Kills, LIS);
Jakob Stoklund Olesen48a16472012-06-22 18:51:35 +0000755 if (LI)
Reid Kleckner04e25e02017-10-03 17:59:02 +0000756 addDefsFromCopies(LI, Loc.locNo(), Loc.wasIndirect(), Kills, Defs, MRI,
757 LIS);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000758 continue;
759 }
760
Bjorn Pettersson715a5ef2017-09-28 13:10:06 +0000761 // For physregs, we only mark the start slot idx. DwarfDebug will see it
762 // as if the DBG_VALUE is valid up until the end of the basic block, or
763 // the next def of the physical register. So we do not need to extend the
764 // range. It might actually happen that the DBG_VALUE is the last use of
765 // the physical register (e.g. if this is an unused input argument to a
766 // function).
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000767 }
768
Robert Lougher10f740d2017-08-03 11:54:02 +0000769 // The computed intervals may extend beyond the range of the debug
770 // location's lexical scope. In this case, splitting of an interval
771 // can result in an interval outside of the scope being created,
772 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
773 // this, trim the intervals to the lexical scope.
774
775 LexicalScope *Scope = LS.findLexicalScope(dl);
776 if (!Scope)
777 return;
778
779 SlotIndex PrevEnd;
780 LocMap::iterator I = locInts.begin();
781
782 // Iterate over the lexical scope ranges. Each time round the loop
783 // we check the intervals for overlap with the end of the previous
784 // range and the start of the next. The first range is handled as
785 // a special case where there is no PrevEnd.
786 for (const InsnRange &Range : Scope->getRanges()) {
787 SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
788 SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
789
790 // At the start of each iteration I has been advanced so that
791 // I.stop() >= PrevEnd. Check for overlap.
792 if (PrevEnd && I.start() < PrevEnd) {
793 SlotIndex IStop = I.stop();
Reid Kleckner04e25e02017-10-03 17:59:02 +0000794 DbgValueLocation Loc = I.value();
Robert Lougher10f740d2017-08-03 11:54:02 +0000795
796 // Stop overlaps previous end - trim the end of the interval to
797 // the scope range.
798 I.setStopUnchecked(PrevEnd);
799 ++I;
800
801 // If the interval also overlaps the start of the "next" (i.e.
802 // current) range create a new interval for the remainder (which
803 // may be further trimmed).
804 if (RStart < IStop)
Reid Kleckner04e25e02017-10-03 17:59:02 +0000805 I.insert(RStart, IStop, Loc);
Robert Lougher10f740d2017-08-03 11:54:02 +0000806 }
807
808 // Advance I so that I.stop() >= RStart, and check for overlap.
809 I.advanceTo(RStart);
810 if (!I.valid())
811 return;
812
813 if (I.start() < RStart) {
814 // Interval start overlaps range - trim to the scope range.
815 I.setStartUnchecked(RStart);
816 // Remember that this interval was trimmed.
817 trimmedDefs.insert(RStart);
818 }
819
820 // The end of a lexical scope range is the last instruction in the
821 // range. To convert to an interval we need the index of the
822 // instruction after it.
823 REnd = REnd.getNextIndex();
824
825 // Advance I to first interval outside current range.
826 I.advanceTo(REnd);
827 if (!I.valid())
828 return;
829
830 PrevEnd = REnd;
831 }
832
833 // Check for overlap with end of final range.
834 if (PrevEnd && I.start() < PrevEnd)
835 I.setStopUnchecked(PrevEnd);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000836}
837
838void LDVImpl::computeIntervals() {
Robert Lougher10f740d2017-08-03 11:54:02 +0000839 LexicalScopes LS;
840 LS.initialize(*MF);
841
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000842 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
Robert Lougher10f740d2017-08-03 11:54:02 +0000843 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000844 userValues[i]->mapVirtRegs(this);
845 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000846}
847
848bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
David Blaikie2f040112014-07-25 16:10:16 +0000849 clear();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000850 MF = &mf;
851 LIS = &pass.getAnalysis<LiveIntervals>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000852 TRI = mf.getSubtarget().getRegisterInfo();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000853 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
854 << mf.getName() << " **********\n");
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000855
856 bool Changed = collectDebugValues(mf);
857 computeIntervals();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000858 LLVM_DEBUG(print(dbgs()));
Manman Ren7a4c8a72013-02-13 20:23:48 +0000859 ModifiedMF = Changed;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000860 return Changed;
861}
862
David Blaikie2f040112014-07-25 16:10:16 +0000863static void removeDebugValues(MachineFunction &mf) {
864 for (MachineBasicBlock &MBB : mf) {
865 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
866 if (!MBBI->isDebugValue()) {
867 ++MBBI;
868 continue;
869 }
870 MBBI = MBB.erase(MBBI);
871 }
872 }
873}
874
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +0000875bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
Devang Patelacbee0b2011-01-07 22:33:41 +0000876 if (!EnableLDV)
877 return false;
Matthias Braunf1caa282017-12-15 22:22:58 +0000878 if (!mf.getFunction().getSubprogram()) {
David Blaikie2f040112014-07-25 16:10:16 +0000879 removeDebugValues(mf);
880 return false;
881 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000882 if (!pImpl)
883 pImpl = new LDVImpl(this);
Manman Ren7a4c8a72013-02-13 20:23:48 +0000884 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000885}
886
887void LiveDebugVariables::releaseMemory() {
Manman Ren7a4c8a72013-02-13 20:23:48 +0000888 if (pImpl)
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000889 static_cast<LDVImpl*>(pImpl)->clear();
890}
891
892LiveDebugVariables::~LiveDebugVariables() {
893 if (pImpl)
894 delete static_cast<LDVImpl*>(pImpl);
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +0000895}
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000896
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000897//===----------------------------------------------------------------------===//
898// Live Range Splitting
899//===----------------------------------------------------------------------===//
900
901bool
Mark Laceyf9ea8852013-08-14 23:50:04 +0000902UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
903 LiveIntervals& LIS) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000904 LLVM_DEBUG({
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000905 dbgs() << "Splitting Loc" << OldLocNo << '\t';
Craig Topperc0196b12014-04-14 00:51:57 +0000906 print(dbgs(), nullptr);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000907 });
908 bool DidChange = false;
909 LocMap::iterator LocMapI;
910 LocMapI.setMap(locInts);
911 for (unsigned i = 0; i != NewRegs.size(); ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000912 LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000913 if (LI->empty())
914 continue;
915
916 // Don't allocate the new LocNo until it is needed.
Reid Klecknereed09732017-09-15 22:08:50 +0000917 unsigned NewLocNo = UndefLocNo;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000918
919 // Iterate over the overlaps between locInts and LI.
920 LocMapI.find(LI->beginIndex());
921 if (!LocMapI.valid())
922 continue;
923 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
924 LiveInterval::iterator LIE = LI->end();
925 while (LocMapI.valid() && LII != LIE) {
926 // At this point, we know that LocMapI.stop() > LII->start.
927 LII = LI->advanceTo(LII, LocMapI.start());
928 if (LII == LIE)
929 break;
930
931 // Now LII->end > LocMapI.start(). Do we have an overlap?
Reid Kleckner04e25e02017-10-03 17:59:02 +0000932 if (LocMapI.value().locNo() == OldLocNo && LII->start < LocMapI.stop()) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000933 // Overlapping correct location. Allocate NewLocNo now.
Reid Klecknereed09732017-09-15 22:08:50 +0000934 if (NewLocNo == UndefLocNo) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000935 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
936 MO.setSubReg(locations[OldLocNo].getSubReg());
937 NewLocNo = getLocationNo(MO);
938 DidChange = true;
939 }
940
941 SlotIndex LStart = LocMapI.start();
942 SlotIndex LStop = LocMapI.stop();
Reid Kleckner04e25e02017-10-03 17:59:02 +0000943 DbgValueLocation OldLoc = LocMapI.value();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000944
945 // Trim LocMapI down to the LII overlap.
946 if (LStart < LII->start)
947 LocMapI.setStartUnchecked(LII->start);
948 if (LStop > LII->end)
949 LocMapI.setStopUnchecked(LII->end);
950
951 // Change the value in the overlap. This may trigger coalescing.
Reid Kleckner04e25e02017-10-03 17:59:02 +0000952 LocMapI.setValue(OldLoc.changeLocNo(NewLocNo));
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000953
954 // Re-insert any removed OldLocNo ranges.
955 if (LStart < LocMapI.start()) {
Reid Kleckner04e25e02017-10-03 17:59:02 +0000956 LocMapI.insert(LStart, LocMapI.start(), OldLoc);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000957 ++LocMapI;
958 assert(LocMapI.valid() && "Unexpected coalescing");
959 }
960 if (LStop > LocMapI.stop()) {
961 ++LocMapI;
Reid Kleckner04e25e02017-10-03 17:59:02 +0000962 LocMapI.insert(LII->end, LStop, OldLoc);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000963 --LocMapI;
964 }
965 }
966
967 // Advance to the next overlap.
968 if (LII->end < LocMapI.stop()) {
969 if (++LII == LIE)
970 break;
971 LocMapI.advanceTo(LII->start);
972 } else {
973 ++LocMapI;
974 if (!LocMapI.valid())
975 break;
976 LII = LI->advanceTo(LII, LocMapI.start());
977 }
978 }
979 }
980
981 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
982 locations.erase(locations.begin() + OldLocNo);
983 LocMapI.goToBegin();
984 while (LocMapI.valid()) {
Reid Kleckner04e25e02017-10-03 17:59:02 +0000985 DbgValueLocation v = LocMapI.value();
986 if (v.locNo() == OldLocNo) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000987 LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
988 << LocMapI.stop() << ")\n");
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000989 LocMapI.erase();
990 } else {
Mikael Holmen57b33f62018-06-21 07:02:46 +0000991 // Undef values always have location number UndefLocNo, so don't change
992 // locNo in that case. See getLocationNo().
993 if (!v.isUndef() && v.locNo() > OldLocNo)
Reid Kleckner04e25e02017-10-03 17:59:02 +0000994 LocMapI.setValueUnchecked(v.changeLocNo(v.locNo() - 1));
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000995 ++LocMapI;
996 }
997 }
998
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000999 LLVM_DEBUG({
1000 dbgs() << "Split result: \t";
1001 print(dbgs(), nullptr);
1002 });
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001003 return DidChange;
1004}
1005
1006bool
Mark Laceyf9ea8852013-08-14 23:50:04 +00001007UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
1008 LiveIntervals &LIS) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001009 bool DidChange = false;
Jakob Stoklund Olesen57c8f582011-05-06 19:31:19 +00001010 // Split locations referring to OldReg. Iterate backwards so splitLocation can
Eric Christopherbe153e62012-03-15 21:33:35 +00001011 // safely erase unused locations.
Jakob Stoklund Olesen57c8f582011-05-06 19:31:19 +00001012 for (unsigned i = locations.size(); i ; --i) {
1013 unsigned LocNo = i-1;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001014 const MachineOperand *Loc = &locations[LocNo];
1015 if (!Loc->isReg() || Loc->getReg() != OldReg)
1016 continue;
Mark Laceyf9ea8852013-08-14 23:50:04 +00001017 DidChange |= splitLocation(LocNo, NewRegs, LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001018 }
1019 return DidChange;
1020}
1021
Mark Laceyf9ea8852013-08-14 23:50:04 +00001022void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001023 bool DidChange = false;
1024 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
Mark Laceyf9ea8852013-08-14 23:50:04 +00001025 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001026
1027 if (!DidChange)
1028 return;
1029
1030 // Map all of the new virtual registers.
1031 UserValue *UV = lookupVirtReg(OldReg);
1032 for (unsigned i = 0; i != NewRegs.size(); ++i)
Mark Laceyf9ea8852013-08-14 23:50:04 +00001033 mapVirtReg(NewRegs[i], UV);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001034}
1035
1036void LiveDebugVariables::
Mark Laceyf9ea8852013-08-14 23:50:04 +00001037splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001038 if (pImpl)
1039 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
1040}
1041
Reid Kleckner4e040282017-09-20 18:19:08 +00001042void UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI,
1043 BitVector &SpilledLocations) {
Reid Kleckner92687d42017-09-20 17:32:54 +00001044 // Build a set of new locations with new numbers so we can coalesce our
1045 // IntervalMap if two vreg intervals collapse to the same physical location.
1046 // Use MapVector instead of SetVector because MapVector::insert returns the
Reid Kleckner4e040282017-09-20 18:19:08 +00001047 // position of the previously or newly inserted element. The boolean value
1048 // tracks if the location was produced by a spill.
1049 // FIXME: This will be problematic if we ever support direct and indirect
1050 // frame index locations, i.e. expressing both variables in memory and
1051 // 'int x, *px = &x'. The "spilled" bit must become part of the location.
Reid Kleckner92687d42017-09-20 17:32:54 +00001052 MapVector<MachineOperand, bool> NewLocations;
1053 SmallVector<unsigned, 4> LocNoMap(locations.size());
1054 for (unsigned I = 0, E = locations.size(); I != E; ++I) {
Reid Kleckner4e040282017-09-20 18:19:08 +00001055 bool Spilled = false;
Reid Kleckner92687d42017-09-20 17:32:54 +00001056 MachineOperand Loc = locations[I];
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001057 // Only virtual registers are rewritten.
Reid Kleckner92687d42017-09-20 17:32:54 +00001058 if (Loc.isReg() && Loc.getReg() &&
1059 TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
1060 unsigned VirtReg = Loc.getReg();
1061 if (VRM.isAssignedReg(VirtReg) &&
1062 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
1063 // This can create a %noreg operand in rare cases when the sub-register
1064 // index is no longer available. That means the user value is in a
1065 // non-existent sub-register, and %noreg is exactly what we want.
1066 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1067 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1068 // FIXME: Translate SubIdx to a stackslot offset.
1069 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
Reid Kleckner4e040282017-09-20 18:19:08 +00001070 Spilled = true;
Reid Kleckner92687d42017-09-20 17:32:54 +00001071 } else {
1072 Loc.setReg(0);
1073 Loc.setSubReg(0);
1074 }
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001075 }
Reid Kleckner92687d42017-09-20 17:32:54 +00001076
1077 // Insert this location if it doesn't already exist and record a mapping
1078 // from the old number to the new number.
Reid Kleckner4e040282017-09-20 18:19:08 +00001079 auto InsertResult = NewLocations.insert({Loc, Spilled});
1080 unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1081 LocNoMap[I] = NewLocNo;
Reid Kleckner92687d42017-09-20 17:32:54 +00001082 }
1083
Reid Kleckner4e040282017-09-20 18:19:08 +00001084 // Rewrite the locations and record which ones were spill slots.
Reid Kleckner92687d42017-09-20 17:32:54 +00001085 locations.clear();
Reid Kleckner4e040282017-09-20 18:19:08 +00001086 SpilledLocations.clear();
1087 SpilledLocations.resize(NewLocations.size());
1088 for (auto &Pair : NewLocations) {
Reid Kleckner92687d42017-09-20 17:32:54 +00001089 locations.push_back(Pair.first);
Reid Kleckner4e040282017-09-20 18:19:08 +00001090 if (Pair.second) {
1091 unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1092 SpilledLocations.set(NewLocNo);
1093 }
1094 }
Reid Kleckner92687d42017-09-20 17:32:54 +00001095
1096 // Update the interval map, but only coalesce left, since intervals to the
1097 // right use the old location numbers. This should merge two contiguous
1098 // DBG_VALUE intervals with different vregs that were allocated to the same
1099 // physical register.
1100 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
Reid Kleckner04e25e02017-10-03 17:59:02 +00001101 DbgValueLocation Loc = I.value();
Mikael Holmen57b33f62018-06-21 07:02:46 +00001102 // Undef values don't exist in locations (and thus not in LocNoMap either)
1103 // so skip over them. See getLocationNo().
1104 if (Loc.isUndef())
1105 continue;
Reid Kleckner04e25e02017-10-03 17:59:02 +00001106 unsigned NewLocNo = LocNoMap[Loc.locNo()];
1107 I.setValueUnchecked(Loc.changeLocNo(NewLocNo));
Reid Kleckner92687d42017-09-20 17:32:54 +00001108 I.setStart(I.start());
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001109 }
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001110}
1111
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001112/// Find an iterator for inserting a DBG_VALUE instruction.
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001113static MachineBasicBlock::iterator
Devang Patel26ffa012011-02-04 01:43:25 +00001114findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001115 LiveIntervals &LIS) {
1116 SlotIndex Start = LIS.getMBBStartIdx(MBB);
1117 Idx = Idx.getBaseIndex();
1118
1119 // Try to find an insert location by going backwards from Idx.
1120 MachineInstr *MI;
1121 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1122 // We've reached the beginning of MBB.
1123 if (Idx == Start) {
Keith Walker830a8c12016-09-16 14:07:29 +00001124 MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001125 return I;
1126 }
1127 Idx = Idx.getPrevIndex();
1128 }
Devang Patel26ffa012011-02-04 01:43:25 +00001129
Jakob Stoklund Olesen088b30a2011-01-13 23:35:53 +00001130 // Don't insert anything after the first terminator, though.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001131 return MI->isTerminator() ? MBB->getFirstTerminator() :
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001132 std::next(MachineBasicBlock::iterator(MI));
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001133}
1134
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001135/// Find an iterator for inserting the next DBG_VALUE instruction
1136/// (or end if no more insert locations found).
1137static MachineBasicBlock::iterator
1138findNextInsertLocation(MachineBasicBlock *MBB,
1139 MachineBasicBlock::iterator I,
1140 SlotIndex StopIdx, MachineOperand &LocMO,
1141 LiveIntervals &LIS,
1142 const TargetRegisterInfo &TRI) {
1143 if (!LocMO.isReg())
1144 return MBB->instr_end();
1145 unsigned Reg = LocMO.getReg();
1146
1147 // Find the next instruction in the MBB that define the register Reg.
Stefan Maksimovic991af7a2018-02-09 14:03:26 +00001148 while (I != MBB->end() && !I->isTerminator()) {
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001149 if (!LIS.isNotInMIMap(*I) &&
1150 SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
1151 break;
1152 if (I->definesRegister(Reg, &TRI))
1153 // The insert location is directly after the instruction/bundle.
1154 return std::next(I);
1155 ++I;
1156 }
1157 return MBB->end();
1158}
1159
1160void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1161 SlotIndex StopIdx,
Reid Kleckner04e25e02017-10-03 17:59:02 +00001162 DbgValueLocation Loc, bool Spilled,
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001163 LiveIntervals &LIS,
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001164 const TargetInstrInfo &TII,
1165 const TargetRegisterInfo &TRI) {
1166 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1167 // Only search within the current MBB.
1168 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1169 MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS);
Mikael Holmen57b33f62018-06-21 07:02:46 +00001170 // Undef values don't exist in locations so create new "noreg" register MOs
1171 // for them. See getLocationNo().
1172 MachineOperand MO = !Loc.isUndef() ?
1173 locations[Loc.locNo()] :
1174 MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false,
1175 /* isKill */ false, /* isDead */ false,
1176 /* isUndef */ false, /* isEarlyClobber */ false,
1177 /* SubReg */ 0, /* isDebug */ true);
1178
Devang Pateleabc3cea2011-08-04 20:42:11 +00001179 ++NumInsertedDebugValues;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001180
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001181 assert(cast<DILocalVariable>(Variable)
Duncan P. N. Exon Smithe686f152015-04-06 23:27:40 +00001182 ->isValidLocationForIntrinsic(getDebugLoc()) &&
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00001183 "Expected inlined-at fields to agree");
Reid Kleckner4e040282017-09-20 18:19:08 +00001184
1185 // If the location was spilled, the new DBG_VALUE will be indirect. If the
1186 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1187 // that the original virtual register was a pointer.
Reid Kleckner4e040282017-09-20 18:19:08 +00001188 const DIExpression *Expr = Expression;
Reid Kleckner04e25e02017-10-03 17:59:02 +00001189 bool IsIndirect = Loc.wasIndirect();
1190 if (Spilled) {
1191 if (IsIndirect)
1192 Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
1193 IsIndirect = true;
1194 }
Reid Kleckner4e040282017-09-20 18:19:08 +00001195
Reid Kleckner04e25e02017-10-03 17:59:02 +00001196 assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
Reid Kleckner4e040282017-09-20 18:19:08 +00001197
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001198 do {
1199 MachineInstrBuilder MIB =
Reid Kleckner4e040282017-09-20 18:19:08 +00001200 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
Reid Kleckner04e25e02017-10-03 17:59:02 +00001201 .add(MO);
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001202 if (IsIndirect)
1203 MIB.addImm(0U);
1204 else
1205 MIB.addReg(0U, RegState::Debug);
1206 MIB.addMetadata(Variable).addMetadata(Expr);
1207
1208 // Continue and insert DBG_VALUES after every redefinition of register
1209 // associated with the debug value within the range
1210 I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
1211 } while (I != MBB->end());
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001212}
1213
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001214void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
Reid Kleckner4e040282017-09-20 18:19:08 +00001215 const TargetInstrInfo &TII,
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001216 const TargetRegisterInfo &TRI,
Reid Kleckner4e040282017-09-20 18:19:08 +00001217 const BitVector &SpilledLocations) {
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001218 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1219
1220 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1221 SlotIndex Start = I.start();
1222 SlotIndex Stop = I.stop();
Reid Kleckner04e25e02017-10-03 17:59:02 +00001223 DbgValueLocation Loc = I.value();
1224 bool Spilled = !Loc.isUndef() ? SpilledLocations.test(Loc.locNo()) : false;
Robert Lougher10f740d2017-08-03 11:54:02 +00001225
1226 // If the interval start was trimmed to the lexical scope insert the
1227 // DBG_VALUE at the previous index (otherwise it appears after the
1228 // first instruction in the range).
1229 if (trimmedDefs.count(Start))
1230 Start = Start.getPrevIndex();
1231
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001232 LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << Loc.locNo());
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001233 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1234 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001235
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001236 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001237 insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, LIS, TII, TRI);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001238 // This interval may span multiple basic blocks.
1239 // Insert a DBG_VALUE into each one.
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001240 while (Stop > MBBEnd) {
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001241 // Move to the next block.
1242 Start = MBBEnd;
1243 if (++MBB == MFEnd)
1244 break;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001245 MBBEnd = LIS.getMBBEndIdx(&*MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001246 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001247 insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, LIS, TII, TRI);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001248 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001249 LLVM_DEBUG(dbgs() << '\n');
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001250 if (MBB == MFEnd)
1251 break;
1252
1253 ++I;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001254 }
1255}
1256
1257void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001258 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
David Blaikie2f040112014-07-25 16:10:16 +00001259 if (!MF)
1260 return;
Eric Christopherfc6de422014-08-05 02:39:49 +00001261 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Reid Kleckner4e040282017-09-20 18:19:08 +00001262 BitVector SpilledLocations;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001263 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001264 LLVM_DEBUG(userValues[i]->print(dbgs(), TRI));
Reid Kleckner4e040282017-09-20 18:19:08 +00001265 userValues[i]->rewriteLocations(*VRM, *TRI, SpilledLocations);
Karl-Johan Karlsson8d8d2012017-10-05 08:37:31 +00001266 userValues[i]->emitDebugValues(VRM, *LIS, *TII, *TRI, SpilledLocations);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001267 }
Manman Ren7a4c8a72013-02-13 20:23:48 +00001268 EmitDone = true;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001269}
1270
1271void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
Manman Ren7a4c8a72013-02-13 20:23:48 +00001272 if (pImpl)
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001273 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1274}
1275
David Blaikie2f040112014-07-25 16:10:16 +00001276bool LiveDebugVariables::doInitialization(Module &M) {
David Blaikie2f040112014-07-25 16:10:16 +00001277 return Pass::doInitialization(M);
1278}
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001279
Aaron Ballman615eb472017-10-15 14:32:27 +00001280#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Clegg705f7982017-06-21 22:19:17 +00001281LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +00001282 if (pImpl)
1283 static_cast<LDVImpl*>(pImpl)->print(dbgs());
1284}
1285#endif