blob: 69297a339d7413aa8689c77a8061262c41c6ce3b [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"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000023#include "llvm/ADT/IntervalMap.h"
Devang Patelb4568662011-08-04 18:45:38 +000024#include "llvm/ADT/Statistic.h"
Devang Patel37a62052011-08-10 21:25:34 +000025#include "llvm/CodeGen/LexicalScopes.h"
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000026#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000027#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000031#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000032#include "llvm/CodeGen/VirtRegMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000034#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Metadata.h"
36#include "llvm/IR/Value.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000037#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000039#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +000040#include "llvm/Target/TargetInstrInfo.h"
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000041#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000042#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000043#include "llvm/Target/TargetSubtargetInfo.h"
David Blaikie2b1dfa72014-04-21 20:37:07 +000044#include <memory>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000045#include <utility>
David Blaikie2b1dfa72014-04-21 20:37:07 +000046
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000047using namespace llvm;
48
Chandler Carruth1b9dde02014-04-22 02:02:50 +000049#define DEBUG_TYPE "livedebug"
50
Devang Patelacbee0b2011-01-07 22:33:41 +000051static cl::opt<bool>
Jakob Stoklund Olesen74ded572011-01-12 23:36:21 +000052EnableLDV("live-debug-variables", cl::init(true),
Devang Patelacbee0b2011-01-07 22:33:41 +000053 cl::desc("Enable the live debug variables pass"), cl::Hidden);
54
Devang Patelb4568662011-08-04 18:45:38 +000055STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000056char LiveDebugVariables::ID = 0;
57
58INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
59 "Debug Variable Analysis", false, false)
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000060INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000061INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
62INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
63 "Debug Variable Analysis", false, false)
64
65void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000066 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000067 AU.addRequiredTransitive<LiveIntervals>();
68 AU.setPreservesAll();
69 MachineFunctionPass::getAnalysisUsage(AU);
70}
71
Craig Topperc0196b12014-04-14 00:51:57 +000072LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(nullptr) {
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +000073 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
74}
75
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +000076/// LocMap - Map of where a user value is live, and its location.
77typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
78
Benjamin Kramer67b014b2011-09-16 00:35:06 +000079namespace {
Eric Christopher9d7d5da2013-11-20 00:54:25 +000080/// UserValueScopes - Keeps track of lexical scopes associated with a
Devang Patelf9e2ae92011-09-13 18:40:53 +000081/// user value's source location.
82class UserValueScopes {
83 DebugLoc DL;
84 LexicalScopes &LS;
85 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
86
87public:
Benjamin Kramer82de7d32016-05-27 14:27:24 +000088 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
Devang Patelf9e2ae92011-09-13 18:40:53 +000089
90 /// dominates - Return true if current scope dominates at least one machine
91 /// instruction in a given machine basic block.
92 bool dominates(MachineBasicBlock *MBB) {
93 if (LBlocks.empty())
94 LS.getMachineBasicBlocks(DL, LBlocks);
Rafael Espindola84921b92015-10-24 23:11:13 +000095 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
Devang Patelf9e2ae92011-09-13 18:40:53 +000096 }
97};
Benjamin Kramer67b014b2011-09-16 00:35:06 +000098} // end anonymous namespace
Devang Patelf9e2ae92011-09-13 18:40:53 +000099
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000100/// UserValue - A user value is a part of a debug info user variable.
101///
102/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
103/// holds part of a user variable. The part is identified by a byte offset.
104///
105/// UserValues are grouped into equivalence classes for easier searching. Two
106/// user values are related if they refer to the same variable, or if they are
107/// held by the same virtual register. The equivalence class is the transitive
108/// closure of that relation.
109namespace {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000110class LDVImpl;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000111class UserValue {
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000112 const MDNode *Variable; ///< The debug info variable we are part of.
113 const MDNode *Expression; ///< Any complex address expression.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000114 unsigned offset; ///< Byte offset into variable.
Adrian Prantl418d1d12013-07-09 20:28:37 +0000115 bool IsIndirect; ///< true if this is a register-indirect+offset value.
Devang Patel26ffa012011-02-04 01:43:25 +0000116 DebugLoc dl; ///< The debug location for the variable. This is
117 ///< used by dwarf writer to find lexical scope.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000118 UserValue *leader; ///< Equivalence class leader.
119 UserValue *next; ///< Next value in equivalence class, or null.
120
121 /// Numbered locations referenced by locmap.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000122 SmallVector<MachineOperand, 4> locations;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000123
124 /// Map of slot indices where this value is live.
125 LocMap locInts;
126
Jakob Stoklund Olesen44086032010-12-03 22:25:07 +0000127 /// coalesceLocation - After LocNo was changed, check if it has become
128 /// identical to another location, and coalesce them. This may cause LocNo or
129 /// a later location to be erased, but no earlier location will be erased.
130 void coalesceLocation(unsigned LocNo);
131
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000132 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
133 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
134 LiveIntervals &LIS, const TargetInstrInfo &TII);
135
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000136 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
137 /// is live. Returns true if any changes were made.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000138 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
139 LiveIntervals &LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000140
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000141public:
142 /// UserValue - Create a new UserValue.
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000143 UserValue(const MDNode *var, const MDNode *expr, unsigned o, bool i,
144 DebugLoc L, LocMap::Allocator &alloc)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000145 : Variable(var), Expression(expr), offset(o), IsIndirect(i),
146 dl(std::move(L)), leader(this), next(nullptr), locInts(alloc) {}
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000147
148 /// getLeader - Get the leader of this value's equivalence class.
149 UserValue *getLeader() {
150 UserValue *l = leader;
151 while (l != l->leader)
152 l = l->leader;
153 return leader = l;
154 }
155
156 /// getNext - Return the next UserValue in the equivalence class.
157 UserValue *getNext() const { return next; }
158
Devang Patel338e4322011-07-06 23:09:51 +0000159 /// match - Does this UserValue match the parameters?
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000160 bool match(const MDNode *Var, const MDNode *Expr, const DILocation *IA,
Duncan P. N. Exon Smith7bb480d2015-04-16 22:27:54 +0000161 unsigned Offset, bool indirect) const {
162 return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA &&
163 Offset == offset && indirect == IsIndirect;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000164 }
165
166 /// merge - Merge equivalence classes.
167 static UserValue *merge(UserValue *L1, UserValue *L2) {
168 L2 = L2->getLeader();
169 if (!L1)
170 return L2;
171 L1 = L1->getLeader();
172 if (L1 == L2)
173 return L1;
174 // Splice L2 before L1's members.
175 UserValue *End = L2;
Richard Trieu7a083812016-02-18 22:09:30 +0000176 while (End->next) {
177 End->leader = L1;
178 End = End->next;
179 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000180 End->leader = L1;
181 End->next = L1->next;
182 L1->next = L2;
183 return L1;
184 }
185
186 /// getLocationNo - Return the location number that matches Loc.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000187 unsigned getLocationNo(const MachineOperand &LocMO) {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000188 if (LocMO.isReg()) {
189 if (LocMO.getReg() == 0)
190 return ~0u;
191 // For register locations we dont care about use/def and other flags.
192 for (unsigned i = 0, e = locations.size(); i != e; ++i)
193 if (locations[i].isReg() &&
194 locations[i].getReg() == LocMO.getReg() &&
195 locations[i].getSubReg() == LocMO.getSubReg())
196 return i;
197 } else
198 for (unsigned i = 0, e = locations.size(); i != e; ++i)
199 if (LocMO.isIdenticalTo(locations[i]))
200 return i;
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000201 locations.push_back(LocMO);
202 // We are storing a MachineOperand outside a MachineInstr.
203 locations.back().clearParent();
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000204 // Don't store def operands.
205 if (locations.back().isReg())
206 locations.back().setIsUse();
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000207 return locations.size() - 1;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000208 }
209
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000210 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
211 void mapVirtRegs(LDVImpl *LDV);
212
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000213 /// addDef - Add a definition point to this value.
214 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
215 // Add a singular (Idx,Idx) -> Loc mapping.
216 LocMap::iterator I = locInts.find(Idx);
217 if (!I.valid() || I.start() != Idx)
218 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
Jakob Stoklund Olesen2539af62011-08-03 23:44:31 +0000219 else
220 // A later DBG_VALUE at the same SlotIndex overrides the old location.
221 I.setValue(getLocationNo(LocMO));
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000222 }
223
224 /// extendDef - Extend the current definition as far as possible down the
225 /// dominator tree. Stop when meeting an existing def or when leaving the live
226 /// range of VNI.
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000227 /// End points where VNI is no longer live are added to Kills.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000228 /// @param Idx Starting point for the definition.
229 /// @param LocNo Location number to propagate.
Matthias Braun34e1be92013-10-10 21:29:02 +0000230 /// @param LR Restrict liveness to where LR has the value VNI. May be null.
231 /// @param VNI When LR is not null, this is the value to restrict to.
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000232 /// @param Kills Append end points of VNI's live range to Kills.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000233 /// @param LIS Live intervals analysis.
234 /// @param MDT Dominator tree.
235 void extendDef(SlotIndex Idx, unsigned LocNo,
Matthias Braun34e1be92013-10-10 21:29:02 +0000236 LiveRange *LR, const VNInfo *VNI,
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000237 SmallVectorImpl<SlotIndex> *Kills,
Devang Patel37a62052011-08-10 21:25:34 +0000238 LiveIntervals &LIS, MachineDominatorTree &MDT,
Eric Christopher6a0c6792012-03-15 21:33:39 +0000239 UserValueScopes &UVS);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000240
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000241 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
242 /// registers. Determine if any of the copies are available at the kill
243 /// points, and add defs if possible.
244 /// @param LI Scan for copies of the value in LI->reg.
245 /// @param LocNo Location number of LI->reg.
246 /// @param Kills Points where the range of LocNo could be extended.
247 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
248 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
249 const SmallVectorImpl<SlotIndex> &Kills,
250 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
251 MachineRegisterInfo &MRI,
252 LiveIntervals &LIS);
253
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000254 /// computeIntervals - Compute the live intervals of all locations after
255 /// collecting all their def points.
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000256 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
Devang Patel37a62052011-08-10 21:25:34 +0000257 LiveIntervals &LIS, MachineDominatorTree &MDT,
Devang Patelf9e2ae92011-09-13 18:40:53 +0000258 UserValueScopes &UVS);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000259
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000260 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
261 /// live. Returns true if any changes were made.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000262 bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
263 LiveIntervals &LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000264
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000265 /// rewriteLocations - Rewrite virtual register locations according to the
266 /// provided virtual register map.
267 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
268
Eric Christopherbc671702013-02-13 02:29:18 +0000269 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000270 void emitDebugValues(VirtRegMap *VRM,
271 LiveIntervals &LIS, const TargetInstrInfo &TRI);
272
Devang Patelf9e2ae92011-09-13 18:40:53 +0000273 /// getDebugLoc - Return DebugLoc of this UserValue.
274 DebugLoc getDebugLoc() { return dl;}
Eric Christopher1cdefae2015-02-27 00:11:34 +0000275 void print(raw_ostream &, const TargetRegisterInfo *);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000276};
277} // namespace
278
279/// LDVImpl - Implementation of the LiveDebugVariables pass.
280namespace {
281class LDVImpl {
282 LiveDebugVariables &pass;
283 LocMap::Allocator allocator;
284 MachineFunction *MF;
285 LiveIntervals *LIS;
Devang Patel37a62052011-08-10 21:25:34 +0000286 LexicalScopes LS;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000287 MachineDominatorTree *MDT;
288 const TargetRegisterInfo *TRI;
289
Manman Ren7a4c8a72013-02-13 20:23:48 +0000290 /// Whether emitDebugValues is called.
291 bool EmitDone;
292 /// Whether the machine function is modified during the pass.
293 bool ModifiedMF;
294
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000295 /// userValues - All allocated UserValue instances.
David Blaikie2b1dfa72014-04-21 20:37:07 +0000296 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000297
298 /// Map virtual register to eq class leader.
299 typedef DenseMap<unsigned, UserValue*> VRMap;
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000300 VRMap virtRegToEqClass;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000301
302 /// Map user variable to eq class leader.
303 typedef DenseMap<const MDNode *, UserValue*> UVMap;
304 UVMap userVarMap;
305
306 /// getUserValue - Find or create a UserValue.
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000307 UserValue *getUserValue(const MDNode *Var, const MDNode *Expr,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000308 unsigned Offset, bool IsIndirect, const DebugLoc &DL);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000309
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000310 /// lookupVirtReg - Find the EC leader for VirtReg or null.
311 UserValue *lookupVirtReg(unsigned VirtReg);
312
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000313 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
314 /// @param MI DBG_VALUE instruction
315 /// @param Idx Last valid SLotIndex before instruction.
316 /// @return True if the DBG_VALUE instruction should be deleted.
317 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
318
319 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
320 /// a UserValue def for each instruction.
321 /// @param mf MachineFunction to be scanned.
322 /// @return True if any debug values were found.
323 bool collectDebugValues(MachineFunction &mf);
324
325 /// computeIntervals - Compute the live intervals of all user values after
326 /// collecting all their def points.
327 void computeIntervals();
328
329public:
David Blaikie2f040112014-07-25 16:10:16 +0000330 LDVImpl(LiveDebugVariables *ps)
331 : pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {}
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000332 bool runOnMachineFunction(MachineFunction &mf);
333
Manman Ren7a4c8a72013-02-13 20:23:48 +0000334 /// clear - Release all memory.
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000335 void clear() {
David Blaikie2f040112014-07-25 16:10:16 +0000336 MF = nullptr;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000337 userValues.clear();
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000338 virtRegToEqClass.clear();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000339 userVarMap.clear();
Manman Ren7a4c8a72013-02-13 20:23:48 +0000340 // Make sure we call emitDebugValues if the machine function was modified.
341 assert((!ModifiedMF || EmitDone) &&
342 "Dbg values are not emitted in LDV");
343 EmitDone = false;
344 ModifiedMF = false;
Marcello Maggioni22594002014-10-24 02:46:50 +0000345 LS.reset();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000346 }
347
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000348 /// mapVirtReg - Map virtual register to an equivalence class.
349 void mapVirtReg(unsigned VirtReg, UserValue *EC);
350
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000351 /// splitRegister - Replace all references to OldReg with NewRegs.
Mark Laceyf9ea8852013-08-14 23:50:04 +0000352 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000353
Eric Christopherbc671702013-02-13 02:29:18 +0000354 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000355 void emitDebugValues(VirtRegMap *VRM);
356
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000357 void print(raw_ostream&);
358};
359} // namespace
360
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000361static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000362 const LLVMContext &Ctx) {
363 if (!DL)
364 return;
365
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000366 auto *Scope = cast<DIScope>(DL.getScope());
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000367 // Omit the directory, because it's likely to be long and uninteresting.
Duncan P. N. Exon Smithb273d062015-04-16 01:37:00 +0000368 CommentOS << Scope->getFilename();
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000369 CommentOS << ':' << DL.getLine();
370 if (DL.getCol() != 0)
371 CommentOS << ':' << DL.getCol();
372
373 DebugLoc InlinedAtDL = DL.getInlinedAt();
374 if (!InlinedAtDL)
375 return;
376
377 CommentOS << " @[ ";
378 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
379 CommentOS << " ]";
380}
381
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000382static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
383 const DILocation *DL) {
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000384 const LLVMContext &Ctx = V->getContext();
385 StringRef Res = V->getName();
386 if (!Res.empty())
387 OS << Res << "," << V->getLine();
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +0000388 if (auto *InlinedAt = DL->getInlinedAt()) {
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000389 if (DebugLoc InlinedAtDL = InlinedAt) {
390 OS << " @[";
391 printDebugLoc(InlinedAtDL, OS, Ctx);
392 OS << "]";
393 }
394 }
395}
396
Eric Christopher1cdefae2015-02-27 00:11:34 +0000397void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000398 auto *DV = cast<DILocalVariable>(Variable);
Frederic Risse6bb1872014-08-07 20:04:00 +0000399 OS << "!\"";
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +0000400 printExtendedName(OS, DV, dl);
Duncan P. N. Exon Smith32e7f282015-04-14 02:09:32 +0000401
Devang Patel6c1ed312011-08-09 01:03:35 +0000402 OS << "\"\t";
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000403 if (offset)
404 OS << '+' << offset;
405 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
406 OS << " [" << I.start() << ';' << I.stop() << "):";
407 if (I.value() == ~0u)
408 OS << "undef";
409 else
410 OS << I.value();
411 }
Jakob Stoklund Olesenc86fe052011-05-06 17:59:59 +0000412 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
413 OS << " Loc" << i << '=';
Eric Christopher1cdefae2015-02-27 00:11:34 +0000414 locations[i].print(OS, TRI);
Jakob Stoklund Olesenc86fe052011-05-06 17:59:59 +0000415 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000416 OS << '\n';
417}
418
419void LDVImpl::print(raw_ostream &OS) {
420 OS << "********** DEBUG VARIABLES **********\n";
421 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
Eric Christopher1cdefae2015-02-27 00:11:34 +0000422 userValues[i]->print(OS, TRI);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000423}
424
Jakob Stoklund Olesen44086032010-12-03 22:25:07 +0000425void UserValue::coalesceLocation(unsigned LocNo) {
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000426 unsigned KeepLoc = 0;
427 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
428 if (KeepLoc == LocNo)
429 continue;
430 if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
431 break;
Jakob Stoklund Olesen44086032010-12-03 22:25:07 +0000432 }
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000433 // No matches.
434 if (KeepLoc == locations.size())
435 return;
436
437 // Keep the smaller location, erase the larger one.
438 unsigned EraseLoc = LocNo;
439 if (KeepLoc > EraseLoc)
440 std::swap(KeepLoc, EraseLoc);
Jakob Stoklund Olesen44086032010-12-03 22:25:07 +0000441 locations.erase(locations.begin() + EraseLoc);
442
443 // Rewrite values.
444 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
445 unsigned v = I.value();
446 if (v == EraseLoc)
447 I.setValue(KeepLoc); // Coalesce when possible.
448 else if (v > EraseLoc)
449 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
450 }
451}
452
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000453void UserValue::mapVirtRegs(LDVImpl *LDV) {
454 for (unsigned i = 0, e = locations.size(); i != e; ++i)
455 if (locations[i].isReg() &&
456 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
457 LDV->mapVirtReg(locations[i].getReg(), this);
458}
459
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000460UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr,
461 unsigned Offset, bool IsIndirect,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000462 const DebugLoc &DL) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000463 UserValue *&Leader = userVarMap[Var];
464 if (Leader) {
465 UserValue *UV = Leader->getLeader();
466 Leader = UV;
467 for (; UV; UV = UV->getNext())
Duncan P. N. Exon Smith7bb480d2015-04-16 22:27:54 +0000468 if (UV->match(Var, Expr, DL->getInlinedAt(), Offset, IsIndirect))
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000469 return UV;
470 }
471
David Blaikie2b1dfa72014-04-21 20:37:07 +0000472 userValues.push_back(
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000473 make_unique<UserValue>(Var, Expr, Offset, IsIndirect, DL, allocator));
David Blaikie2b1dfa72014-04-21 20:37:07 +0000474 UserValue *UV = userValues.back().get();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000475 Leader = UserValue::merge(Leader, UV);
476 return UV;
477}
478
479void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
480 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000481 UserValue *&Leader = virtRegToEqClass[VirtReg];
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000482 Leader = UserValue::merge(Leader, EC);
483}
484
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000485UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen922e1fa2010-12-03 22:25:09 +0000486 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000487 return UV->getLeader();
Craig Topperc0196b12014-04-14 00:51:57 +0000488 return nullptr;
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000489}
490
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000491bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
492 // DBG_VALUE loc, offset, variable
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000493 if (MI->getNumOperands() != 4 ||
Adrian Prantl418d1d12013-07-09 20:28:37 +0000494 !(MI->getOperand(1).isReg() || MI->getOperand(1).isImm()) ||
495 !MI->getOperand(2).isMetadata()) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000496 DEBUG(dbgs() << "Can't handle " << *MI);
497 return false;
498 }
499
500 // Get or create the UserValue for (variable,offset).
Adrian Prantldb3e26d2013-09-16 23:29:03 +0000501 bool IsIndirect = MI->isIndirectDebugValue();
Adrian Prantl418d1d12013-07-09 20:28:37 +0000502 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000503 const MDNode *Var = MI->getDebugVariable();
504 const MDNode *Expr = MI->getDebugExpression();
Adrian Prantldb3e26d2013-09-16 23:29:03 +0000505 //here.
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000506 UserValue *UV =
507 getUserValue(Var, Expr, Offset, IsIndirect, MI->getDebugLoc());
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000508 UV->addDef(Idx, MI->getOperand(0));
509 return true;
510}
511
512bool LDVImpl::collectDebugValues(MachineFunction &mf) {
513 bool Changed = false;
514 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
515 ++MFI) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000516 MachineBasicBlock *MBB = &*MFI;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000517 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
518 MBBI != MBBE;) {
519 if (!MBBI->isDebugValue()) {
520 ++MBBI;
521 continue;
522 }
523 // DBG_VALUE has no slot index, use the previous instruction instead.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000524 SlotIndex Idx =
525 MBBI == MBB->begin()
526 ? LIS->getMBBStartIdx(MBB)
527 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000528 // Handle consecutive DBG_VALUE instructions with the same slot index.
529 do {
530 if (handleDebugValue(MBBI, Idx)) {
531 MBBI = MBB->erase(MBBI);
532 Changed = true;
533 } else
534 ++MBBI;
535 } while (MBBI != MBBE && MBBI->isDebugValue());
536 }
537 }
538 return Changed;
539}
540
Adrian Prantlce858132015-12-21 20:03:00 +0000541/// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
542/// data-flow analysis to propagate them beyond basic block boundaries.
543void UserValue::extendDef(SlotIndex Idx, unsigned LocNo, LiveRange *LR,
544 const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
Devang Patel37a62052011-08-10 21:25:34 +0000545 LiveIntervals &LIS, MachineDominatorTree &MDT,
Eric Christopher6a0c6792012-03-15 21:33:39 +0000546 UserValueScopes &UVS) {
Adrian Prantlce858132015-12-21 20:03:00 +0000547 SlotIndex Start = Idx;
548 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
549 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
550 LocMap::iterator I = locInts.find(Start);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000551
Adrian Prantlce858132015-12-21 20:03:00 +0000552 // Limit to VNI's live range.
553 bool ToEnd = true;
554 if (LR && VNI) {
555 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
556 if (!Segment || Segment->valno != VNI) {
557 if (Kills)
558 Kills->push_back(Start);
559 return;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000560 }
Richard Trieu7a083812016-02-18 22:09:30 +0000561 if (Segment->end < Stop) {
562 Stop = Segment->end;
563 ToEnd = false;
564 }
Adrian Prantlce858132015-12-21 20:03:00 +0000565 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000566
Adrian Prantlce858132015-12-21 20:03:00 +0000567 // There could already be a short def at Start.
568 if (I.valid() && I.start() <= Start) {
569 // Stop when meeting a different location or an already extended interval.
570 Start = Start.getNextSlot();
571 if (I.value() != LocNo || I.stop() != Start)
572 return;
573 // This is a one-slot placeholder. Just skip it.
574 ++I;
575 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000576
Adrian Prantlce858132015-12-21 20:03:00 +0000577 // Limited by the next def.
Richard Trieu7a083812016-02-18 22:09:30 +0000578 if (I.valid() && I.start() < Stop) {
579 Stop = I.start();
580 ToEnd = false;
581 }
Adrian Prantlce858132015-12-21 20:03:00 +0000582 // Limited by VNI's live range.
583 else if (!ToEnd && Kills)
584 Kills->push_back(Stop);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000585
Adrian Prantlce858132015-12-21 20:03:00 +0000586 if (Start < Stop)
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000587 I.insert(Start, Stop, LocNo);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000588}
589
590void
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000591UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
592 const SmallVectorImpl<SlotIndex> &Kills,
593 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
594 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
595 if (Kills.empty())
596 return;
597 // Don't track copies from physregs, there are too many uses.
598 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
599 return;
600
601 // Collect all the (vreg, valno) pairs that are copies of LI.
602 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
Owen Andersonb36376e2014-03-17 19:36:09 +0000603 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
604 MachineInstr *MI = MO.getParent();
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000605 // Copies of the full value.
Owen Andersonb36376e2014-03-17 19:36:09 +0000606 if (MO.getSubReg() || !MI->isCopy())
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000607 continue;
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000608 unsigned DstReg = MI->getOperand(0).getReg();
609
Jakob Stoklund Olesenec0ac3c2011-03-22 22:33:08 +0000610 // Don't follow copies to physregs. These are usually setting up call
611 // arguments, and the argument registers are always call clobbered. We are
612 // better off in the source register which could be a callee-saved register,
613 // or it could be spilled.
614 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
615 continue;
616
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000617 // Is LocNo extended to reach this copy? If not, another def may be blocking
618 // it, or we are looking at a wrong value of LI.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000619 SlotIndex Idx = LIS.getInstructionIndex(*MI);
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000620 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000621 if (!I.valid() || I.value() != LocNo)
622 continue;
623
624 if (!LIS.hasInterval(DstReg))
625 continue;
626 LiveInterval *DstLI = &LIS.getInterval(DstReg);
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000627 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
628 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000629 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
630 }
631
632 if (CopyValues.empty())
633 return;
634
635 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
636
637 // Try to add defs of the copied values for each kill point.
638 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
639 SlotIndex Idx = Kills[i];
640 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
641 LiveInterval *DstLI = CopyValues[j].first;
642 const VNInfo *DstVNI = CopyValues[j].second;
643 if (DstLI->getVNInfoAt(Idx) != DstVNI)
644 continue;
645 // Check that there isn't already a def at Idx
646 LocMap::iterator I = locInts.find(Idx);
647 if (I.valid() && I.start() <= Idx)
648 continue;
649 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
650 << DstVNI->id << " in " << *DstLI << '\n');
651 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
652 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
653 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
654 I.insert(Idx, Idx.getNextSlot(), LocNo);
655 NewDefs.push_back(std::make_pair(Idx, LocNo));
656 break;
657 }
658 }
659}
660
661void
662UserValue::computeIntervals(MachineRegisterInfo &MRI,
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000663 const TargetRegisterInfo &TRI,
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000664 LiveIntervals &LIS,
Devang Patel37a62052011-08-10 21:25:34 +0000665 MachineDominatorTree &MDT,
Eric Christopher6a0c6792012-03-15 21:33:39 +0000666 UserValueScopes &UVS) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000667 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
668
669 // Collect all defs to be extended (Skipping undefs).
670 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
671 if (I.value() != ~0u)
672 Defs.push_back(std::make_pair(I.start(), I.value()));
673
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000674 // Extend all defs, and possibly add new ones along the way.
675 for (unsigned i = 0; i != Defs.size(); ++i) {
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000676 SlotIndex Idx = Defs[i].first;
677 unsigned LocNo = Defs[i].second;
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000678 const MachineOperand &Loc = locations[LocNo];
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000679
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000680 if (!Loc.isReg()) {
Craig Topperc0196b12014-04-14 00:51:57 +0000681 extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS, MDT, UVS);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000682 continue;
683 }
684
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000685 // Register locations are constrained to where the register value is live.
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000686 if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
Craig Topperc0196b12014-04-14 00:51:57 +0000687 LiveInterval *LI = nullptr;
688 const VNInfo *VNI = nullptr;
Jakob Stoklund Olesen48a16472012-06-22 18:51:35 +0000689 if (LIS.hasInterval(Loc.getReg())) {
690 LI = &LIS.getInterval(Loc.getReg());
691 VNI = LI->getVNInfoAt(Idx);
692 }
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000693 SmallVector<SlotIndex, 16> Kills;
Devang Patelf9e2ae92011-09-13 18:40:53 +0000694 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, UVS);
Jakob Stoklund Olesen48a16472012-06-22 18:51:35 +0000695 if (LI)
696 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000697 continue;
698 }
699
700 // For physregs, use the live range of the first regunit as a guide.
701 unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
Matthias Braun34e1be92013-10-10 21:29:02 +0000702 LiveRange *LR = &LIS.getRegUnit(Unit);
703 const VNInfo *VNI = LR->getVNInfoAt(Idx);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000704 // Don't track copies from physregs, it is too expensive.
Craig Topperc0196b12014-04-14 00:51:57 +0000705 extendDef(Idx, LocNo, LR, VNI, nullptr, LIS, MDT, UVS);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000706 }
707
708 // Finally, erase all the undefs.
709 for (LocMap::iterator I = locInts.begin(); I.valid();)
710 if (I.value() == ~0u)
711 I.erase();
712 else
713 ++I;
714}
715
716void LDVImpl::computeIntervals() {
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000717 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
Devang Patelf9e2ae92011-09-13 18:40:53 +0000718 UserValueScopes UVS(userValues[i]->getDebugLoc(), LS);
Jakob Stoklund Olesen32449632012-06-22 17:15:32 +0000719 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, *MDT, UVS);
Jakob Stoklund Olesen816f5f42011-03-18 21:42:19 +0000720 userValues[i]->mapVirtRegs(this);
721 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000722}
723
724bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
David Blaikie2f040112014-07-25 16:10:16 +0000725 clear();
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000726 MF = &mf;
727 LIS = &pass.getAnalysis<LiveIntervals>();
728 MDT = &pass.getAnalysis<MachineDominatorTree>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000729 TRI = mf.getSubtarget().getRegisterInfo();
Devang Patel37a62052011-08-10 21:25:34 +0000730 LS.initialize(mf);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000731 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
David Blaikiec8c29202012-08-22 17:18:53 +0000732 << mf.getName() << " **********\n");
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000733
734 bool Changed = collectDebugValues(mf);
735 computeIntervals();
736 DEBUG(print(dbgs()));
Manman Ren7a4c8a72013-02-13 20:23:48 +0000737 ModifiedMF = Changed;
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000738 return Changed;
739}
740
David Blaikie2f040112014-07-25 16:10:16 +0000741static void removeDebugValues(MachineFunction &mf) {
742 for (MachineBasicBlock &MBB : mf) {
743 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
744 if (!MBBI->isDebugValue()) {
745 ++MBBI;
746 continue;
747 }
748 MBBI = MBB.erase(MBBI);
749 }
750 }
751}
752
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +0000753bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
Devang Patelacbee0b2011-01-07 22:33:41 +0000754 if (!EnableLDV)
755 return false;
Peter Collingbourned4bff302015-11-05 22:03:56 +0000756 if (!mf.getFunction()->getSubprogram()) {
David Blaikie2f040112014-07-25 16:10:16 +0000757 removeDebugValues(mf);
758 return false;
759 }
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000760 if (!pImpl)
761 pImpl = new LDVImpl(this);
Manman Ren7a4c8a72013-02-13 20:23:48 +0000762 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000763}
764
765void LiveDebugVariables::releaseMemory() {
Manman Ren7a4c8a72013-02-13 20:23:48 +0000766 if (pImpl)
Jakob Stoklund Olesen4be0bd72010-12-02 00:37:37 +0000767 static_cast<LDVImpl*>(pImpl)->clear();
768}
769
770LiveDebugVariables::~LiveDebugVariables() {
771 if (pImpl)
772 delete static_cast<LDVImpl*>(pImpl);
Jakob Stoklund Olesend4900a62010-11-30 02:17:10 +0000773}
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +0000774
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000775//===----------------------------------------------------------------------===//
776// Live Range Splitting
777//===----------------------------------------------------------------------===//
778
779bool
Mark Laceyf9ea8852013-08-14 23:50:04 +0000780UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
781 LiveIntervals& LIS) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000782 DEBUG({
783 dbgs() << "Splitting Loc" << OldLocNo << '\t';
Craig Topperc0196b12014-04-14 00:51:57 +0000784 print(dbgs(), nullptr);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000785 });
786 bool DidChange = false;
787 LocMap::iterator LocMapI;
788 LocMapI.setMap(locInts);
789 for (unsigned i = 0; i != NewRegs.size(); ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000790 LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000791 if (LI->empty())
792 continue;
793
794 // Don't allocate the new LocNo until it is needed.
795 unsigned NewLocNo = ~0u;
796
797 // Iterate over the overlaps between locInts and LI.
798 LocMapI.find(LI->beginIndex());
799 if (!LocMapI.valid())
800 continue;
801 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
802 LiveInterval::iterator LIE = LI->end();
803 while (LocMapI.valid() && LII != LIE) {
804 // At this point, we know that LocMapI.stop() > LII->start.
805 LII = LI->advanceTo(LII, LocMapI.start());
806 if (LII == LIE)
807 break;
808
809 // Now LII->end > LocMapI.start(). Do we have an overlap?
810 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
811 // Overlapping correct location. Allocate NewLocNo now.
812 if (NewLocNo == ~0u) {
813 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
814 MO.setSubReg(locations[OldLocNo].getSubReg());
815 NewLocNo = getLocationNo(MO);
816 DidChange = true;
817 }
818
819 SlotIndex LStart = LocMapI.start();
820 SlotIndex LStop = LocMapI.stop();
821
822 // Trim LocMapI down to the LII overlap.
823 if (LStart < LII->start)
824 LocMapI.setStartUnchecked(LII->start);
825 if (LStop > LII->end)
826 LocMapI.setStopUnchecked(LII->end);
827
828 // Change the value in the overlap. This may trigger coalescing.
829 LocMapI.setValue(NewLocNo);
830
831 // Re-insert any removed OldLocNo ranges.
832 if (LStart < LocMapI.start()) {
833 LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
834 ++LocMapI;
835 assert(LocMapI.valid() && "Unexpected coalescing");
836 }
837 if (LStop > LocMapI.stop()) {
838 ++LocMapI;
839 LocMapI.insert(LII->end, LStop, OldLocNo);
840 --LocMapI;
841 }
842 }
843
844 // Advance to the next overlap.
845 if (LII->end < LocMapI.stop()) {
846 if (++LII == LIE)
847 break;
848 LocMapI.advanceTo(LII->start);
849 } else {
850 ++LocMapI;
851 if (!LocMapI.valid())
852 break;
853 LII = LI->advanceTo(LII, LocMapI.start());
854 }
855 }
856 }
857
858 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
859 locations.erase(locations.begin() + OldLocNo);
860 LocMapI.goToBegin();
861 while (LocMapI.valid()) {
862 unsigned v = LocMapI.value();
863 if (v == OldLocNo) {
864 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
865 << LocMapI.stop() << ")\n");
866 LocMapI.erase();
867 } else {
868 if (v > OldLocNo)
869 LocMapI.setValueUnchecked(v-1);
870 ++LocMapI;
871 }
872 }
873
Craig Topperc0196b12014-04-14 00:51:57 +0000874 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000875 return DidChange;
876}
877
878bool
Mark Laceyf9ea8852013-08-14 23:50:04 +0000879UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
880 LiveIntervals &LIS) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000881 bool DidChange = false;
Jakob Stoklund Olesen57c8f582011-05-06 19:31:19 +0000882 // Split locations referring to OldReg. Iterate backwards so splitLocation can
Eric Christopherbe153e62012-03-15 21:33:35 +0000883 // safely erase unused locations.
Jakob Stoklund Olesen57c8f582011-05-06 19:31:19 +0000884 for (unsigned i = locations.size(); i ; --i) {
885 unsigned LocNo = i-1;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000886 const MachineOperand *Loc = &locations[LocNo];
887 if (!Loc->isReg() || Loc->getReg() != OldReg)
888 continue;
Mark Laceyf9ea8852013-08-14 23:50:04 +0000889 DidChange |= splitLocation(LocNo, NewRegs, LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000890 }
891 return DidChange;
892}
893
Mark Laceyf9ea8852013-08-14 23:50:04 +0000894void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000895 bool DidChange = false;
896 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
Mark Laceyf9ea8852013-08-14 23:50:04 +0000897 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000898
899 if (!DidChange)
900 return;
901
902 // Map all of the new virtual registers.
903 UserValue *UV = lookupVirtReg(OldReg);
904 for (unsigned i = 0; i != NewRegs.size(); ++i)
Mark Laceyf9ea8852013-08-14 23:50:04 +0000905 mapVirtReg(NewRegs[i], UV);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000906}
907
908void LiveDebugVariables::
Mark Laceyf9ea8852013-08-14 23:50:04 +0000909splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000910 if (pImpl)
911 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
912}
913
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000914void
915UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
916 // Iterate over locations in reverse makes it easier to handle coalescing.
917 for (unsigned i = locations.size(); i ; --i) {
918 unsigned LocNo = i-1;
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000919 MachineOperand &Loc = locations[LocNo];
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000920 // Only virtual registers are rewritten.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000921 if (!Loc.isReg() || !Loc.getReg() ||
922 !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000923 continue;
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000924 unsigned VirtReg = Loc.getReg();
Jakob Stoklund Olesen1a3534a2011-01-12 22:37:49 +0000925 if (VRM.isAssignedReg(VirtReg) &&
926 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
Jakob Stoklund Olesen89bd2ae2011-05-08 19:21:08 +0000927 // This can create a %noreg operand in rare cases when the sub-register
928 // index is no longer available. That means the user value is in a
929 // non-existent sub-register, and %noreg is exactly what we want.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000930 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
Jakob Stoklund Olesen28df7ef2011-11-13 01:23:30 +0000931 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000932 // FIXME: Translate SubIdx to a stackslot offset.
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000933 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000934 } else {
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000935 Loc.setReg(0);
936 Loc.setSubReg(0);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000937 }
Jakob Stoklund Olesen44086032010-12-03 22:25:07 +0000938 coalesceLocation(LocNo);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000939 }
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000940}
941
Devang Patel26ffa012011-02-04 01:43:25 +0000942/// findInsertLocation - Find an iterator for inserting a DBG_VALUE
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000943/// instruction.
944static MachineBasicBlock::iterator
Devang Patel26ffa012011-02-04 01:43:25 +0000945findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000946 LiveIntervals &LIS) {
947 SlotIndex Start = LIS.getMBBStartIdx(MBB);
948 Idx = Idx.getBaseIndex();
949
950 // Try to find an insert location by going backwards from Idx.
951 MachineInstr *MI;
952 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
953 // We've reached the beginning of MBB.
954 if (Idx == Start) {
955 MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000956 return I;
957 }
958 Idx = Idx.getPrevIndex();
959 }
Devang Patel26ffa012011-02-04 01:43:25 +0000960
Jakob Stoklund Olesen088b30a2011-01-13 23:35:53 +0000961 // Don't insert anything after the first terminator, though.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000962 return MI->isTerminator() ? MBB->getFirstTerminator() :
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000963 std::next(MachineBasicBlock::iterator(MI));
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000964}
965
966void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
967 unsigned LocNo,
968 LiveIntervals &LIS,
969 const TargetInstrInfo &TII) {
Devang Patel26ffa012011-02-04 01:43:25 +0000970 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
Jakob Stoklund Olesen9adf5e02011-01-09 05:33:21 +0000971 MachineOperand &Loc = locations[LocNo];
Devang Pateleabc3cea2011-08-04 20:42:11 +0000972 ++NumInsertedDebugValues;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000973
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000974 assert(cast<DILocalVariable>(Variable)
Duncan P. N. Exon Smithe686f152015-04-06 23:27:40 +0000975 ->isValidLocationForIntrinsic(getDebugLoc()) &&
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +0000976 "Expected inlined-at fields to agree");
Adrian Prantl418d1d12013-07-09 20:28:37 +0000977 if (Loc.isReg())
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +0000978 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000979 IsIndirect, Loc.getReg(), offset, Variable, Expression);
Adrian Prantl418d1d12013-07-09 20:28:37 +0000980 else
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +0000981 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000982 .addOperand(Loc)
983 .addImm(offset)
984 .addMetadata(Variable)
985 .addMetadata(Expression);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000986}
987
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000988void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
989 const TargetInstrInfo &TII) {
990 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
991
992 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
993 SlotIndex Start = I.start();
994 SlotIndex Stop = I.stop();
995 unsigned LocNo = I.value();
996 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000997 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
998 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +0000999
1000 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001001 insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001002 // This interval may span multiple basic blocks.
1003 // Insert a DBG_VALUE into each one.
1004 while(Stop > MBBEnd) {
1005 // Move to the next block.
1006 Start = MBBEnd;
1007 if (++MBB == MFEnd)
1008 break;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001009 MBBEnd = LIS.getMBBEndIdx(&*MBB);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001010 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001011 insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001012 }
1013 DEBUG(dbgs() << '\n');
1014 if (MBB == MFEnd)
1015 break;
1016
1017 ++I;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001018 }
1019}
1020
1021void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1022 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
David Blaikie2f040112014-07-25 16:10:16 +00001023 if (!MF)
1024 return;
Eric Christopherfc6de422014-08-05 02:39:49 +00001025 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001026 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
Eric Christopher1cdefae2015-02-27 00:11:34 +00001027 DEBUG(userValues[i]->print(dbgs(), TRI));
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001028 userValues[i]->rewriteLocations(*VRM, *TRI);
1029 userValues[i]->emitDebugValues(VRM, *LIS, *TII);
1030 }
Manman Ren7a4c8a72013-02-13 20:23:48 +00001031 EmitDone = true;
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001032}
1033
1034void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
Manman Ren7a4c8a72013-02-13 20:23:48 +00001035 if (pImpl)
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001036 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1037}
1038
David Blaikie2f040112014-07-25 16:10:16 +00001039bool LiveDebugVariables::doInitialization(Module &M) {
David Blaikie2f040112014-07-25 16:10:16 +00001040 return Pass::doInitialization(M);
1041}
Jakob Stoklund Olesenafc2bc22010-12-03 21:47:10 +00001042
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +00001043#ifndef NDEBUG
Yaron Kereneb2a2542016-01-29 20:50:44 +00001044LLVM_DUMP_METHOD void LiveDebugVariables::dump() {
Jakob Stoklund Olesen9ec20112010-12-02 18:15:44 +00001045 if (pImpl)
1046 static_cast<LDVImpl*>(pImpl)->print(dbgs());
1047}
1048#endif