Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/LiveDebugVariables.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the LiveDebugVariables analysis.
10
//
11
// Remove all DBG_VALUE instructions referencing virtual registers and replace
12
// them with a data structure tracking where live user variables are kept - in a
13
// virtual register or in a stack slot.
14
//
15
// Allow the data structure to be updated during register allocation when values
16
// are moved between registers and stack slots. Finally emit new DBG_VALUE
17
// instructions after register allocation is complete.
18
//
19
//===----------------------------------------------------------------------===//
20
21
#include "LiveDebugVariables.h"
22
#include "llvm/ADT/ArrayRef.h"
23
#include "llvm/ADT/DenseMap.h"
24
#include "llvm/ADT/IntervalMap.h"
25
#include "llvm/ADT/MapVector.h"
26
#include "llvm/ADT/STLExtras.h"
27
#include "llvm/ADT/SmallSet.h"
28
#include "llvm/ADT/SmallVector.h"
29
#include "llvm/ADT/Statistic.h"
30
#include "llvm/ADT/StringRef.h"
31
#include "llvm/CodeGen/LexicalScopes.h"
32
#include "llvm/CodeGen/LiveInterval.h"
33
#include "llvm/CodeGen/LiveIntervals.h"
34
#include "llvm/CodeGen/MachineBasicBlock.h"
35
#include "llvm/CodeGen/MachineDominators.h"
36
#include "llvm/CodeGen/MachineFunction.h"
37
#include "llvm/CodeGen/MachineInstr.h"
38
#include "llvm/CodeGen/MachineInstrBuilder.h"
39
#include "llvm/CodeGen/MachineOperand.h"
40
#include "llvm/CodeGen/MachineRegisterInfo.h"
41
#include "llvm/CodeGen/SlotIndexes.h"
42
#include "llvm/CodeGen/TargetInstrInfo.h"
43
#include "llvm/CodeGen/TargetOpcodes.h"
44
#include "llvm/CodeGen/TargetRegisterInfo.h"
45
#include "llvm/CodeGen/TargetSubtargetInfo.h"
46
#include "llvm/CodeGen/VirtRegMap.h"
47
#include "llvm/Config/llvm-config.h"
48
#include "llvm/IR/DebugInfoMetadata.h"
49
#include "llvm/IR/DebugLoc.h"
50
#include "llvm/IR/Function.h"
51
#include "llvm/IR/Metadata.h"
52
#include "llvm/MC/MCRegisterInfo.h"
53
#include "llvm/Pass.h"
54
#include "llvm/Support/Casting.h"
55
#include "llvm/Support/CommandLine.h"
56
#include "llvm/Support/Compiler.h"
57
#include "llvm/Support/Debug.h"
58
#include "llvm/Support/raw_ostream.h"
59
#include <algorithm>
60
#include <cassert>
61
#include <iterator>
62
#include <memory>
63
#include <utility>
64
65
using namespace llvm;
66
67
#define DEBUG_TYPE "livedebugvars"
68
69
static cl::opt<bool>
70
EnableLDV("live-debug-variables", cl::init(true),
71
          cl::desc("Enable the live debug variables pass"), cl::Hidden);
72
73
STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
74
STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
75
76
char LiveDebugVariables::ID = 0;
77
78
42.3k
INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
79
42.3k
                "Debug Variable Analysis", false, false)
80
42.3k
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
81
42.3k
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
82
42.3k
INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
83
                "Debug Variable Analysis", false, false)
84
85
33.6k
void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
86
33.6k
  AU.addRequired<MachineDominatorTree>();
87
33.6k
  AU.addRequiredTransitive<LiveIntervals>();
88
33.6k
  AU.setPreservesAll();
89
33.6k
  MachineFunctionPass::getAnalysisUsage(AU);
90
33.6k
}
91
92
33.6k
LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
93
33.6k
  initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
94
33.6k
}
95
96
enum : unsigned { UndefLocNo = ~0U };
97
98
/// Describes a location by number along with some flags about the original
99
/// usage of the location.
100
class DbgValueLocation {
101
public:
102
  DbgValueLocation(unsigned LocNo, bool WasIndirect)
103
9.99k
      : LocNo(LocNo), WasIndirect(WasIndirect) {
104
9.99k
    static_assert(sizeof(*this) == sizeof(unsigned), "bad bitfield packing");
105
9.99k
    assert(locNo() == LocNo && "location truncation");
106
9.99k
  }
107
108
18.8k
  DbgValueLocation() : LocNo(0), WasIndirect(0) {}
109
110
40.3k
  unsigned locNo() const {
111
40.3k
    // Fix up the undef location number, which gets truncated.
112
40.3k
    return LocNo == INT_MAX ? 
UndefLocNo300
:
LocNo40.0k
;
113
40.3k
  }
114
5.48k
  bool wasIndirect() const { return WasIndirect; }
115
20.0k
  bool isUndef() const { return locNo() == UndefLocNo; }
116
117
4.98k
  DbgValueLocation changeLocNo(unsigned NewLocNo) const {
118
4.98k
    return DbgValueLocation(NewLocNo, WasIndirect);
119
4.98k
  }
120
121
  friend inline bool operator==(const DbgValueLocation &LHS,
122
9.82k
                                const DbgValueLocation &RHS) {
123
9.82k
    return LHS.LocNo == RHS.LocNo && 
LHS.WasIndirect == RHS.WasIndirect9.43k
;
124
9.82k
  }
125
126
  friend inline bool operator!=(const DbgValueLocation &LHS,
127
4.66k
                                const DbgValueLocation &RHS) {
128
4.66k
    return !(LHS == RHS);
129
4.66k
  }
130
131
private:
132
  unsigned LocNo : 31;
133
  unsigned WasIndirect : 1;
134
};
135
136
/// Map of where a user value is live, and its location.
137
using LocMap = IntervalMap<SlotIndex, DbgValueLocation, 4>;
138
139
/// Map of stack slot offsets for spilled locations.
140
/// Non-spilled locations are not added to the map.
141
using SpillOffsetMap = DenseMap<unsigned, unsigned>;
142
143
namespace {
144
145
class LDVImpl;
146
147
/// A user value is a part of a debug info user variable.
148
///
149
/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
150
/// holds part of a user variable. The part is identified by a byte offset.
151
///
152
/// UserValues are grouped into equivalence classes for easier searching. Two
153
/// user values are related if they refer to the same variable, or if they are
154
/// held by the same virtual register. The equivalence class is the transitive
155
/// closure of that relation.
156
class UserValue {
157
  const DILocalVariable *Variable; ///< The debug info variable we are part of.
158
  const DIExpression *Expression; ///< Any complex address expression.
159
  DebugLoc dl;            ///< The debug location for the variable. This is
160
                          ///< used by dwarf writer to find lexical scope.
161
  UserValue *leader;      ///< Equivalence class leader.
162
  UserValue *next = nullptr; ///< Next value in equivalence class, or null.
163
164
  /// Numbered locations referenced by locmap.
165
  SmallVector<MachineOperand, 4> locations;
166
167
  /// Map of slot indices where this value is live.
168
  LocMap locInts;
169
170
  /// Insert a DBG_VALUE into MBB at Idx for LocNo.
171
  void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
172
                        SlotIndex StopIdx, DbgValueLocation Loc, bool Spilled,
173
                        unsigned SpillOffset, LiveIntervals &LIS,
174
                        const TargetInstrInfo &TII,
175
                        const TargetRegisterInfo &TRI);
176
177
  /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
178
  /// is live. Returns true if any changes were made.
179
  bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
180
                     LiveIntervals &LIS);
181
182
public:
183
  /// Create a new UserValue.
184
  UserValue(const DILocalVariable *var, const DIExpression *expr, DebugLoc L,
185
            LocMap::Allocator &alloc)
186
      : Variable(var), Expression(expr), dl(std::move(L)), leader(this),
187
4.68k
        locInts(alloc) {}
188
189
  /// Get the leader of this value's equivalence class.
190
13.7k
  UserValue *getLeader() {
191
13.7k
    UserValue *l = leader;
192
13.7k
    while (l != l->leader)
193
0
      l = l->leader;
194
13.7k
    return leader = l;
195
13.7k
  }
196
197
  /// Return the next UserValue in the equivalence class.
198
7.99M
  UserValue *getNext() const { return next; }
199
200
  /// Does this UserValue match the parameters?
201
  bool match(const DILocalVariable *Var, const DIExpression *Expr,
202
7.99M
             const DILocation *IA) const {
203
7.99M
    // FIXME: The fragment should be part of the equivalence class, but not
204
7.99M
    // other things in the expression like stack values.
205
7.99M
    return Var == Variable && Expr == Expression && 
dl->getInlinedAt() == IA324
;
206
7.99M
  }
207
208
  /// Merge equivalence classes.
209
5.18k
  static UserValue *merge(UserValue *L1, UserValue *L2) {
210
5.18k
    L2 = L2->getLeader();
211
5.18k
    if (!L1)
212
1.07k
      return L2;
213
4.11k
    L1 = L1->getLeader();
214
4.11k
    if (L1 == L2)
215
4
      return L1;
216
4.10k
    // Splice L2 before L1's members.
217
4.10k
    UserValue *End = L2;
218
4.11k
    while (End->next) {
219
10
      End->leader = L1;
220
10
      End = End->next;
221
10
    }
222
4.10k
    End->leader = L1;
223
4.10k
    End->next = L1->next;
224
4.10k
    L1->next = L2;
225
4.10k
    return L1;
226
4.10k
  }
227
228
  /// Return the location number that matches Loc.
229
  ///
230
  /// For undef values we always return location number UndefLocNo without
231
  /// inserting anything in locations. Since locations is a vector and the
232
  /// location number is the position in the vector and UndefLocNo is ~0,
233
  /// we would need a very big vector to put the value at the right position.
234
5.04k
  unsigned getLocationNo(const MachineOperand &LocMO) {
235
5.04k
    if (LocMO.isReg()) {
236
873
      if (LocMO.getReg() == 0)
237
77
        return UndefLocNo;
238
796
      // For register locations we dont care about use/def and other flags.
239
1.11k
      
for (unsigned i = 0, e = locations.size(); 796
i != e;
++i319
)
240
375
        if (locations[i].isReg() &&
241
375
            
locations[i].getReg() == LocMO.getReg()344
&&
242
375
            
locations[i].getSubReg() == LocMO.getSubReg()58
)
243
56
          return i;
244
796
    } else
245
4.18k
      
for (unsigned i = 0, e = locations.size(); 4.16k
i != e;
++i17
)
246
38
        if (LocMO.isIdenticalTo(locations[i]))
247
21
          return i;
248
5.04k
    locations.push_back(LocMO);
249
4.88k
    // We are storing a MachineOperand outside a MachineInstr.
250
4.88k
    locations.back().clearParent();
251
4.88k
    // Don't store def operands.
252
4.88k
    if (locations.back().isReg()) {
253
740
      if (locations.back().isDef())
254
1
        locations.back().setIsDead(false);
255
740
      locations.back().setIsUse();
256
740
    }
257
4.88k
    return locations.size() - 1;
258
5.04k
  }
259
260
  /// Ensure that all virtual register locations are mapped.
261
  void mapVirtRegs(LDVImpl *LDV);
262
263
  /// Add a definition point to this value.
264
5.00k
  void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect) {
265
5.00k
    DbgValueLocation Loc(getLocationNo(LocMO), IsIndirect);
266
5.00k
    // Add a singular (Idx,Idx) -> Loc mapping.
267
5.00k
    LocMap::iterator I = locInts.find(Idx);
268
5.00k
    if (!I.valid() || 
I.start() != Idx21
)
269
4.98k
      I.insert(Idx, Idx.getNextSlot(), Loc);
270
21
    else
271
21
      // A later DBG_VALUE at the same SlotIndex overrides the old location.
272
21
      I.setValue(Loc);
273
5.00k
  }
274
275
  /// Extend the current definition as far as possible down.
276
  ///
277
  /// Stop when meeting an existing def or when leaving the live
278
  /// range of VNI. End points where VNI is no longer live are added to Kills.
279
  ///
280
  /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
281
  /// data-flow analysis to propagate them beyond basic block boundaries.
282
  ///
283
  /// \param Idx Starting point for the definition.
284
  /// \param Loc Location number to propagate.
285
  /// \param LR Restrict liveness to where LR has the value VNI. May be null.
286
  /// \param VNI When LR is not null, this is the value to restrict to.
287
  /// \param [out] Kills Append end points of VNI's live range to Kills.
288
  /// \param LIS Live intervals analysis.
289
  void extendDef(SlotIndex Idx, DbgValueLocation Loc,
290
                 LiveRange *LR, const VNInfo *VNI,
291
                 SmallVectorImpl<SlotIndex> *Kills,
292
                 LiveIntervals &LIS);
293
294
  /// The value in LI/LocNo may be copies to other registers. Determine if
295
  /// any of the copies are available at the kill points, and add defs if
296
  /// possible.
297
  ///
298
  /// \param LI Scan for copies of the value in LI->reg.
299
  /// \param LocNo Location number of LI->reg.
300
  /// \param WasIndirect Indicates if the original use of LI->reg was indirect
301
  /// \param Kills Points where the range of LocNo could be extended.
302
  /// \param [in,out] NewDefs Append (Idx, LocNo) of inserted defs here.
303
  void addDefsFromCopies(
304
      LiveInterval *LI, unsigned LocNo, bool WasIndirect,
305
      const SmallVectorImpl<SlotIndex> &Kills,
306
      SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
307
      MachineRegisterInfo &MRI, LiveIntervals &LIS);
308
309
  /// Compute the live intervals of all locations after collecting all their
310
  /// def points.
311
  void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
312
                        LiveIntervals &LIS, LexicalScopes &LS);
313
314
  /// Replace OldReg ranges with NewRegs ranges where NewRegs is
315
  /// live. Returns true if any changes were made.
316
  bool splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
317
                     LiveIntervals &LIS);
318
319
  /// Rewrite virtual register locations according to the provided virtual
320
  /// register map. Record the stack slot offsets for the locations that
321
  /// were spilled.
322
  void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
323
                        const TargetInstrInfo &TII,
324
                        const TargetRegisterInfo &TRI,
325
                        SpillOffsetMap &SpillOffsets);
326
327
  /// Recreate DBG_VALUE instruction from data structures.
328
  void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
329
                       const TargetInstrInfo &TII,
330
                       const TargetRegisterInfo &TRI,
331
                       const SpillOffsetMap &SpillOffsets);
332
333
  /// Return DebugLoc of this UserValue.
334
5.00k
  DebugLoc getDebugLoc() { return dl;}
335
336
  void print(raw_ostream &, const TargetRegisterInfo *);
337
};
338
339
/// A user label is a part of a debug info user label.
340
class UserLabel {
341
  const DILabel *Label; ///< The debug info label we are part of.
342
  DebugLoc dl;          ///< The debug location for the label. This is
343
                        ///< used by dwarf writer to find lexical scope.
344
  SlotIndex loc;        ///< Slot used by the debug label.
345
346
  /// Insert a DBG_LABEL into MBB at Idx.
347
  void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
348
                        LiveIntervals &LIS, const TargetInstrInfo &TII);
349
350
public:
351
  /// Create a new UserLabel.
352
  UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
353
4
      : Label(label), dl(std::move(L)), loc(Idx) {}
354
355
  /// Does this UserLabel match the parameters?
356
  bool match(const DILabel *L, const DILocation *IA,
357
3
             const SlotIndex Index) const {
358
3
    return Label == L && dl->getInlinedAt() == IA && loc == Index;
359
3
  }
360
361
  /// Recreate DBG_LABEL instruction from data structures.
362
  void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII);
363
364
  /// Return DebugLoc of this UserLabel.
365
4
  DebugLoc getDebugLoc() { return dl; }
366
367
  void print(raw_ostream &, const TargetRegisterInfo *);
368
};
369
370
/// Implementation of the LiveDebugVariables pass.
371
class LDVImpl {
372
  LiveDebugVariables &pass;
373
  LocMap::Allocator allocator;
374
  MachineFunction *MF = nullptr;
375
  LiveIntervals *LIS;
376
  const TargetRegisterInfo *TRI;
377
378
  /// Whether emitDebugValues is called.
379
  bool EmitDone = false;
380
381
  /// Whether the machine function is modified during the pass.
382
  bool ModifiedMF = false;
383
384
  /// All allocated UserValue instances.
385
  SmallVector<std::unique_ptr<UserValue>, 8> userValues;
386
387
  /// All allocated UserLabel instances.
388
  SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
389
390
  /// Map virtual register to eq class leader.
391
  using VRMap = DenseMap<unsigned, UserValue *>;
392
  VRMap virtRegToEqClass;
393
394
  /// Map user variable to eq class leader.
395
  using UVMap = DenseMap<const DILocalVariable *, UserValue *>;
396
  UVMap userVarMap;
397
398
  /// Find or create a UserValue.
399
  UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr,
400
                          const DebugLoc &DL);
401
402
  /// Find the EC leader for VirtReg or null.
403
  UserValue *lookupVirtReg(unsigned VirtReg);
404
405
  /// Add DBG_VALUE instruction to our maps.
406
  ///
407
  /// \param MI DBG_VALUE instruction
408
  /// \param Idx Last valid SLotIndex before instruction.
409
  ///
410
  /// \returns True if the DBG_VALUE instruction should be deleted.
411
  bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
412
413
  /// Add DBG_LABEL instruction to UserLabel.
414
  ///
415
  /// \param MI DBG_LABEL instruction
416
  /// \param Idx Last valid SlotIndex before instruction.
417
  ///
418
  /// \returns True if the DBG_LABEL instruction should be deleted.
419
  bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
420
421
  /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
422
  /// for each instruction.
423
  ///
424
  /// \param mf MachineFunction to be scanned.
425
  ///
426
  /// \returns True if any debug values were found.
427
  bool collectDebugValues(MachineFunction &mf);
428
429
  /// Compute the live intervals of all user values after collecting all
430
  /// their def points.
431
  void computeIntervals();
432
433
public:
434
1.99k
  LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
435
436
  bool runOnMachineFunction(MachineFunction &mf);
437
438
  /// Release all memory.
439
70.5k
  void clear() {
440
70.5k
    MF = nullptr;
441
70.5k
    userValues.clear();
442
70.5k
    userLabels.clear();
443
70.5k
    virtRegToEqClass.clear();
444
70.5k
    userVarMap.clear();
445
70.5k
    // Make sure we call emitDebugValues if the machine function was modified.
446
70.5k
    assert((!ModifiedMF || EmitDone) &&
447
70.5k
           "Dbg values are not emitted in LDV");
448
70.5k
    EmitDone = false;
449
70.5k
    ModifiedMF = false;
450
70.5k
  }
451
452
  /// Map virtual register to an equivalence class.
453
  void mapVirtReg(unsigned VirtReg, UserValue *EC);
454
455
  /// Replace all references to OldReg with NewRegs.
456
  void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
457
458
  /// Recreate DBG_VALUE instruction from data structures.
459
  void emitDebugValues(VirtRegMap *VRM);
460
461
  void print(raw_ostream&);
462
};
463
464
} // end anonymous namespace
465
466
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
467
static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
468
                          const LLVMContext &Ctx) {
469
  if (!DL)
470
    return;
471
472
  auto *Scope = cast<DIScope>(DL.getScope());
473
  // Omit the directory, because it's likely to be long and uninteresting.
474
  CommentOS << Scope->getFilename();
475
  CommentOS << ':' << DL.getLine();
476
  if (DL.getCol() != 0)
477
    CommentOS << ':' << DL.getCol();
478
479
  DebugLoc InlinedAtDL = DL.getInlinedAt();
480
  if (!InlinedAtDL)
481
    return;
482
483
  CommentOS << " @[ ";
484
  printDebugLoc(InlinedAtDL, CommentOS, Ctx);
485
  CommentOS << " ]";
486
}
487
488
static void printExtendedName(raw_ostream &OS, const DINode *Node,
489
                              const DILocation *DL) {
490
  const LLVMContext &Ctx = Node->getContext();
491
  StringRef Res;
492
  unsigned Line;
493
  if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
494
    Res = V->getName();
495
    Line = V->getLine();
496
  } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
497
    Res = L->getName();
498
    Line = L->getLine();
499
  }
500
501
  if (!Res.empty())
502
    OS << Res << "," << Line;
503
  auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
504
  if (InlinedAt) {
505
    if (DebugLoc InlinedAtDL = InlinedAt) {
506
      OS << " @[";
507
      printDebugLoc(InlinedAtDL, OS, Ctx);
508
      OS << "]";
509
    }
510
  }
511
}
512
513
void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
514
  OS << "!\"";
515
  printExtendedName(OS, Variable, dl);
516
517
  OS << "\"\t";
518
  for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
519
    OS << " [" << I.start() << ';' << I.stop() << "):";
520
    if (I.value().isUndef())
521
      OS << "undef";
522
    else {
523
      OS << I.value().locNo();
524
      if (I.value().wasIndirect())
525
        OS << " ind";
526
    }
527
  }
528
  for (unsigned i = 0, e = locations.size(); i != e; ++i) {
529
    OS << " Loc" << i << '=';
530
    locations[i].print(OS, TRI);
531
  }
532
  OS << '\n';
533
}
534
535
void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
536
  OS << "!\"";
537
  printExtendedName(OS, Label, dl);
538
539
  OS << "\"\t";
540
  OS << loc;
541
  OS << '\n';
542
}
543
544
void LDVImpl::print(raw_ostream &OS) {
545
  OS << "********** DEBUG VARIABLES **********\n";
546
  for (auto &userValue : userValues)
547
    userValue->print(OS, TRI);
548
  OS << "********** DEBUG LABELS **********\n";
549
  for (auto &userLabel : userLabels)
550
    userLabel->print(OS, TRI);
551
}
552
#endif
553
554
4.68k
void UserValue::mapVirtRegs(LDVImpl *LDV) {
555
9.54k
  for (unsigned i = 0, e = locations.size(); i != e; 
++i4.85k
)
556
4.85k
    if (locations[i].isReg() &&
557
4.85k
        
TargetRegisterInfo::isVirtualRegister(locations[i].getReg())711
)
558
471
      LDV->mapVirtReg(locations[i].getReg(), this);
559
4.68k
}
560
561
UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
562
5.00k
                                 const DIExpression *Expr, const DebugLoc &DL) {
563
5.00k
  UserValue *&Leader = userVarMap[Var];
564
5.00k
  if (Leader) {
565
4.38k
    UserValue *UV = Leader->getLeader();
566
4.38k
    Leader = UV;
567
8.00M
    for (; UV; 
UV = UV->getNext()7.99M
)
568
7.99M
      if (UV->match(Var, Expr, DL->getInlinedAt()))
569
317
        return UV;
570
4.38k
  }
571
5.00k
572
5.00k
  userValues.push_back(
573
4.68k
      llvm::make_unique<UserValue>(Var, Expr, DL, allocator));
574
4.68k
  UserValue *UV = userValues.back().get();
575
4.68k
  Leader = UserValue::merge(Leader, UV);
576
4.68k
  return UV;
577
5.00k
}
578
579
500
void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
580
500
  assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
581
500
  UserValue *&Leader = virtRegToEqClass[VirtReg];
582
500
  Leader = UserValue::merge(Leader, EC);
583
500
}
584
585
23.7k
UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
586
23.7k
  if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
587
28
    return UV->getLeader();
588
23.6k
  return nullptr;
589
23.6k
}
590
591
5.00k
bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
592
5.00k
  // DBG_VALUE loc, offset, variable
593
5.00k
  if (MI.getNumOperands() != 4 ||
594
5.00k
      !(MI.getOperand(1).isReg() || 
MI.getOperand(1).isImm()65
) ||
595
5.00k
      !MI.getOperand(2).isMetadata()) {
596
0
    LLVM_DEBUG(dbgs() << "Can't handle " << MI);
597
0
    return false;
598
0
  }
599
5.00k
600
5.00k
  // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
601
5.00k
  // register that hasn't been defined yet. If we do not remove those here, then
602
5.00k
  // the re-insertion of the DBG_VALUE instruction after register allocation
603
5.00k
  // will be incorrect.
604
5.00k
  // TODO: If earlier passes are corrected to generate sane debug information
605
5.00k
  // (and if the machine verifier is improved to catch this), then these checks
606
5.00k
  // could be removed or replaced by asserts.
607
5.00k
  bool Discard = false;
608
5.00k
  if (MI.getOperand(0).isReg() &&
609
5.00k
      
TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg())837
) {
610
523
    const unsigned Reg = MI.getOperand(0).getReg();
611
523
    if (!LIS->hasInterval(Reg)) {
612
1
      // The DBG_VALUE is described by a virtual register that does not have a
613
1
      // live interval. Discard the DBG_VALUE.
614
1
      Discard = true;
615
1
      LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
616
1
                        << " " << MI);
617
522
    } else {
618
522
      // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
619
522
      // is defined dead at Idx (where Idx is the slot index for the instruction
620
522
      // preceding the DBG_VALUE).
621
522
      const LiveInterval &LI = LIS->getInterval(Reg);
622
522
      LiveQueryResult LRQ = LI.Query(Idx);
623
522
      if (!LRQ.valueOutOrDead()) {
624
12
        // We have found a DBG_VALUE with the value in a virtual register that
625
12
        // is not live. Discard the DBG_VALUE.
626
12
        Discard = true;
627
12
        LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
628
12
                          << " " << MI);
629
12
      }
630
522
    }
631
523
  }
632
5.00k
633
5.00k
  // Get or create the UserValue for (variable,offset) here.
634
5.00k
  bool IsIndirect = MI.getOperand(1).isImm();
635
5.00k
  if (IsIndirect)
636
5.00k
    assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
637
5.00k
  const DILocalVariable *Var = MI.getDebugVariable();
638
5.00k
  const DIExpression *Expr = MI.getDebugExpression();
639
5.00k
  UserValue *UV =
640
5.00k
      getUserValue(Var, Expr, MI.getDebugLoc());
641
5.00k
  if (!Discard)
642
4.99k
    UV->addDef(Idx, MI.getOperand(0), IsIndirect);
643
13
  else {
644
13
    MachineOperand MO = MachineOperand::CreateReg(0U, false);
645
13
    MO.setIsDebug();
646
13
    UV->addDef(Idx, MO, false);
647
13
  }
648
5.00k
  return true;
649
5.00k
}
650
651
5
bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
652
5
  // DBG_LABEL label
653
5
  if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
654
0
    LLVM_DEBUG(dbgs() << "Can't handle " << MI);
655
0
    return false;
656
0
  }
657
5
658
5
  // Get or create the UserLabel for label here.
659
5
  const DILabel *Label = MI.getDebugLabel();
660
5
  const DebugLoc &DL = MI.getDebugLoc();
661
5
  bool Found = false;
662
5
  for (auto const &L : userLabels) {
663
3
    if (L->match(Label, DL->getInlinedAt(), Idx)) {
664
1
      Found = true;
665
1
      break;
666
1
    }
667
3
  }
668
5
  if (!Found)
669
4
    userLabels.push_back(llvm::make_unique<UserLabel>(Label, DL, Idx));
670
5
671
5
  return true;
672
5
}
673
674
35.2k
bool LDVImpl::collectDebugValues(MachineFunction &mf) {
675
35.2k
  bool Changed = false;
676
438k
  for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
677
403k
       ++MFI) {
678
403k
    MachineBasicBlock *MBB = &*MFI;
679
403k
    for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
680
3.21M
         MBBI != MBBE;) {
681
2.80M
      // Use the first debug instruction in the sequence to get a SlotIndex
682
2.80M
      // for following consecutive debug instructions.
683
2.80M
      if (!MBBI->isDebugInstr()) {
684
2.80M
        ++MBBI;
685
2.80M
        continue;
686
2.80M
      }
687
796
      // Debug instructions has no slot index. Use the previous
688
796
      // non-debug instruction's SlotIndex as its SlotIndex.
689
796
      SlotIndex Idx =
690
796
          MBBI == MBB->begin()
691
796
              ? 
LIS->getMBBStartIdx(MBB)224
692
796
              : 
LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot()572
;
693
796
      // Handle consecutive debug instructions with the same slot index.
694
5.01k
      do {
695
5.01k
        // Only handle DBG_VALUE in handleDebugValue(). Skip all other
696
5.01k
        // kinds of debug instructions.
697
5.01k
        if ((MBBI->isDebugValue() && 
handleDebugValue(*MBBI, Idx)5.00k
) ||
698
5.01k
            
(5
MBBI->isDebugLabel()5
&&
handleDebugLabel(*MBBI, Idx)5
)) {
699
5.01k
          MBBI = MBB->erase(MBBI);
700
5.01k
          Changed = true;
701
5.01k
        } else
702
0
          ++MBBI;
703
5.01k
      } while (MBBI != MBBE && 
MBBI->isDebugInstr()4.98k
);
704
796
    }
705
403k
  }
706
35.2k
  return Changed;
707
35.2k
}
708
709
void UserValue::extendDef(SlotIndex Idx, DbgValueLocation Loc, LiveRange *LR,
710
                          const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
711
4.66k
                          LiveIntervals &LIS) {
712
4.66k
  SlotIndex Start = Idx;
713
4.66k
  MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
714
4.66k
  SlotIndex Stop = LIS.getMBBEndIdx(MBB);
715
4.66k
  LocMap::iterator I = locInts.find(Start);
716
4.66k
717
4.66k
  // Limit to VNI's live range.
718
4.66k
  bool ToEnd = true;
719
4.66k
  if (LR && 
VNI508
) {
720
508
    LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
721
508
    if (!Segment || Segment->valno != VNI) {
722
0
      if (Kills)
723
0
        Kills->push_back(Start);
724
0
      return;
725
0
    }
726
508
    if (Segment->end < Stop) {
727
384
      Stop = Segment->end;
728
384
      ToEnd = false;
729
384
    }
730
508
  }
731
4.66k
732
4.66k
  // There could already be a short def at Start.
733
4.66k
  if (I.valid() && I.start() <= Start) {
734
4.66k
    // Stop when meeting a different location or an already extended interval.
735
4.66k
    Start = Start.getNextSlot();
736
4.66k
    if (I.value() != Loc || I.stop() != Start)
737
0
      return;
738
4.66k
    // This is a one-slot placeholder. Just skip it.
739
4.66k
    ++I;
740
4.66k
  }
741
4.66k
742
4.66k
  // Limited by the next def.
743
4.66k
  if (I.valid() && 
I.start() < Stop124
)
744
27
    Stop = I.start();
745
4.64k
  // Limited by VNI's live range.
746
4.64k
  else if (!ToEnd && 
Kills382
)
747
382
    Kills->push_back(Stop);
748
4.66k
749
4.66k
  if (Start < Stop)
750
4.66k
    I.insert(Start, Stop, Loc);
751
4.66k
}
752
753
void UserValue::addDefsFromCopies(
754
    LiveInterval *LI, unsigned LocNo, bool WasIndirect,
755
    const SmallVectorImpl<SlotIndex> &Kills,
756
    SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
757
490
    MachineRegisterInfo &MRI, LiveIntervals &LIS) {
758
490
  if (Kills.empty())
759
122
    return;
760
368
  // Don't track copies from physregs, there are too many uses.
761
368
  if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
762
0
    return;
763
368
764
368
  // Collect all the (vreg, valno) pairs that are copies of LI.
765
368
  SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
766
927
  for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
767
927
    MachineInstr *MI = MO.getParent();
768
927
    // Copies of the full value.
769
927
    if (MO.getSubReg() || 
!MI->isCopy()920
)
770
653
      continue;
771
274
    unsigned DstReg = MI->getOperand(0).getReg();
772
274
773
274
    // Don't follow copies to physregs. These are usually setting up call
774
274
    // arguments, and the argument registers are always call clobbered. We are
775
274
    // better off in the source register which could be a callee-saved register,
776
274
    // or it could be spilled.
777
274
    if (!TargetRegisterInfo::isVirtualRegister(DstReg))
778
190
      continue;
779
84
780
84
    // Is LocNo extended to reach this copy? If not, another def may be blocking
781
84
    // it, or we are looking at a wrong value of LI.
782
84
    SlotIndex Idx = LIS.getInstructionIndex(*MI);
783
84
    LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
784
84
    if (!I.valid() || 
I.value().locNo() != LocNo75
)
785
23
      continue;
786
61
787
61
    if (!LIS.hasInterval(DstReg))
788
0
      continue;
789
61
    LiveInterval *DstLI = &LIS.getInterval(DstReg);
790
61
    const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
791
61
    assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
792
61
    CopyValues.push_back(std::make_pair(DstLI, DstVNI));
793
61
  }
794
368
795
368
  if (CopyValues.empty())
796
345
    return;
797
23
798
23
  LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI
799
23
                    << '\n');
800
23
801
23
  // Try to add defs of the copied values for each kill point.
802
46
  for (unsigned i = 0, e = Kills.size(); i != e; 
++i23
) {
803
23
    SlotIndex Idx = Kills[i];
804
77
    for (unsigned j = 0, e = CopyValues.size(); j != e; 
++j54
) {
805
61
      LiveInterval *DstLI = CopyValues[j].first;
806
61
      const VNInfo *DstVNI = CopyValues[j].second;
807
61
      if (DstLI->getVNInfoAt(Idx) != DstVNI)
808
54
        continue;
809
7
      // Check that there isn't already a def at Idx
810
7
      LocMap::iterator I = locInts.find(Idx);
811
7
      if (I.valid() && 
I.start() <= Idx4
)
812
0
        continue;
813
7
      LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
814
7
                        << DstVNI->id << " in " << *DstLI << '\n');
815
7
      MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
816
7
      assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
817
7
      unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
818
7
      DbgValueLocation NewLoc(LocNo, WasIndirect);
819
7
      I.insert(Idx, Idx.getNextSlot(), NewLoc);
820
7
      NewDefs.push_back(std::make_pair(Idx, NewLoc));
821
7
      break;
822
7
    }
823
23
  }
824
23
}
825
826
void UserValue::computeIntervals(MachineRegisterInfo &MRI,
827
                                 const TargetRegisterInfo &TRI,
828
4.68k
                                 LiveIntervals &LIS, LexicalScopes &LS) {
829
4.68k
  SmallVector<std::pair<SlotIndex, DbgValueLocation>, 16> Defs;
830
4.68k
831
4.68k
  // Collect all defs to be extended (Skipping undefs).
832
9.67k
  for (LocMap::const_iterator I = locInts.begin(); I.valid(); 
++I4.98k
)
833
4.98k
    if (!I.value().isUndef())
834
4.90k
      Defs.push_back(std::make_pair(I.start(), I.value()));
835
4.68k
836
4.68k
  // Extend all defs, and possibly add new ones along the way.
837
9.60k
  for (unsigned i = 0; i != Defs.size(); 
++i4.91k
) {
838
4.91k
    SlotIndex Idx = Defs[i].first;
839
4.91k
    DbgValueLocation Loc = Defs[i].second;
840
4.91k
    const MachineOperand &LocMO = locations[Loc.locNo()];
841
4.91k
842
4.91k
    if (!LocMO.isReg()) {
843
4.16k
      extendDef(Idx, Loc, nullptr, nullptr, nullptr, LIS);
844
4.16k
      continue;
845
4.16k
    }
846
756
847
756
    // Register locations are constrained to where the register value is live.
848
756
    if (TargetRegisterInfo::isVirtualRegister(LocMO.getReg())) {
849
508
      LiveInterval *LI = nullptr;
850
508
      const VNInfo *VNI = nullptr;
851
508
      if (LIS.hasInterval(LocMO.getReg())) {
852
508
        LI = &LIS.getInterval(LocMO.getReg());
853
508
        VNI = LI->getVNInfoAt(Idx);
854
508
      }
855
508
      SmallVector<SlotIndex, 16> Kills;
856
508
      extendDef(Idx, Loc, LI, VNI, &Kills, LIS);
857
508
      // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
858
508
      // if the original location for example is %vreg0:sub_hi, and we find a
859
508
      // full register copy in addDefsFromCopies (at the moment it only handles
860
508
      // full register copies), then we must add the sub1 sub-register index to
861
508
      // the new location. However, that is only possible if the new virtual
862
508
      // register is of the same regclass (or if there is an equivalent
863
508
      // sub-register in that regclass). For now, simply skip handling copies if
864
508
      // a sub-register is involved.
865
508
      if (LI && !LocMO.getSubReg())
866
490
        addDefsFromCopies(LI, Loc.locNo(), Loc.wasIndirect(), Kills, Defs, MRI,
867
490
                          LIS);
868
508
      continue;
869
508
    }
870
756
871
756
    // For physregs, we only mark the start slot idx. DwarfDebug will see it
872
756
    // as if the DBG_VALUE is valid up until the end of the basic block, or
873
756
    // the next def of the physical register. So we do not need to extend the
874
756
    // range. It might actually happen that the DBG_VALUE is the last use of
875
756
    // the physical register (e.g. if this is an unused input argument to a
876
756
    // function).
877
756
  }
878
4.68k
879
4.68k
  // The computed intervals may extend beyond the range of the debug
880
4.68k
  // location's lexical scope. In this case, splitting of an interval
881
4.68k
  // can result in an interval outside of the scope being created,
882
4.68k
  // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
883
4.68k
  // this, trim the intervals to the lexical scope.
884
4.68k
885
4.68k
  LexicalScope *Scope = LS.findLexicalScope(dl);
886
4.68k
  if (!Scope)
887
33
    return;
888
4.65k
889
4.65k
  SlotIndex PrevEnd;
890
4.65k
  LocMap::iterator I = locInts.begin();
891
4.65k
892
4.65k
  // Iterate over the lexical scope ranges. Each time round the loop
893
4.65k
  // we check the intervals for overlap with the end of the previous
894
4.65k
  // range and the start of the next. The first range is handled as
895
4.65k
  // a special case where there is no PrevEnd.
896
4.67k
  for (const InsnRange &Range : Scope->getRanges()) {
897
4.67k
    SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
898
4.67k
    SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
899
4.67k
900
4.67k
    // At the start of each iteration I has been advanced so that
901
4.67k
    // I.stop() >= PrevEnd. Check for overlap.
902
4.67k
    if (PrevEnd && 
I.start() < PrevEnd17
) {
903
6
      SlotIndex IStop = I.stop();
904
6
      DbgValueLocation Loc = I.value();
905
6
906
6
      // Stop overlaps previous end - trim the end of the interval to
907
6
      // the scope range.
908
6
      I.setStopUnchecked(PrevEnd);
909
6
      ++I;
910
6
911
6
      // If the interval also overlaps the start of the "next" (i.e.
912
6
      // current) range create a new interval for the remainder
913
6
      if (RStart < IStop)
914
4
        I.insert(RStart, IStop, Loc);
915
6
    }
916
4.67k
917
4.67k
    // Advance I so that I.stop() >= RStart, and check for overlap.
918
4.67k
    I.advanceTo(RStart);
919
4.67k
    if (!I.valid())
920
100
      return;
921
4.57k
922
4.57k
    // The end of a lexical scope range is the last instruction in the
923
4.57k
    // range. To convert to an interval we need the index of the
924
4.57k
    // instruction after it.
925
4.57k
    REnd = REnd.getNextIndex();
926
4.57k
927
4.57k
    // Advance I to first interval outside current range.
928
4.57k
    I.advanceTo(REnd);
929
4.57k
    if (!I.valid())
930
4.52k
      return;
931
51
932
51
    PrevEnd = REnd;
933
51
  }
934
4.65k
935
4.65k
  // Check for overlap with end of final range.
936
4.65k
  
if (34
PrevEnd34
&&
I.start() < PrevEnd34
)
937
33
    I.setStopUnchecked(PrevEnd);
938
34
}
939
940
35.2k
void LDVImpl::computeIntervals() {
941
35.2k
  LexicalScopes LS;
942
35.2k
  LS.initialize(*MF);
943
35.2k
944
39.9k
  for (unsigned i = 0, e = userValues.size(); i != e; 
++i4.68k
) {
945
4.68k
    userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
946
4.68k
    userValues[i]->mapVirtRegs(this);
947
4.68k
  }
948
35.2k
}
949
950
35.2k
bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
951
35.2k
  clear();
952
35.2k
  MF = &mf;
953
35.2k
  LIS = &pass.getAnalysis<LiveIntervals>();
954
35.2k
  TRI = mf.getSubtarget().getRegisterInfo();
955
35.2k
  LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
956
35.2k
                    << mf.getName() << " **********\n");
957
35.2k
958
35.2k
  bool Changed = collectDebugValues(mf);
959
35.2k
  computeIntervals();
960
35.2k
  LLVM_DEBUG(print(dbgs()));
961
35.2k
  ModifiedMF = Changed;
962
35.2k
  return Changed;
963
35.2k
}
964
965
449k
static void removeDebugValues(MachineFunction &mf) {
966
2.42M
  for (MachineBasicBlock &MBB : mf) {
967
21.4M
    for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
968
19.0M
      if (!MBBI->isDebugValue()) {
969
19.0M
        ++MBBI;
970
19.0M
        continue;
971
19.0M
      }
972
29
      MBBI = MBB.erase(MBBI);
973
29
    }
974
2.42M
  }
975
449k
}
976
977
484k
bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
978
484k
  if (!EnableLDV)
979
0
    return false;
980
484k
  if (!mf.getFunction().getSubprogram()) {
981
449k
    removeDebugValues(mf);
982
449k
    return false;
983
449k
  }
984
35.2k
  if (!pImpl)
985
1.99k
    pImpl = new LDVImpl(this);
986
35.2k
  return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
987
35.2k
}
988
989
484k
void LiveDebugVariables::releaseMemory() {
990
484k
  if (pImpl)
991
35.3k
    static_cast<LDVImpl*>(pImpl)->clear();
992
484k
}
993
994
33.4k
LiveDebugVariables::~LiveDebugVariables() {
995
33.4k
  if (pImpl)
996
1.99k
    delete static_cast<LDVImpl*>(pImpl);
997
33.4k
}
998
999
//===----------------------------------------------------------------------===//
1000
//                           Live Range Splitting
1001
//===----------------------------------------------------------------------===//
1002
1003
bool
1004
UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
1005
15
                         LiveIntervals& LIS) {
1006
15
  LLVM_DEBUG({
1007
15
    dbgs() << "Splitting Loc" << OldLocNo << '\t';
1008
15
    print(dbgs(), nullptr);
1009
15
  });
1010
15
  bool DidChange = false;
1011
15
  LocMap::iterator LocMapI;
1012
15
  LocMapI.setMap(locInts);
1013
46
  for (unsigned i = 0; i != NewRegs.size(); 
++i31
) {
1014
31
    LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
1015
31
    if (LI->empty())
1016
1
      continue;
1017
30
1018
30
    // Don't allocate the new LocNo until it is needed.
1019
30
    unsigned NewLocNo = UndefLocNo;
1020
30
1021
30
    // Iterate over the overlaps between locInts and LI.
1022
30
    LocMapI.find(LI->beginIndex());
1023
30
    if (!LocMapI.valid())
1024
1
      continue;
1025
29
    LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
1026
29
    LiveInterval::iterator LIE = LI->end();
1027
49
    while (LocMapI.valid() && LII != LIE) {
1028
34
      // At this point, we know that LocMapI.stop() > LII->start.
1029
34
      LII = LI->advanceTo(LII, LocMapI.start());
1030
34
      if (LII == LIE)
1031
0
        break;
1032
34
1033
34
      // Now LII->end > LocMapI.start(). Do we have an overlap?
1034
34
      if (LocMapI.value().locNo() == OldLocNo && 
LII->start < LocMapI.stop()32
) {
1035
32
        // Overlapping correct location. Allocate NewLocNo now.
1036
32
        if (NewLocNo == UndefLocNo) {
1037
29
          MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
1038
29
          MO.setSubReg(locations[OldLocNo].getSubReg());
1039
29
          NewLocNo = getLocationNo(MO);
1040
29
          DidChange = true;
1041
29
        }
1042
32
1043
32
        SlotIndex LStart = LocMapI.start();
1044
32
        SlotIndex LStop  = LocMapI.stop();
1045
32
        DbgValueLocation OldLoc = LocMapI.value();
1046
32
1047
32
        // Trim LocMapI down to the LII overlap.
1048
32
        if (LStart < LII->start)
1049
8
          LocMapI.setStartUnchecked(LII->start);
1050
32
        if (LStop > LII->end)
1051
9
          LocMapI.setStopUnchecked(LII->end);
1052
32
1053
32
        // Change the value in the overlap. This may trigger coalescing.
1054
32
        LocMapI.setValue(OldLoc.changeLocNo(NewLocNo));
1055
32
1056
32
        // Re-insert any removed OldLocNo ranges.
1057
32
        if (LStart < LocMapI.start()) {
1058
8
          LocMapI.insert(LStart, LocMapI.start(), OldLoc);
1059
8
          ++LocMapI;
1060
8
          assert(LocMapI.valid() && "Unexpected coalescing");
1061
8
        }
1062
32
        if (LStop > LocMapI.stop()) {
1063
9
          ++LocMapI;
1064
9
          LocMapI.insert(LII->end, LStop, OldLoc);
1065
9
          --LocMapI;
1066
9
        }
1067
32
      }
1068
34
1069
34
      // Advance to the next overlap.
1070
34
      if (LII->end < LocMapI.stop()) {
1071
2
        if (++LII == LIE)
1072
2
          break;
1073
0
        LocMapI.advanceTo(LII->start);
1074
32
      } else {
1075
32
        ++LocMapI;
1076
32
        if (!LocMapI.valid())
1077
12
          break;
1078
20
        LII = LI->advanceTo(LII, LocMapI.start());
1079
20
      }
1080
34
    }
1081
29
  }
1082
15
1083
15
  // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
1084
15
  locations.erase(locations.begin() + OldLocNo);
1085
15
  LocMapI.goToBegin();
1086
50
  while (LocMapI.valid()) {
1087
35
    DbgValueLocation v = LocMapI.value();
1088
35
    if (v.locNo() == OldLocNo) {
1089
0
      LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
1090
0
                        << LocMapI.stop() << ")\n");
1091
0
      LocMapI.erase();
1092
35
    } else {
1093
35
      // Undef values always have location number UndefLocNo, so don't change
1094
35
      // locNo in that case. See getLocationNo().
1095
35
      if (!v.isUndef() && v.locNo() > OldLocNo)
1096
31
        LocMapI.setValueUnchecked(v.changeLocNo(v.locNo() - 1));
1097
35
      ++LocMapI;
1098
35
    }
1099
35
  }
1100
15
1101
15
  LLVM_DEBUG({
1102
15
    dbgs() << "Split result: \t";
1103
15
    print(dbgs(), nullptr);
1104
15
  });
1105
15
  return DidChange;
1106
15
}
1107
1108
bool
1109
UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
1110
15
                         LiveIntervals &LIS) {
1111
15
  bool DidChange = false;
1112
15
  // Split locations referring to OldReg. Iterate backwards so splitLocation can
1113
15
  // safely erase unused locations.
1114
36
  for (unsigned i = locations.size(); i ; 
--i21
) {
1115
21
    unsigned LocNo = i-1;
1116
21
    const MachineOperand *Loc = &locations[LocNo];
1117
21
    if (!Loc->isReg() || Loc->getReg() != OldReg)
1118
6
      continue;
1119
15
    DidChange |= splitLocation(LocNo, NewRegs, LIS);
1120
15
  }
1121
15
  return DidChange;
1122
15
}
1123
1124
23.7k
void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
1125
23.7k
  bool DidChange = false;
1126
23.7k
  for (UserValue *UV = lookupVirtReg(OldReg); UV; 
UV = UV->getNext()15
)
1127
15
    DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
1128
23.7k
1129
23.7k
  if (!DidChange)
1130
23.6k
    return;
1131
14
1132
14
  // Map all of the new virtual registers.
1133
14
  UserValue *UV = lookupVirtReg(OldReg);
1134
43
  for (unsigned i = 0; i != NewRegs.size(); 
++i29
)
1135
29
    mapVirtReg(NewRegs[i], UV);
1136
14
}
1137
1138
void LiveDebugVariables::
1139
177k
splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
1140
177k
  if (pImpl)
1141
23.7k
    static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
1142
177k
}
1143
1144
void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1145
                                 const TargetInstrInfo &TII,
1146
                                 const TargetRegisterInfo &TRI,
1147
4.68k
                                 SpillOffsetMap &SpillOffsets) {
1148
4.68k
  // Build a set of new locations with new numbers so we can coalesce our
1149
4.68k
  // IntervalMap if two vreg intervals collapse to the same physical location.
1150
4.68k
  // Use MapVector instead of SetVector because MapVector::insert returns the
1151
4.68k
  // position of the previously or newly inserted element. The boolean value
1152
4.68k
  // tracks if the location was produced by a spill.
1153
4.68k
  // FIXME: This will be problematic if we ever support direct and indirect
1154
4.68k
  // frame index locations, i.e. expressing both variables in memory and
1155
4.68k
  // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1156
4.68k
  MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
1157
4.68k
  SmallVector<unsigned, 4> LocNoMap(locations.size());
1158
9.56k
  for (unsigned I = 0, E = locations.size(); I != E; 
++I4.87k
) {
1159
4.87k
    bool Spilled = false;
1160
4.87k
    unsigned SpillOffset = 0;
1161
4.87k
    MachineOperand Loc = locations[I];
1162
4.87k
    // Only virtual registers are rewritten.
1163
4.87k
    if (Loc.isReg() && 
Loc.getReg()725
&&
1164
4.87k
        
TargetRegisterInfo::isVirtualRegister(Loc.getReg())725
) {
1165
485
      unsigned VirtReg = Loc.getReg();
1166
485
      if (VRM.isAssignedReg(VirtReg) &&
1167
485
          
TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))469
) {
1168
467
        // This can create a %noreg operand in rare cases when the sub-register
1169
467
        // index is no longer available. That means the user value is in a
1170
467
        // non-existent sub-register, and %noreg is exactly what we want.
1171
467
        Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1172
467
      } else 
if (18
VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT18
) {
1173
16
        // Retrieve the stack slot offset.
1174
16
        unsigned SpillSize;
1175
16
        const MachineRegisterInfo &MRI = MF.getRegInfo();
1176
16
        const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
1177
16
        bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
1178
16
                                             SpillOffset, MF);
1179
16
1180
16
        // FIXME: Invalidate the location if the offset couldn't be calculated.
1181
16
        (void)Success;
1182
16
1183
16
        Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
1184
16
        Spilled = true;
1185
16
      } else {
1186
2
        Loc.setReg(0);
1187
2
        Loc.setSubReg(0);
1188
2
      }
1189
485
    }
1190
4.87k
1191
4.87k
    // Insert this location if it doesn't already exist and record a mapping
1192
4.87k
    // from the old number to the new number.
1193
4.87k
    auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
1194
4.87k
    unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1195
4.87k
    LocNoMap[I] = NewLocNo;
1196
4.87k
  }
1197
4.68k
1198
4.68k
  // Rewrite the locations and record the stack slot offsets for spills.
1199
4.68k
  locations.clear();
1200
4.68k
  SpillOffsets.clear();
1201
4.74k
  for (auto &Pair : NewLocations) {
1202
4.74k
    bool Spilled;
1203
4.74k
    unsigned SpillOffset;
1204
4.74k
    std::tie(Spilled, SpillOffset) = Pair.second;
1205
4.74k
    locations.push_back(Pair.first);
1206
4.74k
    if (Spilled) {
1207
16
      unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1208
16
      SpillOffsets[NewLocNo] = SpillOffset;
1209
16
    }
1210
4.74k
  }
1211
4.68k
1212
4.68k
  // Update the interval map, but only coalesce left, since intervals to the
1213
4.68k
  // right use the old location numbers. This should merge two contiguous
1214
4.68k
  // DBG_VALUE intervals with different vregs that were allocated to the same
1215
4.68k
  // physical register.
1216
9.68k
  for (LocMap::iterator I = locInts.begin(); I.valid(); 
++I4.99k
) {
1217
4.99k
    DbgValueLocation Loc = I.value();
1218
4.99k
    // Undef values don't exist in locations (and thus not in LocNoMap either)
1219
4.99k
    // so skip over them. See getLocationNo().
1220
4.99k
    if (Loc.isUndef())
1221
75
      continue;
1222
4.92k
    unsigned NewLocNo = LocNoMap[Loc.locNo()];
1223
4.92k
    I.setValueUnchecked(Loc.changeLocNo(NewLocNo));
1224
4.92k
    I.setStart(I.start());
1225
4.92k
  }
1226
4.68k
}
1227
1228
/// Find an iterator for inserting a DBG_VALUE instruction.
1229
static MachineBasicBlock::iterator
1230
findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
1231
5.00k
                   LiveIntervals &LIS) {
1232
5.00k
  SlotIndex Start = LIS.getMBBStartIdx(MBB);
1233
5.00k
  Idx = Idx.getBaseIndex();
1234
5.00k
1235
5.00k
  // Try to find an insert location by going backwards from Idx.
1236
5.00k
  MachineInstr *MI;
1237
5.36k
  while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1238
4.82k
    // We've reached the beginning of MBB.
1239
4.82k
    if (Idx == Start) {
1240
4.46k
      MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
1241
4.46k
      return I;
1242
4.46k
    }
1243
361
    Idx = Idx.getPrevIndex();
1244
361
  }
1245
5.00k
1246
5.00k
  // Don't insert anything after the first terminator, though.
1247
5.00k
  
return MI->isTerminator() 534
?
MBB->getFirstTerminator()0
:
1248
534
                              std::next(MachineBasicBlock::iterator(MI));
1249
5.00k
}
1250
1251
/// Find an iterator for inserting the next DBG_VALUE instruction
1252
/// (or end if no more insert locations found).
1253
static MachineBasicBlock::iterator
1254
findNextInsertLocation(MachineBasicBlock *MBB,
1255
                       MachineBasicBlock::iterator I,
1256
                       SlotIndex StopIdx, MachineOperand &LocMO,
1257
                       LiveIntervals &LIS,
1258
5.00k
                       const TargetRegisterInfo &TRI) {
1259
5.00k
  if (!LocMO.isReg())
1260
4.17k
    return MBB->instr_end();
1261
831
  unsigned Reg = LocMO.getReg();
1262
831
1263
831
  // Find the next instruction in the MBB that define the register Reg.
1264
2.77k
  while (I != MBB->end() && 
!I->isTerminator()2.74k
) {
1265
2.53k
    if (!LIS.isNotInMIMap(*I) &&
1266
2.53k
        
SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I))2.32k
)
1267
587
      break;
1268
1.95k
    if (I->definesRegister(Reg, &TRI))
1269
5
      // The insert location is directly after the instruction/bundle.
1270
5
      return std::next(I);
1271
1.94k
    ++I;
1272
1.94k
  }
1273
831
  
return MBB->end()826
;
1274
831
}
1275
1276
void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1277
                                 SlotIndex StopIdx, DbgValueLocation Loc,
1278
                                 bool Spilled, unsigned SpillOffset,
1279
                                 LiveIntervals &LIS, const TargetInstrInfo &TII,
1280
4.99k
                                 const TargetRegisterInfo &TRI) {
1281
4.99k
  SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1282
4.99k
  // Only search within the current MBB.
1283
4.99k
  StopIdx = (MBBEndIdx < StopIdx) ? 
MBBEndIdx0
: StopIdx;
1284
4.99k
  MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS);
1285
4.99k
  // Undef values don't exist in locations so create new "noreg" register MOs
1286
4.99k
  // for them. See getLocationNo().
1287
4.99k
  MachineOperand MO = !Loc.isUndef() ?
1288
4.92k
    locations[Loc.locNo()] :
1289
4.99k
    MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false,
1290
75
                              /* isKill */ false, /* isDead */ false,
1291
75
                              /* isUndef */ false, /* isEarlyClobber */ false,
1292
75
                              /* SubReg */ 0, /* isDebug */ true);
1293
4.99k
1294
4.99k
  ++NumInsertedDebugValues;
1295
4.99k
1296
4.99k
  assert(cast<DILocalVariable>(Variable)
1297
4.99k
             ->isValidLocationForIntrinsic(getDebugLoc()) &&
1298
4.99k
         "Expected inlined-at fields to agree");
1299
4.99k
1300
4.99k
  // If the location was spilled, the new DBG_VALUE will be indirect. If the
1301
4.99k
  // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1302
4.99k
  // that the original virtual register was a pointer. Also, add the stack slot
1303
4.99k
  // offset for the spilled register to the expression.
1304
4.99k
  const DIExpression *Expr = Expression;
1305
4.99k
  uint8_t DIExprFlags = DIExpression::ApplyOffset;
1306
4.99k
  bool IsIndirect = Loc.wasIndirect();
1307
4.99k
  if (Spilled) {
1308
16
    if (IsIndirect)
1309
2
      DIExprFlags |= DIExpression::DerefAfter;
1310
16
    Expr =
1311
16
        DIExpression::prepend(Expr, DIExprFlags, SpillOffset);
1312
16
    IsIndirect = true;
1313
16
  }
1314
4.99k
1315
4.99k
  assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
1316
4.99k
1317
5.00k
  do {
1318
5.00k
    BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
1319
5.00k
            IsIndirect, MO, Variable, Expr);
1320
5.00k
1321
5.00k
    // Continue and insert DBG_VALUES after every redefinition of register
1322
5.00k
    // associated with the debug value within the range
1323
5.00k
    I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
1324
5.00k
  } while (I != MBB->end());
1325
4.99k
}
1326
1327
void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1328
                                 LiveIntervals &LIS,
1329
4
                                 const TargetInstrInfo &TII) {
1330
4
  MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
1331
4
  ++NumInsertedDebugLabels;
1332
4
  BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
1333
4
      .addMetadata(Label);
1334
4
}
1335
1336
void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1337
                                const TargetInstrInfo &TII,
1338
                                const TargetRegisterInfo &TRI,
1339
4.68k
                                const SpillOffsetMap &SpillOffsets) {
1340
4.68k
  MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1341
4.68k
1342
9.68k
  for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1343
4.99k
    SlotIndex Start = I.start();
1344
4.99k
    SlotIndex Stop = I.stop();
1345
4.99k
    DbgValueLocation Loc = I.value();
1346
4.99k
    auto SpillIt =
1347
4.99k
        !Loc.isUndef() ? 
SpillOffsets.find(Loc.locNo())4.92k
:
SpillOffsets.end()75
;
1348
4.99k
    bool Spilled = SpillIt != SpillOffsets.end();
1349
4.99k
    unsigned SpillOffset = Spilled ? 
SpillIt->second16
:
04.98k
;
1350
4.99k
1351
4.99k
    LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << Loc.locNo());
1352
4.99k
    MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1353
4.99k
    SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1354
4.99k
1355
4.99k
    LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1356
4.99k
    insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII,
1357
4.99k
                     TRI);
1358
4.99k
    // This interval may span multiple basic blocks.
1359
4.99k
    // Insert a DBG_VALUE into each one.
1360
4.99k
    while (Stop > MBBEnd) {
1361
0
      // Move to the next block.
1362
0
      Start = MBBEnd;
1363
0
      if (++MBB == MFEnd)
1364
0
        break;
1365
0
      MBBEnd = LIS.getMBBEndIdx(&*MBB);
1366
0
      LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1367
0
      insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII,
1368
0
                       TRI);
1369
0
    }
1370
4.99k
    LLVM_DEBUG(dbgs() << '\n');
1371
4.99k
    if (MBB == MFEnd)
1372
0
      break;
1373
4.99k
1374
4.99k
    ++I;
1375
4.99k
  }
1376
4.68k
}
1377
1378
4
void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII) {
1379
4
  LLVM_DEBUG(dbgs() << "\t" << loc);
1380
4
  MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
1381
4
1382
4
  LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1383
4
  insertDebugLabel(&*MBB, loc, LIS, TII);
1384
4
1385
4
  LLVM_DEBUG(dbgs() << '\n');
1386
4
}
1387
1388
35.3k
void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1389
35.3k
  LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1390
35.3k
  if (!MF)
1391
54
    return;
1392
35.2k
  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1393
35.2k
  SpillOffsetMap SpillOffsets;
1394
35.2k
  for (auto &userValue : userValues) {
1395
4.68k
    LLVM_DEBUG(userValue->print(dbgs(), TRI));
1396
4.68k
    userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
1397
4.68k
    userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets);
1398
4.68k
  }
1399
35.2k
  LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
1400
35.2k
  for (auto &userLabel : userLabels) {
1401
4
    LLVM_DEBUG(userLabel->print(dbgs(), TRI));
1402
4
    userLabel->emitDebugLabel(*LIS, *TII);
1403
4
  }
1404
35.2k
  EmitDone = true;
1405
35.2k
}
1406
1407
484k
void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1408
484k
  if (pImpl)
1409
35.3k
    static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1410
484k
}
1411
1412
33.6k
bool LiveDebugVariables::doInitialization(Module &M) {
1413
33.6k
  return Pass::doInitialization(M);
1414
33.6k
}
1415
1416
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1417
LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
1418
  if (pImpl)
1419
    static_cast<LDVImpl*>(pImpl)->print(dbgs());
1420
}
1421
#endif