blob: 20e997ae377bdb6935959cf3c206548e40686ffa [file] [log] [blame]
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +00001//===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveDebugVariables analysis.
11//
12// Remove all DBG_VALUE instructions referencing virtual registers and replace
13// them with a data structure tracking where live user variables are kept - in a
14// virtual register or in a stack slot.
15//
16// Allow the data structure to be updated during register allocation when values
17// are moved between registers and stack slots. Finally emit new DBG_VALUE
18// instructions after register allocation is complete.
19//
20//===----------------------------------------------------------------------===//
21
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000022#define DEBUG_TYPE "livedebug"
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000023#include "LiveDebugVariables.h"
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +000024#include "VirtRegMap.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000025#include "llvm/Constants.h"
26#include "llvm/Metadata.h"
27#include "llvm/Value.h"
28#include "llvm/ADT/IntervalMap.h"
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000029#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000030#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +000031#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +000033#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000034#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +000037#include "llvm/Target/TargetInstrInfo.h"
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000038#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000039#include "llvm/Target/TargetRegisterInfo.h"
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000040
41using namespace llvm;
42
Devang Patel51a666f2011-01-07 22:33:41 +000043static cl::opt<bool>
Jakob Stoklund Olesen25dc2262011-01-12 23:36:21 +000044EnableLDV("live-debug-variables", cl::init(true),
Devang Patel51a666f2011-01-07 22:33:41 +000045 cl::desc("Enable the live debug variables pass"), cl::Hidden);
46
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000047char LiveDebugVariables::ID = 0;
48
49INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
50 "Debug Variable Analysis", false, false)
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000051INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000052INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
53INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
54 "Debug Variable Analysis", false, false)
55
56void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000057 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000058 AU.addRequiredTransitive<LiveIntervals>();
59 AU.setPreservesAll();
60 MachineFunctionPass::getAnalysisUsage(AU);
61}
62
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000063LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(0) {
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000064 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
65}
66
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000067/// LocMap - Map of where a user value is live, and its location.
68typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
69
70/// UserValue - A user value is a part of a debug info user variable.
71///
72/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
73/// holds part of a user variable. The part is identified by a byte offset.
74///
75/// UserValues are grouped into equivalence classes for easier searching. Two
76/// user values are related if they refer to the same variable, or if they are
77/// held by the same virtual register. The equivalence class is the transitive
78/// closure of that relation.
79namespace {
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +000080class LDVImpl;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000081class UserValue {
82 const MDNode *variable; ///< The debug info variable we are part of.
83 unsigned offset; ///< Byte offset into variable.
Devang Patelf827cd72011-02-04 01:43:25 +000084 DebugLoc dl; ///< The debug location for the variable. This is
85 ///< used by dwarf writer to find lexical scope.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000086 UserValue *leader; ///< Equivalence class leader.
87 UserValue *next; ///< Next value in equivalence class, or null.
88
89 /// Numbered locations referenced by locmap.
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +000090 SmallVector<MachineOperand, 4> locations;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000091
92 /// Map of slot indices where this value is live.
93 LocMap locInts;
94
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +000095 /// coalesceLocation - After LocNo was changed, check if it has become
96 /// identical to another location, and coalesce them. This may cause LocNo or
97 /// a later location to be erased, but no earlier location will be erased.
98 void coalesceLocation(unsigned LocNo);
99
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000100 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
101 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
102 LiveIntervals &LIS, const TargetInstrInfo &TII);
103
Andrew Trickc1dbd5d2011-03-22 19:18:42 +0000104 /// insertDebugKill - Insert an undef DBG_VALUE into MBB at Idx.
105 void insertDebugKill(MachineBasicBlock *MBB, SlotIndex Idx,
106 LiveIntervals &LIS, const TargetInstrInfo &TII);
107
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000108public:
109 /// UserValue - Create a new UserValue.
Devang Patelf827cd72011-02-04 01:43:25 +0000110 UserValue(const MDNode *var, unsigned o, DebugLoc L,
111 LocMap::Allocator &alloc)
112 : variable(var), offset(o), dl(L), leader(this), next(0), locInts(alloc)
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000113 {}
114
115 /// getLeader - Get the leader of this value's equivalence class.
116 UserValue *getLeader() {
117 UserValue *l = leader;
118 while (l != l->leader)
119 l = l->leader;
120 return leader = l;
121 }
122
123 /// getNext - Return the next UserValue in the equivalence class.
124 UserValue *getNext() const { return next; }
125
126 /// match - Does this UserValue match the aprameters?
127 bool match(const MDNode *Var, unsigned Offset) const {
128 return Var == variable && Offset == offset;
129 }
130
131 /// merge - Merge equivalence classes.
132 static UserValue *merge(UserValue *L1, UserValue *L2) {
133 L2 = L2->getLeader();
134 if (!L1)
135 return L2;
136 L1 = L1->getLeader();
137 if (L1 == L2)
138 return L1;
139 // Splice L2 before L1's members.
140 UserValue *End = L2;
141 while (End->next)
142 End->leader = L1, End = End->next;
143 End->leader = L1;
144 End->next = L1->next;
145 L1->next = L2;
146 return L1;
147 }
148
149 /// getLocationNo - Return the location number that matches Loc.
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000150 unsigned getLocationNo(const MachineOperand &LocMO) {
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000151 if (LocMO.isReg()) {
152 if (LocMO.getReg() == 0)
153 return ~0u;
154 // For register locations we dont care about use/def and other flags.
155 for (unsigned i = 0, e = locations.size(); i != e; ++i)
156 if (locations[i].isReg() &&
157 locations[i].getReg() == LocMO.getReg() &&
158 locations[i].getSubReg() == LocMO.getSubReg())
159 return i;
160 } else
161 for (unsigned i = 0, e = locations.size(); i != e; ++i)
162 if (LocMO.isIdenticalTo(locations[i]))
163 return i;
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000164 locations.push_back(LocMO);
165 // We are storing a MachineOperand outside a MachineInstr.
166 locations.back().clearParent();
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000167 // Don't store def operands.
168 if (locations.back().isReg())
169 locations.back().setIsUse();
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000170 return locations.size() - 1;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000171 }
172
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000173 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
174 void mapVirtRegs(LDVImpl *LDV);
175
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000176 /// addDef - Add a definition point to this value.
177 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
178 // Add a singular (Idx,Idx) -> Loc mapping.
179 LocMap::iterator I = locInts.find(Idx);
180 if (!I.valid() || I.start() != Idx)
181 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
182 }
183
184 /// extendDef - Extend the current definition as far as possible down the
185 /// dominator tree. Stop when meeting an existing def or when leaving the live
186 /// range of VNI.
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000187 /// End points where VNI is no longer live are added to Kills.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000188 /// @param Idx Starting point for the definition.
189 /// @param LocNo Location number to propagate.
190 /// @param LI Restrict liveness to where LI has the value VNI. May be null.
191 /// @param VNI When LI is not null, this is the value to restrict to.
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000192 /// @param Kills Append end points of VNI's live range to Kills.
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000193 /// @param LIS Live intervals analysis.
194 /// @param MDT Dominator tree.
195 void extendDef(SlotIndex Idx, unsigned LocNo,
196 LiveInterval *LI, const VNInfo *VNI,
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000197 SmallVectorImpl<SlotIndex> *Kills,
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000198 LiveIntervals &LIS, MachineDominatorTree &MDT);
199
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000200 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
201 /// registers. Determine if any of the copies are available at the kill
202 /// points, and add defs if possible.
203 /// @param LI Scan for copies of the value in LI->reg.
204 /// @param LocNo Location number of LI->reg.
205 /// @param Kills Points where the range of LocNo could be extended.
206 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
207 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
208 const SmallVectorImpl<SlotIndex> &Kills,
209 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
210 MachineRegisterInfo &MRI,
211 LiveIntervals &LIS);
212
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000213 /// computeIntervals - Compute the live intervals of all locations after
214 /// collecting all their def points.
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000215 void computeIntervals(MachineRegisterInfo &MRI,
216 LiveIntervals &LIS, MachineDominatorTree &MDT);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000217
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000218 /// renameRegister - Update locations to rewrite OldReg as NewReg:SubIdx.
219 void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
220 const TargetRegisterInfo *TRI);
221
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000222 /// rewriteLocations - Rewrite virtual register locations according to the
223 /// provided virtual register map.
224 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
225
226 /// emitDebugVariables - Recreate DBG_VALUE instruction from data structures.
227 void emitDebugValues(VirtRegMap *VRM,
228 LiveIntervals &LIS, const TargetInstrInfo &TRI);
229
Devang Patelf827cd72011-02-04 01:43:25 +0000230 /// findDebugLoc - Return DebugLoc used for this DBG_VALUE instruction. A
231 /// variable may have more than one corresponding DBG_VALUE instructions.
232 /// Only first one needs DebugLoc to identify variable's lexical scope
233 /// in source file.
234 DebugLoc findDebugLoc();
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000235 void print(raw_ostream&, const TargetRegisterInfo*);
236};
237} // namespace
238
239/// LDVImpl - Implementation of the LiveDebugVariables pass.
240namespace {
241class LDVImpl {
242 LiveDebugVariables &pass;
243 LocMap::Allocator allocator;
244 MachineFunction *MF;
245 LiveIntervals *LIS;
246 MachineDominatorTree *MDT;
247 const TargetRegisterInfo *TRI;
248
249 /// userValues - All allocated UserValue instances.
250 SmallVector<UserValue*, 8> userValues;
251
252 /// Map virtual register to eq class leader.
253 typedef DenseMap<unsigned, UserValue*> VRMap;
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000254 VRMap virtRegToEqClass;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000255
256 /// Map user variable to eq class leader.
257 typedef DenseMap<const MDNode *, UserValue*> UVMap;
258 UVMap userVarMap;
259
260 /// getUserValue - Find or create a UserValue.
Devang Patelf827cd72011-02-04 01:43:25 +0000261 UserValue *getUserValue(const MDNode *Var, unsigned Offset, DebugLoc DL);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000262
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000263 /// lookupVirtReg - Find the EC leader for VirtReg or null.
264 UserValue *lookupVirtReg(unsigned VirtReg);
265
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000266 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
267 /// @param MI DBG_VALUE instruction
268 /// @param Idx Last valid SLotIndex before instruction.
269 /// @return True if the DBG_VALUE instruction should be deleted.
270 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
271
272 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
273 /// a UserValue def for each instruction.
274 /// @param mf MachineFunction to be scanned.
275 /// @return True if any debug values were found.
276 bool collectDebugValues(MachineFunction &mf);
277
278 /// computeIntervals - Compute the live intervals of all user values after
279 /// collecting all their def points.
280 void computeIntervals();
281
282public:
283 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
284 bool runOnMachineFunction(MachineFunction &mf);
285
286 /// clear - Relase all memory.
287 void clear() {
288 DeleteContainerPointers(userValues);
289 userValues.clear();
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000290 virtRegToEqClass.clear();
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000291 userVarMap.clear();
292 }
293
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000294 /// mapVirtReg - Map virtual register to an equivalence class.
295 void mapVirtReg(unsigned VirtReg, UserValue *EC);
296
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000297 /// renameRegister - Replace all references to OldReg wiht NewReg:SubIdx.
298 void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx);
299
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000300 /// emitDebugVariables - Recreate DBG_VALUE instruction from data structures.
301 void emitDebugValues(VirtRegMap *VRM);
302
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000303 void print(raw_ostream&);
304};
305} // namespace
306
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000307void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
308 if (const MDString *MDS = dyn_cast<MDString>(variable->getOperand(2)))
309 OS << "!\"" << MDS->getString() << "\"\t";
310 if (offset)
311 OS << '+' << offset;
312 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
313 OS << " [" << I.start() << ';' << I.stop() << "):";
314 if (I.value() == ~0u)
315 OS << "undef";
316 else
317 OS << I.value();
318 }
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000319 for (unsigned i = 0, e = locations.size(); i != e; ++i)
320 OS << " Loc" << i << '=' << locations[i];
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000321 OS << '\n';
322}
323
324void LDVImpl::print(raw_ostream &OS) {
325 OS << "********** DEBUG VARIABLES **********\n";
326 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
327 userValues[i]->print(OS, TRI);
328}
329
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +0000330void UserValue::coalesceLocation(unsigned LocNo) {
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000331 unsigned KeepLoc = 0;
332 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
333 if (KeepLoc == LocNo)
334 continue;
335 if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
336 break;
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +0000337 }
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000338 // No matches.
339 if (KeepLoc == locations.size())
340 return;
341
342 // Keep the smaller location, erase the larger one.
343 unsigned EraseLoc = LocNo;
344 if (KeepLoc > EraseLoc)
345 std::swap(KeepLoc, EraseLoc);
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +0000346 locations.erase(locations.begin() + EraseLoc);
347
348 // Rewrite values.
349 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
350 unsigned v = I.value();
351 if (v == EraseLoc)
352 I.setValue(KeepLoc); // Coalesce when possible.
353 else if (v > EraseLoc)
354 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
355 }
356}
357
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000358void UserValue::mapVirtRegs(LDVImpl *LDV) {
359 for (unsigned i = 0, e = locations.size(); i != e; ++i)
360 if (locations[i].isReg() &&
361 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
362 LDV->mapVirtReg(locations[i].getReg(), this);
363}
364
Devang Patelf827cd72011-02-04 01:43:25 +0000365UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset,
366 DebugLoc DL) {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000367 UserValue *&Leader = userVarMap[Var];
368 if (Leader) {
369 UserValue *UV = Leader->getLeader();
370 Leader = UV;
371 for (; UV; UV = UV->getNext())
372 if (UV->match(Var, Offset))
373 return UV;
374 }
375
Devang Patelf827cd72011-02-04 01:43:25 +0000376 UserValue *UV = new UserValue(Var, Offset, DL, allocator);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000377 userValues.push_back(UV);
378 Leader = UserValue::merge(Leader, UV);
379 return UV;
380}
381
382void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
383 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000384 UserValue *&Leader = virtRegToEqClass[VirtReg];
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000385 Leader = UserValue::merge(Leader, EC);
386}
387
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000388UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000389 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000390 return UV->getLeader();
391 return 0;
392}
393
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000394bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
395 // DBG_VALUE loc, offset, variable
396 if (MI->getNumOperands() != 3 ||
397 !MI->getOperand(1).isImm() || !MI->getOperand(2).isMetadata()) {
398 DEBUG(dbgs() << "Can't handle " << *MI);
399 return false;
400 }
401
402 // Get or create the UserValue for (variable,offset).
403 unsigned Offset = MI->getOperand(1).getImm();
404 const MDNode *Var = MI->getOperand(2).getMetadata();
Devang Patelf827cd72011-02-04 01:43:25 +0000405 UserValue *UV = getUserValue(Var, Offset, MI->getDebugLoc());
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000406 UV->addDef(Idx, MI->getOperand(0));
407 return true;
408}
409
410bool LDVImpl::collectDebugValues(MachineFunction &mf) {
411 bool Changed = false;
412 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
413 ++MFI) {
414 MachineBasicBlock *MBB = MFI;
415 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
416 MBBI != MBBE;) {
417 if (!MBBI->isDebugValue()) {
418 ++MBBI;
419 continue;
420 }
421 // DBG_VALUE has no slot index, use the previous instruction instead.
422 SlotIndex Idx = MBBI == MBB->begin() ?
423 LIS->getMBBStartIdx(MBB) :
424 LIS->getInstructionIndex(llvm::prior(MBBI)).getDefIndex();
425 // Handle consecutive DBG_VALUE instructions with the same slot index.
426 do {
427 if (handleDebugValue(MBBI, Idx)) {
428 MBBI = MBB->erase(MBBI);
429 Changed = true;
430 } else
431 ++MBBI;
432 } while (MBBI != MBBE && MBBI->isDebugValue());
433 }
434 }
435 return Changed;
436}
437
438void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
439 LiveInterval *LI, const VNInfo *VNI,
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000440 SmallVectorImpl<SlotIndex> *Kills,
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000441 LiveIntervals &LIS, MachineDominatorTree &MDT) {
442 SmallVector<SlotIndex, 16> Todo;
443 Todo.push_back(Idx);
444
445 do {
446 SlotIndex Start = Todo.pop_back_val();
447 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
448 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
Jakob Stoklund Olesen12a40312011-01-12 23:14:04 +0000449 LocMap::iterator I = locInts.find(Start);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000450
451 // Limit to VNI's live range.
452 bool ToEnd = true;
453 if (LI && VNI) {
454 LiveRange *Range = LI->getLiveRangeContaining(Start);
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000455 if (!Range || Range->valno != VNI) {
456 if (Kills)
457 Kills->push_back(Start);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000458 continue;
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000459 }
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000460 if (Range->end < Stop)
461 Stop = Range->end, ToEnd = false;
462 }
463
464 // There could already be a short def at Start.
465 if (I.valid() && I.start() <= Start) {
466 // Stop when meeting a different location or an already extended interval.
467 Start = Start.getNextSlot();
468 if (I.value() != LocNo || I.stop() != Start)
469 continue;
470 // This is a one-slot placeholder. Just skip it.
471 ++I;
472 }
473
474 // Limited by the next def.
475 if (I.valid() && I.start() < Stop)
476 Stop = I.start(), ToEnd = false;
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000477 // Limited by VNI's live range.
478 else if (!ToEnd && Kills)
479 Kills->push_back(Stop);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000480
481 if (Start >= Stop)
482 continue;
483
484 I.insert(Start, Stop, LocNo);
485
486 // If we extended to the MBB end, propagate down the dominator tree.
487 if (!ToEnd)
488 continue;
489 const std::vector<MachineDomTreeNode*> &Children =
490 MDT.getNode(MBB)->getChildren();
491 for (unsigned i = 0, e = Children.size(); i != e; ++i)
492 Todo.push_back(LIS.getMBBStartIdx(Children[i]->getBlock()));
493 } while (!Todo.empty());
494}
495
496void
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000497UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
498 const SmallVectorImpl<SlotIndex> &Kills,
499 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
500 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
501 if (Kills.empty())
502 return;
503 // Don't track copies from physregs, there are too many uses.
504 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
505 return;
506
507 // Collect all the (vreg, valno) pairs that are copies of LI.
508 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
509 for (MachineRegisterInfo::use_nodbg_iterator
510 UI = MRI.use_nodbg_begin(LI->reg),
511 UE = MRI.use_nodbg_end(); UI != UE; ++UI) {
512 // Copies of the full value.
513 if (UI.getOperand().getSubReg() || !UI->isCopy())
514 continue;
515 MachineInstr *MI = &*UI;
516 unsigned DstReg = MI->getOperand(0).getReg();
517
518 // Is LocNo extended to reach this copy? If not, another def may be blocking
519 // it, or we are looking at a wrong value of LI.
520 SlotIndex Idx = LIS.getInstructionIndex(MI);
521 LocMap::iterator I = locInts.find(Idx.getUseIndex());
522 if (!I.valid() || I.value() != LocNo)
523 continue;
524
525 if (!LIS.hasInterval(DstReg))
526 continue;
527 LiveInterval *DstLI = &LIS.getInterval(DstReg);
528 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getDefIndex());
529 assert(DstVNI && DstVNI->def == Idx.getDefIndex() && "Bad copy value");
530 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
531 }
532
533 if (CopyValues.empty())
534 return;
535
536 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
537
538 // Try to add defs of the copied values for each kill point.
539 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
540 SlotIndex Idx = Kills[i];
541 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
542 LiveInterval *DstLI = CopyValues[j].first;
543 const VNInfo *DstVNI = CopyValues[j].second;
544 if (DstLI->getVNInfoAt(Idx) != DstVNI)
545 continue;
546 // Check that there isn't already a def at Idx
547 LocMap::iterator I = locInts.find(Idx);
548 if (I.valid() && I.start() <= Idx)
549 continue;
550 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
551 << DstVNI->id << " in " << *DstLI << '\n');
552 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
553 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
554 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
555 I.insert(Idx, Idx.getNextSlot(), LocNo);
556 NewDefs.push_back(std::make_pair(Idx, LocNo));
557 break;
558 }
559 }
560}
561
562void
563UserValue::computeIntervals(MachineRegisterInfo &MRI,
564 LiveIntervals &LIS,
565 MachineDominatorTree &MDT) {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000566 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
567
568 // Collect all defs to be extended (Skipping undefs).
569 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
570 if (I.value() != ~0u)
571 Defs.push_back(std::make_pair(I.start(), I.value()));
572
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000573 // Extend all defs, and possibly add new ones along the way.
574 for (unsigned i = 0; i != Defs.size(); ++i) {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000575 SlotIndex Idx = Defs[i].first;
576 unsigned LocNo = Defs[i].second;
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000577 const MachineOperand &Loc = locations[LocNo];
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000578
579 // Register locations are constrained to where the register value is live.
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000580 if (Loc.isReg() && LIS.hasInterval(Loc.getReg())) {
581 LiveInterval *LI = &LIS.getInterval(Loc.getReg());
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000582 const VNInfo *VNI = LI->getVNInfoAt(Idx);
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000583 SmallVector<SlotIndex, 16> Kills;
584 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT);
585 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000586 } else
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000587 extendDef(Idx, LocNo, 0, 0, 0, LIS, MDT);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000588 }
589
590 // Finally, erase all the undefs.
591 for (LocMap::iterator I = locInts.begin(); I.valid();)
592 if (I.value() == ~0u)
593 I.erase();
594 else
595 ++I;
596}
597
598void LDVImpl::computeIntervals() {
Jakob Stoklund Olesen1744e472011-03-18 21:42:19 +0000599 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
600 userValues[i]->computeIntervals(MF->getRegInfo(), *LIS, *MDT);
601 userValues[i]->mapVirtRegs(this);
602 }
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000603}
604
605bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
606 MF = &mf;
607 LIS = &pass.getAnalysis<LiveIntervals>();
608 MDT = &pass.getAnalysis<MachineDominatorTree>();
609 TRI = mf.getTarget().getRegisterInfo();
610 clear();
611 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
612 << ((Value*)mf.getFunction())->getName()
613 << " **********\n");
614
615 bool Changed = collectDebugValues(mf);
616 computeIntervals();
617 DEBUG(print(dbgs()));
618 return Changed;
619}
620
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +0000621bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
Devang Patel51a666f2011-01-07 22:33:41 +0000622 if (!EnableLDV)
623 return false;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000624 if (!pImpl)
625 pImpl = new LDVImpl(this);
626 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
627}
628
629void LiveDebugVariables::releaseMemory() {
630 if (pImpl)
631 static_cast<LDVImpl*>(pImpl)->clear();
632}
633
634LiveDebugVariables::~LiveDebugVariables() {
635 if (pImpl)
636 delete static_cast<LDVImpl*>(pImpl);
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +0000637}
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000638
639void UserValue::
640renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
641 const TargetRegisterInfo *TRI) {
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +0000642 for (unsigned i = locations.size(); i; --i) {
643 unsigned LocNo = i - 1;
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000644 MachineOperand &Loc = locations[LocNo];
645 if (!Loc.isReg() || Loc.getReg() != OldReg)
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000646 continue;
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000647 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
648 Loc.substPhysReg(NewReg, *TRI);
649 else
650 Loc.substVirtReg(NewReg, SubIdx, *TRI);
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +0000651 coalesceLocation(LocNo);
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000652 }
653}
654
655void LDVImpl::
656renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
Jakob Stoklund Olesen8d2584a2010-12-03 21:47:08 +0000657 UserValue *UV = lookupVirtReg(OldReg);
658 if (!UV)
659 return;
660
661 if (TargetRegisterInfo::isVirtualRegister(NewReg))
662 mapVirtReg(NewReg, UV);
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000663 virtRegToEqClass.erase(OldReg);
Jakob Stoklund Olesen8d2584a2010-12-03 21:47:08 +0000664
665 do {
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000666 UV->renameRegister(OldReg, NewReg, SubIdx, TRI);
Jakob Stoklund Olesen8d2584a2010-12-03 21:47:08 +0000667 UV = UV->getNext();
668 } while (UV);
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000669}
670
671void LiveDebugVariables::
672renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
673 if (pImpl)
674 static_cast<LDVImpl*>(pImpl)->renameRegister(OldReg, NewReg, SubIdx);
675}
676
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000677void
678UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
679 // Iterate over locations in reverse makes it easier to handle coalescing.
680 for (unsigned i = locations.size(); i ; --i) {
681 unsigned LocNo = i-1;
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000682 MachineOperand &Loc = locations[LocNo];
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000683 // Only virtual registers are rewritten.
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000684 if (!Loc.isReg() || !Loc.getReg() ||
685 !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000686 continue;
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000687 unsigned VirtReg = Loc.getReg();
Jakob Stoklund Olesenf2036272011-01-12 22:37:49 +0000688 if (VRM.isAssignedReg(VirtReg) &&
689 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000690 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
Jakob Stoklund Olesenf0704d22011-01-12 23:14:07 +0000691 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT &&
692 VRM.isSpillSlotUsed(VRM.getStackSlot(VirtReg))) {
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000693 // FIXME: Translate SubIdx to a stackslot offset.
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000694 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000695 } else {
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000696 Loc.setReg(0);
697 Loc.setSubReg(0);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000698 }
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +0000699 coalesceLocation(LocNo);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000700 }
701 DEBUG(print(dbgs(), &TRI));
702}
703
Devang Patelf827cd72011-02-04 01:43:25 +0000704/// findInsertLocation - Find an iterator for inserting a DBG_VALUE
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000705/// instruction.
706static MachineBasicBlock::iterator
Devang Patelf827cd72011-02-04 01:43:25 +0000707findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000708 LiveIntervals &LIS) {
709 SlotIndex Start = LIS.getMBBStartIdx(MBB);
710 Idx = Idx.getBaseIndex();
711
712 // Try to find an insert location by going backwards from Idx.
713 MachineInstr *MI;
714 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
715 // We've reached the beginning of MBB.
716 if (Idx == Start) {
717 MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000718 return I;
719 }
720 Idx = Idx.getPrevIndex();
721 }
Devang Patelf827cd72011-02-04 01:43:25 +0000722
Jakob Stoklund Oleseneea666f2011-01-13 23:35:53 +0000723 // Don't insert anything after the first terminator, though.
724 return MI->getDesc().isTerminator() ? MBB->getFirstTerminator() :
725 llvm::next(MachineBasicBlock::iterator(MI));
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000726}
727
Devang Patelf827cd72011-02-04 01:43:25 +0000728DebugLoc UserValue::findDebugLoc() {
729 DebugLoc D = dl;
730 dl = DebugLoc();
731 return D;
732}
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000733void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
734 unsigned LocNo,
735 LiveIntervals &LIS,
736 const TargetInstrInfo &TII) {
Devang Patelf827cd72011-02-04 01:43:25 +0000737 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000738 MachineOperand &Loc = locations[LocNo];
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000739
740 // Frame index locations may require a target callback.
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000741 if (Loc.isFI()) {
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000742 MachineInstr *MI = TII.emitFrameIndexDebugValue(*MBB->getParent(),
Devang Patelf827cd72011-02-04 01:43:25 +0000743 Loc.getIndex(), offset, variable,
744 findDebugLoc());
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000745 if (MI) {
746 MBB->insert(I, MI);
747 return;
748 }
749 }
750 // This is not a frame index, or the target is happy with a standard FI.
Devang Patelf827cd72011-02-04 01:43:25 +0000751 BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
Jakob Stoklund Olesen0804ead2011-01-09 05:33:21 +0000752 .addOperand(Loc).addImm(offset).addMetadata(variable);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000753}
754
Andrew Trickc1dbd5d2011-03-22 19:18:42 +0000755void UserValue::insertDebugKill(MachineBasicBlock *MBB, SlotIndex Idx,
756 LiveIntervals &LIS, const TargetInstrInfo &TII) {
757 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
758 BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE)).addReg(0)
759 .addImm(offset).addMetadata(variable);
760}
761
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000762void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
763 const TargetInstrInfo &TII) {
764 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
765
766 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
767 SlotIndex Start = I.start();
768 SlotIndex Stop = I.stop();
769 unsigned LocNo = I.value();
770 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
771 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
772 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
773
774 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
775 insertDebugValue(MBB, Start, LocNo, LIS, TII);
776
777 // This interval may span multiple basic blocks.
778 // Insert a DBG_VALUE into each one.
779 while(Stop > MBBEnd) {
780 // Move to the next block.
781 Start = MBBEnd;
782 if (++MBB == MFEnd)
783 break;
784 MBBEnd = LIS.getMBBEndIdx(MBB);
785 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
786 insertDebugValue(MBB, Start, LocNo, LIS, TII);
787 }
788 DEBUG(dbgs() << '\n');
789 if (MBB == MFEnd)
790 break;
791
792 ++I;
Andrew Trickc1dbd5d2011-03-22 19:18:42 +0000793 if (Stop == MBBEnd)
794 continue;
795 // The current interval ends before MBB.
796 // Insert a kill if there is a gap.
797 if (!I.valid() || I.start() > Stop)
798 insertDebugKill(MBB, Stop, LIS, TII);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000799 }
800}
801
802void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
803 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
804 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
805 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
806 userValues[i]->rewriteLocations(*VRM, *TRI);
807 userValues[i]->emitDebugValues(VRM, *LIS, *TII);
808 }
809}
810
811void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
812 if (pImpl)
813 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
814}
815
816
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000817#ifndef NDEBUG
818void LiveDebugVariables::dump() {
819 if (pImpl)
820 static_cast<LDVImpl*>(pImpl)->print(dbgs());
821}
822#endif
823