xref: /llvm-project/llvm/lib/CodeGen/LiveDebugVariables.cpp (revision dee85d47d9f15fc268f7b18f279dac2774836615)
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/InitializePasses.h"
53 #include "llvm/MC/MCRegisterInfo.h"
54 #include "llvm/Pass.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/CommandLine.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 INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
79                 "Debug Variable Analysis", false, false)
80 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
81 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
82 INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
83                 "Debug Variable Analysis", false, false)
84 
85 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
86   AU.addRequired<MachineDominatorTree>();
87   AU.addRequiredTransitive<LiveIntervals>();
88   AU.setPreservesAll();
89   MachineFunctionPass::getAnalysisUsage(AU);
90 }
91 
92 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
93   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
94 }
95 
96 enum : unsigned { UndefLocNo = ~0U };
97 
98 namespace {
99 /// Describes a debug variable value by location number and expression along
100 /// with some flags about the original usage of the location.
101 class DbgVariableValue {
102 public:
103   DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList,
104                    const DIExpression &Expr)
105       : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) {
106     assert(!(WasIndirect && WasList) &&
107            "DBG_VALUE_LISTs should not be indirect.");
108     SmallVector<unsigned> LocNoVec;
109     for (unsigned LocNo : NewLocs) {
110       auto It = find(LocNoVec, LocNo);
111       if (It == LocNoVec.end())
112         LocNoVec.push_back(LocNo);
113       else {
114         // Loc duplicates an element in LocNos; replace references to Op
115         // with references to the duplicating element.
116         unsigned OpIdx = LocNoVec.size();
117         unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It);
118         Expression =
119             DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx);
120       }
121     }
122     // FIXME: Debug values referencing 64+ unique machine locations are rare and
123     // currently unsupported for performance reasons. If we can verify that
124     // performance is acceptable for such debug values, we can increase the
125     // bit-width of LocNoCount to 14 to enable up to 16384 unique machine
126     // locations. We will also need to verify that this does not cause issues
127     // with LiveDebugVariables' use of IntervalMap.
128     if (LocNoVec.size() < 64) {
129       LocNoCount = LocNoVec.size();
130       if (LocNoCount > 0) {
131         LocNos = std::make_unique<unsigned[]>(LocNoCount);
132         std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin());
133       }
134     } else {
135       LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine "
136                            "locations, dropping...\n");
137       LocNoCount = 1;
138       // Turn this into an undef debug value list; right now, the simplest form
139       // of this is an expression with one arg, and an undef debug operand.
140       Expression =
141           DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0,
142                                                 dwarf::DW_OP_stack_value});
143       if (auto FragmentInfoOpt = Expr.getFragmentInfo())
144         Expression = *DIExpression::createFragmentExpression(
145             Expression, FragmentInfoOpt->OffsetInBits,
146             FragmentInfoOpt->SizeInBits);
147       LocNos = std::make_unique<unsigned[]>(LocNoCount);
148       LocNos[0] = UndefLocNo;
149     }
150   }
151 
152   DbgVariableValue() : LocNoCount(0), WasIndirect(0), WasList(0) {}
153   DbgVariableValue(const DbgVariableValue &Other)
154       : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()),
155         WasList(Other.getWasList()), Expression(Other.getExpression()) {
156     if (Other.getLocNoCount()) {
157       LocNos.reset(new unsigned[Other.getLocNoCount()]);
158       std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
159     }
160   }
161 
162   DbgVariableValue &operator=(const DbgVariableValue &Other) {
163     if (this == &Other)
164       return *this;
165     if (Other.getLocNoCount()) {
166       LocNos.reset(new unsigned[Other.getLocNoCount()]);
167       std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
168     } else {
169       LocNos.release();
170     }
171     LocNoCount = Other.getLocNoCount();
172     WasIndirect = Other.getWasIndirect();
173     WasList = Other.getWasList();
174     Expression = Other.getExpression();
175     return *this;
176   }
177 
178   const DIExpression *getExpression() const { return Expression; }
179   uint8_t getLocNoCount() const { return LocNoCount; }
180   bool containsLocNo(unsigned LocNo) const {
181     return is_contained(loc_nos(), LocNo);
182   }
183   bool getWasIndirect() const { return WasIndirect; }
184   bool getWasList() const { return WasList; }
185   bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); }
186 
187   DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const {
188     SmallVector<unsigned, 4> NewLocNos;
189     for (unsigned LocNo : loc_nos())
190       NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1
191                                                                : LocNo);
192     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
193   }
194 
195   DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const {
196     SmallVector<unsigned> NewLocNos;
197     for (unsigned LocNo : loc_nos())
198       // Undef values don't exist in locations (and thus not in LocNoMap
199       // either) so skip over them. See getLocationNo().
200       NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]);
201     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
202   }
203 
204   DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const {
205     SmallVector<unsigned> NewLocNos;
206     NewLocNos.assign(loc_nos_begin(), loc_nos_end());
207     auto OldLocIt = find(NewLocNos, OldLocNo);
208     assert(OldLocIt != NewLocNos.end() && "Old location must be present.");
209     *OldLocIt = NewLocNo;
210     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
211   }
212 
213   bool hasLocNoGreaterThan(unsigned LocNo) const {
214     return any_of(loc_nos(),
215                   [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; });
216   }
217 
218   void printLocNos(llvm::raw_ostream &OS) const {
219     for (const unsigned &Loc : loc_nos())
220       OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc;
221   }
222 
223   friend inline bool operator==(const DbgVariableValue &LHS,
224                                 const DbgVariableValue &RHS) {
225     if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList,
226                  LHS.Expression) !=
227         std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression))
228       return false;
229     return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(),
230                       RHS.loc_nos_begin());
231   }
232 
233   friend inline bool operator!=(const DbgVariableValue &LHS,
234                                 const DbgVariableValue &RHS) {
235     return !(LHS == RHS);
236   }
237 
238   unsigned *loc_nos_begin() { return LocNos.get(); }
239   const unsigned *loc_nos_begin() const { return LocNos.get(); }
240   unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; }
241   const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; }
242   ArrayRef<unsigned> loc_nos() const {
243     return ArrayRef<unsigned>(LocNos.get(), LocNoCount);
244   }
245 
246 private:
247   // IntervalMap requires the value object to be very small, to the extent
248   // that we do not have enough room for an std::vector. Using a C-style array
249   // (with a unique_ptr wrapper for convenience) allows us to optimize for this
250   // specific case by packing the array size into only 6 bits (it is highly
251   // unlikely that any debug value will need 64+ locations).
252   std::unique_ptr<unsigned[]> LocNos;
253   uint8_t LocNoCount : 6;
254   bool WasIndirect : 1;
255   bool WasList : 1;
256   const DIExpression *Expression = nullptr;
257 };
258 } // namespace
259 
260 /// Map of where a user value is live to that value.
261 using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>;
262 
263 /// Map of stack slot offsets for spilled locations.
264 /// Non-spilled locations are not added to the map.
265 using SpillOffsetMap = DenseMap<unsigned, unsigned>;
266 
267 /// Cache to save the location where it can be used as the starting
268 /// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug.
269 /// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from
270 /// repeatedly searching the same set of PHIs/Labels/Debug instructions
271 /// if it is called many times for the same block.
272 using BlockSkipInstsMap =
273     DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>;
274 
275 namespace {
276 
277 class LDVImpl;
278 
279 /// A user value is a part of a debug info user variable.
280 ///
281 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
282 /// holds part of a user variable. The part is identified by a byte offset.
283 ///
284 /// UserValues are grouped into equivalence classes for easier searching. Two
285 /// user values are related if they are held by the same virtual register. The
286 /// equivalence class is the transitive closure of that relation.
287 class UserValue {
288   const DILocalVariable *Variable; ///< The debug info variable we are part of.
289   /// The part of the variable we describe.
290   const Optional<DIExpression::FragmentInfo> Fragment;
291   DebugLoc dl;            ///< The debug location for the variable. This is
292                           ///< used by dwarf writer to find lexical scope.
293   UserValue *leader;      ///< Equivalence class leader.
294   UserValue *next = nullptr; ///< Next value in equivalence class, or null.
295 
296   /// Numbered locations referenced by locmap.
297   SmallVector<MachineOperand, 4> locations;
298 
299   /// Map of slot indices where this value is live.
300   LocMap locInts;
301 
302   /// Set of interval start indexes that have been trimmed to the
303   /// lexical scope.
304   SmallSet<SlotIndex, 2> trimmedDefs;
305 
306   /// Insert a DBG_VALUE into MBB at Idx for DbgValue.
307   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
308                         SlotIndex StopIdx, DbgVariableValue DbgValue,
309                         ArrayRef<bool> LocSpills,
310                         ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS,
311                         const TargetInstrInfo &TII,
312                         const TargetRegisterInfo &TRI,
313                         BlockSkipInstsMap &BBSkipInstsMap);
314 
315   /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
316   /// is live. Returns true if any changes were made.
317   bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
318                      LiveIntervals &LIS);
319 
320 public:
321   /// Create a new UserValue.
322   UserValue(const DILocalVariable *var,
323             Optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
324             LocMap::Allocator &alloc)
325       : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
326         locInts(alloc) {}
327 
328   /// Get the leader of this value's equivalence class.
329   UserValue *getLeader() {
330     UserValue *l = leader;
331     while (l != l->leader)
332       l = l->leader;
333     return leader = l;
334   }
335 
336   /// Return the next UserValue in the equivalence class.
337   UserValue *getNext() const { return next; }
338 
339   /// Merge equivalence classes.
340   static UserValue *merge(UserValue *L1, UserValue *L2) {
341     L2 = L2->getLeader();
342     if (!L1)
343       return L2;
344     L1 = L1->getLeader();
345     if (L1 == L2)
346       return L1;
347     // Splice L2 before L1's members.
348     UserValue *End = L2;
349     while (End->next) {
350       End->leader = L1;
351       End = End->next;
352     }
353     End->leader = L1;
354     End->next = L1->next;
355     L1->next = L2;
356     return L1;
357   }
358 
359   /// Return the location number that matches Loc.
360   ///
361   /// For undef values we always return location number UndefLocNo without
362   /// inserting anything in locations. Since locations is a vector and the
363   /// location number is the position in the vector and UndefLocNo is ~0,
364   /// we would need a very big vector to put the value at the right position.
365   unsigned getLocationNo(const MachineOperand &LocMO) {
366     if (LocMO.isReg()) {
367       if (LocMO.getReg() == 0)
368         return UndefLocNo;
369       // For register locations we dont care about use/def and other flags.
370       for (unsigned i = 0, e = locations.size(); i != e; ++i)
371         if (locations[i].isReg() &&
372             locations[i].getReg() == LocMO.getReg() &&
373             locations[i].getSubReg() == LocMO.getSubReg())
374           return i;
375     } else
376       for (unsigned i = 0, e = locations.size(); i != e; ++i)
377         if (LocMO.isIdenticalTo(locations[i]))
378           return i;
379     locations.push_back(LocMO);
380     // We are storing a MachineOperand outside a MachineInstr.
381     locations.back().clearParent();
382     // Don't store def operands.
383     if (locations.back().isReg()) {
384       if (locations.back().isDef())
385         locations.back().setIsDead(false);
386       locations.back().setIsUse();
387     }
388     return locations.size() - 1;
389   }
390 
391   /// Remove (recycle) a location number. If \p LocNo still is used by the
392   /// locInts nothing is done.
393   void removeLocationIfUnused(unsigned LocNo) {
394     // Bail out if LocNo still is used.
395     for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
396       const DbgVariableValue &DbgValue = I.value();
397       if (DbgValue.containsLocNo(LocNo))
398         return;
399     }
400     // Remove the entry in the locations vector, and adjust all references to
401     // location numbers above the removed entry.
402     locations.erase(locations.begin() + LocNo);
403     for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
404       const DbgVariableValue &DbgValue = I.value();
405       if (DbgValue.hasLocNoGreaterThan(LocNo))
406         I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo));
407     }
408   }
409 
410   /// Ensure that all virtual register locations are mapped.
411   void mapVirtRegs(LDVImpl *LDV);
412 
413   /// Add a definition point to this user value.
414   void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect,
415               bool IsList, const DIExpression &Expr) {
416     SmallVector<unsigned> Locs;
417     for (MachineOperand Op : LocMOs)
418       Locs.push_back(getLocationNo(Op));
419     DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr);
420     // Add a singular (Idx,Idx) -> value mapping.
421     LocMap::iterator I = locInts.find(Idx);
422     if (!I.valid() || I.start() != Idx)
423       I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue));
424     else
425       // A later DBG_VALUE at the same SlotIndex overrides the old location.
426       I.setValue(std::move(DbgValue));
427   }
428 
429   /// Extend the current definition as far as possible down.
430   ///
431   /// Stop when meeting an existing def or when leaving the live
432   /// range of VNI. End points where VNI is no longer live are added to Kills.
433   ///
434   /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
435   /// data-flow analysis to propagate them beyond basic block boundaries.
436   ///
437   /// \param Idx Starting point for the definition.
438   /// \param DbgValue value to propagate.
439   /// \param LiveIntervalInfo For each location number key in this map,
440   /// restricts liveness to where the LiveRange has the value equal to the\
441   /// VNInfo.
442   /// \param [out] Kills Append end points of VNI's live range to Kills.
443   /// \param LIS Live intervals analysis.
444   void extendDef(SlotIndex Idx, DbgVariableValue DbgValue,
445                  SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
446                      &LiveIntervalInfo,
447                  Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
448                  LiveIntervals &LIS);
449 
450   /// The value in LI may be copies to other registers. Determine if
451   /// any of the copies are available at the kill points, and add defs if
452   /// possible.
453   ///
454   /// \param DbgValue Location number of LI->reg, and DIExpression.
455   /// \param LocIntervals Scan for copies of the value for each location in the
456   /// corresponding LiveInterval->reg.
457   /// \param KilledAt The point where the range of DbgValue could be extended.
458   /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here.
459   void addDefsFromCopies(
460       DbgVariableValue DbgValue,
461       SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
462       SlotIndex KilledAt,
463       SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
464       MachineRegisterInfo &MRI, LiveIntervals &LIS);
465 
466   /// Compute the live intervals of all locations after collecting all their
467   /// def points.
468   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
469                         LiveIntervals &LIS, LexicalScopes &LS);
470 
471   /// Replace OldReg ranges with NewRegs ranges where NewRegs is
472   /// live. Returns true if any changes were made.
473   bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
474                      LiveIntervals &LIS);
475 
476   /// Rewrite virtual register locations according to the provided virtual
477   /// register map. Record the stack slot offsets for the locations that
478   /// were spilled.
479   void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
480                         const TargetInstrInfo &TII,
481                         const TargetRegisterInfo &TRI,
482                         SpillOffsetMap &SpillOffsets);
483 
484   /// Recreate DBG_VALUE instruction from data structures.
485   void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
486                        const TargetInstrInfo &TII,
487                        const TargetRegisterInfo &TRI,
488                        const SpillOffsetMap &SpillOffsets,
489                        BlockSkipInstsMap &BBSkipInstsMap);
490 
491   /// Return DebugLoc of this UserValue.
492   const DebugLoc &getDebugLoc() { return dl; }
493 
494   void print(raw_ostream &, const TargetRegisterInfo *);
495 };
496 
497 /// A user label is a part of a debug info user label.
498 class UserLabel {
499   const DILabel *Label; ///< The debug info label we are part of.
500   DebugLoc dl;          ///< The debug location for the label. This is
501                         ///< used by dwarf writer to find lexical scope.
502   SlotIndex loc;        ///< Slot used by the debug label.
503 
504   /// Insert a DBG_LABEL into MBB at Idx.
505   void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
506                         LiveIntervals &LIS, const TargetInstrInfo &TII,
507                         BlockSkipInstsMap &BBSkipInstsMap);
508 
509 public:
510   /// Create a new UserLabel.
511   UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
512       : Label(label), dl(std::move(L)), loc(Idx) {}
513 
514   /// Does this UserLabel match the parameters?
515   bool matches(const DILabel *L, const DILocation *IA,
516              const SlotIndex Index) const {
517     return Label == L && dl->getInlinedAt() == IA && loc == Index;
518   }
519 
520   /// Recreate DBG_LABEL instruction from data structures.
521   void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
522                       BlockSkipInstsMap &BBSkipInstsMap);
523 
524   /// Return DebugLoc of this UserLabel.
525   const DebugLoc &getDebugLoc() { return dl; }
526 
527   void print(raw_ostream &, const TargetRegisterInfo *);
528 };
529 
530 /// Implementation of the LiveDebugVariables pass.
531 class LDVImpl {
532   LiveDebugVariables &pass;
533   LocMap::Allocator allocator;
534   MachineFunction *MF = nullptr;
535   LiveIntervals *LIS;
536   const TargetRegisterInfo *TRI;
537 
538   using StashedInstrRef =
539       std::tuple<unsigned, unsigned, const DILocalVariable *,
540                  const DIExpression *, DebugLoc>;
541 
542   /// Position and VReg of a PHI instruction during register allocation.
543   struct PHIValPos {
544     SlotIndex SI;    /// Slot where this PHI occurs.
545     Register Reg;    /// VReg this PHI occurs in.
546     unsigned SubReg; /// Qualifiying subregister for Reg.
547   };
548 
549   /// Map from debug instruction number to PHI position during allocation.
550   std::map<unsigned, PHIValPos> PHIValToPos;
551   /// Index of, for each VReg, which debug instruction numbers and corresponding
552   /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
553   /// at different positions.
554   DenseMap<Register, std::vector<unsigned>> RegToPHIIdx;
555 
556   std::map<SlotIndex, std::vector<StashedInstrRef>> StashedInstrReferences;
557 
558   /// Whether emitDebugValues is called.
559   bool EmitDone = false;
560 
561   /// Whether the machine function is modified during the pass.
562   bool ModifiedMF = false;
563 
564   /// All allocated UserValue instances.
565   SmallVector<std::unique_ptr<UserValue>, 8> userValues;
566 
567   /// All allocated UserLabel instances.
568   SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
569 
570   /// Map virtual register to eq class leader.
571   using VRMap = DenseMap<unsigned, UserValue *>;
572   VRMap virtRegToEqClass;
573 
574   /// Map to find existing UserValue instances.
575   using UVMap = DenseMap<DebugVariable, UserValue *>;
576   UVMap userVarMap;
577 
578   /// Find or create a UserValue.
579   UserValue *getUserValue(const DILocalVariable *Var,
580                           Optional<DIExpression::FragmentInfo> Fragment,
581                           const DebugLoc &DL);
582 
583   /// Find the EC leader for VirtReg or null.
584   UserValue *lookupVirtReg(Register VirtReg);
585 
586   /// Add DBG_VALUE instruction to our maps.
587   ///
588   /// \param MI DBG_VALUE instruction
589   /// \param Idx Last valid SLotIndex before instruction.
590   ///
591   /// \returns True if the DBG_VALUE instruction should be deleted.
592   bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
593 
594   /// Track a DBG_INSTR_REF. This needs to be removed from the MachineFunction
595   /// during regalloc -- but there's no need to maintain live ranges, as we
596   /// refer to a value rather than a location.
597   ///
598   /// \param MI DBG_INSTR_REF instruction
599   /// \param Idx Last valid SlotIndex before instruction
600   ///
601   /// \returns True if the DBG_VALUE instruction should be deleted.
602   bool handleDebugInstrRef(MachineInstr &MI, SlotIndex Idx);
603 
604   /// Add DBG_LABEL instruction to UserLabel.
605   ///
606   /// \param MI DBG_LABEL instruction
607   /// \param Idx Last valid SlotIndex before instruction.
608   ///
609   /// \returns True if the DBG_LABEL instruction should be deleted.
610   bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
611 
612   /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
613   /// for each instruction.
614   ///
615   /// \param mf MachineFunction to be scanned.
616   ///
617   /// \returns True if any debug values were found.
618   bool collectDebugValues(MachineFunction &mf);
619 
620   /// Compute the live intervals of all user values after collecting all
621   /// their def points.
622   void computeIntervals();
623 
624 public:
625   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
626 
627   bool runOnMachineFunction(MachineFunction &mf);
628 
629   /// Release all memory.
630   void clear() {
631     MF = nullptr;
632     PHIValToPos.clear();
633     RegToPHIIdx.clear();
634     StashedInstrReferences.clear();
635     userValues.clear();
636     userLabels.clear();
637     virtRegToEqClass.clear();
638     userVarMap.clear();
639     // Make sure we call emitDebugValues if the machine function was modified.
640     assert((!ModifiedMF || EmitDone) &&
641            "Dbg values are not emitted in LDV");
642     EmitDone = false;
643     ModifiedMF = false;
644   }
645 
646   /// Map virtual register to an equivalence class.
647   void mapVirtReg(Register VirtReg, UserValue *EC);
648 
649   /// Replace any PHI referring to OldReg with its corresponding NewReg, if
650   /// present.
651   void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
652 
653   /// Replace all references to OldReg with NewRegs.
654   void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
655 
656   /// Recreate DBG_VALUE instruction from data structures.
657   void emitDebugValues(VirtRegMap *VRM);
658 
659   void print(raw_ostream&);
660 };
661 
662 } // end anonymous namespace
663 
664 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
665 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
666                           const LLVMContext &Ctx) {
667   if (!DL)
668     return;
669 
670   auto *Scope = cast<DIScope>(DL.getScope());
671   // Omit the directory, because it's likely to be long and uninteresting.
672   CommentOS << Scope->getFilename();
673   CommentOS << ':' << DL.getLine();
674   if (DL.getCol() != 0)
675     CommentOS << ':' << DL.getCol();
676 
677   DebugLoc InlinedAtDL = DL.getInlinedAt();
678   if (!InlinedAtDL)
679     return;
680 
681   CommentOS << " @[ ";
682   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
683   CommentOS << " ]";
684 }
685 
686 static void printExtendedName(raw_ostream &OS, const DINode *Node,
687                               const DILocation *DL) {
688   const LLVMContext &Ctx = Node->getContext();
689   StringRef Res;
690   unsigned Line = 0;
691   if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
692     Res = V->getName();
693     Line = V->getLine();
694   } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
695     Res = L->getName();
696     Line = L->getLine();
697   }
698 
699   if (!Res.empty())
700     OS << Res << "," << Line;
701   auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
702   if (InlinedAt) {
703     if (DebugLoc InlinedAtDL = InlinedAt) {
704       OS << " @[";
705       printDebugLoc(InlinedAtDL, OS, Ctx);
706       OS << "]";
707     }
708   }
709 }
710 
711 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
712   OS << "!\"";
713   printExtendedName(OS, Variable, dl);
714 
715   OS << "\"\t";
716   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
717     OS << " [" << I.start() << ';' << I.stop() << "):";
718     if (I.value().isUndef())
719       OS << " undef";
720     else {
721       I.value().printLocNos(OS);
722       if (I.value().getWasIndirect())
723         OS << " ind";
724       else if (I.value().getWasList())
725         OS << " list";
726     }
727   }
728   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
729     OS << " Loc" << i << '=';
730     locations[i].print(OS, TRI);
731   }
732   OS << '\n';
733 }
734 
735 void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
736   OS << "!\"";
737   printExtendedName(OS, Label, dl);
738 
739   OS << "\"\t";
740   OS << loc;
741   OS << '\n';
742 }
743 
744 void LDVImpl::print(raw_ostream &OS) {
745   OS << "********** DEBUG VARIABLES **********\n";
746   for (auto &userValue : userValues)
747     userValue->print(OS, TRI);
748   OS << "********** DEBUG LABELS **********\n";
749   for (auto &userLabel : userLabels)
750     userLabel->print(OS, TRI);
751 }
752 #endif
753 
754 void UserValue::mapVirtRegs(LDVImpl *LDV) {
755   for (unsigned i = 0, e = locations.size(); i != e; ++i)
756     if (locations[i].isReg() &&
757         Register::isVirtualRegister(locations[i].getReg()))
758       LDV->mapVirtReg(locations[i].getReg(), this);
759 }
760 
761 UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
762                                  Optional<DIExpression::FragmentInfo> Fragment,
763                                  const DebugLoc &DL) {
764   // FIXME: Handle partially overlapping fragments. See
765   // https://reviews.llvm.org/D70121#1849741.
766   DebugVariable ID(Var, Fragment, DL->getInlinedAt());
767   UserValue *&UV = userVarMap[ID];
768   if (!UV) {
769     userValues.push_back(
770         std::make_unique<UserValue>(Var, Fragment, DL, allocator));
771     UV = userValues.back().get();
772   }
773   return UV;
774 }
775 
776 void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) {
777   assert(Register::isVirtualRegister(VirtReg) && "Only map VirtRegs");
778   UserValue *&Leader = virtRegToEqClass[VirtReg];
779   Leader = UserValue::merge(Leader, EC);
780 }
781 
782 UserValue *LDVImpl::lookupVirtReg(Register VirtReg) {
783   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
784     return UV->getLeader();
785   return nullptr;
786 }
787 
788 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
789   // DBG_VALUE loc, offset, variable, expr
790   // DBG_VALUE_LIST variable, expr, locs...
791   if (!MI.isDebugValue()) {
792     LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
793     return false;
794   }
795   if (!MI.getDebugVariableOp().isMetadata()) {
796     LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
797                       << MI);
798     return false;
799   }
800   if (MI.isNonListDebugValue() &&
801       (MI.getNumOperands() != 4 ||
802        !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
803     LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
804     return false;
805   }
806 
807   // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
808   // register that hasn't been defined yet. If we do not remove those here, then
809   // the re-insertion of the DBG_VALUE instruction after register allocation
810   // will be incorrect.
811   // TODO: If earlier passes are corrected to generate sane debug information
812   // (and if the machine verifier is improved to catch this), then these checks
813   // could be removed or replaced by asserts.
814   bool Discard = false;
815   for (const MachineOperand &Op : MI.debug_operands()) {
816     if (Op.isReg() && Register::isVirtualRegister(Op.getReg())) {
817       const Register Reg = Op.getReg();
818       if (!LIS->hasInterval(Reg)) {
819         // The DBG_VALUE is described by a virtual register that does not have a
820         // live interval. Discard the DBG_VALUE.
821         Discard = true;
822         LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
823                           << " " << MI);
824       } else {
825         // The DBG_VALUE is only valid if either Reg is live out from Idx, or
826         // Reg is defined dead at Idx (where Idx is the slot index for the
827         // instruction preceding the DBG_VALUE).
828         const LiveInterval &LI = LIS->getInterval(Reg);
829         LiveQueryResult LRQ = LI.Query(Idx);
830         if (!LRQ.valueOutOrDead()) {
831           // We have found a DBG_VALUE with the value in a virtual register that
832           // is not live. Discard the DBG_VALUE.
833           Discard = true;
834           LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
835                             << " " << MI);
836         }
837       }
838     }
839   }
840 
841   // Get or create the UserValue for (variable,offset) here.
842   bool IsIndirect = MI.isDebugOffsetImm();
843   if (IsIndirect)
844     assert(MI.getDebugOffset().getImm() == 0 &&
845            "DBG_VALUE with nonzero offset");
846   bool IsList = MI.isDebugValueList();
847   const DILocalVariable *Var = MI.getDebugVariable();
848   const DIExpression *Expr = MI.getDebugExpression();
849   UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
850   if (!Discard)
851     UV->addDef(Idx,
852                ArrayRef<MachineOperand>(MI.debug_operands().begin(),
853                                         MI.debug_operands().end()),
854                IsIndirect, IsList, *Expr);
855   else {
856     MachineOperand MO = MachineOperand::CreateReg(0U, false);
857     MO.setIsDebug();
858     // We should still pass a list the same size as MI.debug_operands() even if
859     // all MOs are undef, so that DbgVariableValue can correctly adjust the
860     // expression while removing the duplicated undefs.
861     SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
862     UV->addDef(Idx, UndefMOs, false, IsList, *Expr);
863   }
864   return true;
865 }
866 
867 bool LDVImpl::handleDebugInstrRef(MachineInstr &MI, SlotIndex Idx) {
868   assert(MI.isDebugRef());
869   unsigned InstrNum = MI.getOperand(0).getImm();
870   unsigned OperandNum = MI.getOperand(1).getImm();
871   auto *Var = MI.getDebugVariable();
872   auto *Expr = MI.getDebugExpression();
873   auto &DL = MI.getDebugLoc();
874   StashedInstrRef Stashed =
875       std::make_tuple(InstrNum, OperandNum, Var, Expr, DL);
876   StashedInstrReferences[Idx].push_back(Stashed);
877   return true;
878 }
879 
880 bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
881   // DBG_LABEL label
882   if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
883     LLVM_DEBUG(dbgs() << "Can't handle " << MI);
884     return false;
885   }
886 
887   // Get or create the UserLabel for label here.
888   const DILabel *Label = MI.getDebugLabel();
889   const DebugLoc &DL = MI.getDebugLoc();
890   bool Found = false;
891   for (auto const &L : userLabels) {
892     if (L->matches(Label, DL->getInlinedAt(), Idx)) {
893       Found = true;
894       break;
895     }
896   }
897   if (!Found)
898     userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
899 
900   return true;
901 }
902 
903 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
904   bool Changed = false;
905   for (MachineBasicBlock &MBB : mf) {
906     for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
907          MBBI != MBBE;) {
908       // Use the first debug instruction in the sequence to get a SlotIndex
909       // for following consecutive debug instructions.
910       if (!MBBI->isDebugOrPseudoInstr()) {
911         ++MBBI;
912         continue;
913       }
914       // Debug instructions has no slot index. Use the previous
915       // non-debug instruction's SlotIndex as its SlotIndex.
916       SlotIndex Idx =
917           MBBI == MBB.begin()
918               ? LIS->getMBBStartIdx(&MBB)
919               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
920       // Handle consecutive debug instructions with the same slot index.
921       do {
922         // Only handle DBG_VALUE in handleDebugValue(). Skip all other
923         // kinds of debug instructions.
924         if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
925             (MBBI->isDebugRef() && handleDebugInstrRef(*MBBI, Idx)) ||
926             (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
927           MBBI = MBB.erase(MBBI);
928           Changed = true;
929         } else
930           ++MBBI;
931       } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
932     }
933   }
934   return Changed;
935 }
936 
937 void UserValue::extendDef(
938     SlotIndex Idx, DbgVariableValue DbgValue,
939     SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
940         &LiveIntervalInfo,
941     Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
942     LiveIntervals &LIS) {
943   SlotIndex Start = Idx;
944   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
945   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
946   LocMap::iterator I = locInts.find(Start);
947 
948   // Limit to the intersection of the VNIs' live ranges.
949   for (auto &LII : LiveIntervalInfo) {
950     LiveRange *LR = LII.second.first;
951     assert(LR && LII.second.second && "Missing range info for Idx.");
952     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
953     assert(Segment && Segment->valno == LII.second.second &&
954            "Invalid VNInfo for Idx given?");
955     if (Segment->end < Stop) {
956       Stop = Segment->end;
957       Kills = {Stop, {LII.first}};
958     } else if (Segment->end == Stop && Kills.hasValue()) {
959       // If multiple locations end at the same place, track all of them in
960       // Kills.
961       Kills->second.push_back(LII.first);
962     }
963   }
964 
965   // There could already be a short def at Start.
966   if (I.valid() && I.start() <= Start) {
967     // Stop when meeting a different location or an already extended interval.
968     Start = Start.getNextSlot();
969     if (I.value() != DbgValue || I.stop() != Start) {
970       // Clear `Kills`, as we have a new def available.
971       Kills = None;
972       return;
973     }
974     // This is a one-slot placeholder. Just skip it.
975     ++I;
976   }
977 
978   // Limited by the next def.
979   if (I.valid() && I.start() < Stop) {
980     Stop = I.start();
981     // Clear `Kills`, as we have a new def available.
982     Kills = None;
983   }
984 
985   if (Start < Stop) {
986     DbgVariableValue ExtDbgValue(DbgValue);
987     I.insert(Start, Stop, std::move(ExtDbgValue));
988   }
989 }
990 
991 void UserValue::addDefsFromCopies(
992     DbgVariableValue DbgValue,
993     SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
994     SlotIndex KilledAt,
995     SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
996     MachineRegisterInfo &MRI, LiveIntervals &LIS) {
997   // Don't track copies from physregs, there are too many uses.
998   if (any_of(LocIntervals, [](auto LocI) {
999         return !Register::isVirtualRegister(LocI.second->reg());
1000       }))
1001     return;
1002 
1003   // Collect all the (vreg, valno) pairs that are copies of LI.
1004   SmallDenseMap<unsigned,
1005                 SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>>
1006       CopyValues;
1007   for (auto &LocInterval : LocIntervals) {
1008     unsigned LocNo = LocInterval.first;
1009     LiveInterval *LI = LocInterval.second;
1010     for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) {
1011       MachineInstr *MI = MO.getParent();
1012       // Copies of the full value.
1013       if (MO.getSubReg() || !MI->isCopy())
1014         continue;
1015       Register DstReg = MI->getOperand(0).getReg();
1016 
1017       // Don't follow copies to physregs. These are usually setting up call
1018       // arguments, and the argument registers are always call clobbered. We are
1019       // better off in the source register which could be a callee-saved
1020       // register, or it could be spilled.
1021       if (!Register::isVirtualRegister(DstReg))
1022         continue;
1023 
1024       // Is the value extended to reach this copy? If not, another def may be
1025       // blocking it, or we are looking at a wrong value of LI.
1026       SlotIndex Idx = LIS.getInstructionIndex(*MI);
1027       LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
1028       if (!I.valid() || I.value() != DbgValue)
1029         continue;
1030 
1031       if (!LIS.hasInterval(DstReg))
1032         continue;
1033       LiveInterval *DstLI = &LIS.getInterval(DstReg);
1034       const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
1035       assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
1036       CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI));
1037     }
1038   }
1039 
1040   if (CopyValues.empty())
1041     return;
1042 
1043 #if !defined(NDEBUG)
1044   for (auto &LocInterval : LocIntervals)
1045     LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
1046                       << " copies of " << *LocInterval.second << '\n');
1047 #endif
1048 
1049   // Try to add defs of the copied values for the kill point. Check that there
1050   // isn't already a def at Idx.
1051   LocMap::iterator I = locInts.find(KilledAt);
1052   if (I.valid() && I.start() <= KilledAt)
1053     return;
1054   DbgVariableValue NewValue(DbgValue);
1055   for (auto &LocInterval : LocIntervals) {
1056     unsigned LocNo = LocInterval.first;
1057     bool FoundCopy = false;
1058     for (auto &LIAndVNI : CopyValues[LocNo]) {
1059       LiveInterval *DstLI = LIAndVNI.first;
1060       const VNInfo *DstVNI = LIAndVNI.second;
1061       if (DstLI->getVNInfoAt(KilledAt) != DstVNI)
1062         continue;
1063       LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
1064                         << DstVNI->id << " in " << *DstLI << '\n');
1065       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
1066       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
1067       unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0));
1068       NewValue = NewValue.changeLocNo(LocNo, NewLocNo);
1069       FoundCopy = true;
1070       break;
1071     }
1072     // If there are any killed locations we can't find a copy for, we can't
1073     // extend the variable value.
1074     if (!FoundCopy)
1075       return;
1076   }
1077   I.insert(KilledAt, KilledAt.getNextSlot(), NewValue);
1078   NewDefs.push_back(std::make_pair(KilledAt, NewValue));
1079 }
1080 
1081 void UserValue::computeIntervals(MachineRegisterInfo &MRI,
1082                                  const TargetRegisterInfo &TRI,
1083                                  LiveIntervals &LIS, LexicalScopes &LS) {
1084   SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
1085 
1086   // Collect all defs to be extended (Skipping undefs).
1087   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1088     if (!I.value().isUndef())
1089       Defs.push_back(std::make_pair(I.start(), I.value()));
1090 
1091   // Extend all defs, and possibly add new ones along the way.
1092   for (unsigned i = 0; i != Defs.size(); ++i) {
1093     SlotIndex Idx = Defs[i].first;
1094     DbgVariableValue DbgValue = Defs[i].second;
1095     SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
1096     SmallVector<const VNInfo *, 4> VNIs;
1097     bool ShouldExtendDef = false;
1098     for (unsigned LocNo : DbgValue.loc_nos()) {
1099       const MachineOperand &LocMO = locations[LocNo];
1100       if (!LocMO.isReg() || !Register::isVirtualRegister(LocMO.getReg())) {
1101         ShouldExtendDef |= !LocMO.isReg();
1102         continue;
1103       }
1104       ShouldExtendDef = true;
1105       LiveInterval *LI = nullptr;
1106       const VNInfo *VNI = nullptr;
1107       if (LIS.hasInterval(LocMO.getReg())) {
1108         LI = &LIS.getInterval(LocMO.getReg());
1109         VNI = LI->getVNInfoAt(Idx);
1110       }
1111       if (LI && VNI)
1112         LIs[LocNo] = {LI, VNI};
1113     }
1114     if (ShouldExtendDef) {
1115       Optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
1116       extendDef(Idx, DbgValue, LIs, Kills, LIS);
1117 
1118       if (Kills) {
1119         SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals;
1120         bool AnySubreg = false;
1121         for (unsigned LocNo : Kills->second) {
1122           const MachineOperand &LocMO = this->locations[LocNo];
1123           if (LocMO.getSubReg()) {
1124             AnySubreg = true;
1125             break;
1126           }
1127           LiveInterval *LI = &LIS.getInterval(LocMO.getReg());
1128           KilledLocIntervals.push_back({LocNo, LI});
1129         }
1130 
1131         // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
1132         // if the original location for example is %vreg0:sub_hi, and we find a
1133         // full register copy in addDefsFromCopies (at the moment it only
1134         // handles full register copies), then we must add the sub1 sub-register
1135         // index to the new location. However, that is only possible if the new
1136         // virtual register is of the same regclass (or if there is an
1137         // equivalent sub-register in that regclass). For now, simply skip
1138         // handling copies if a sub-register is involved.
1139         if (!AnySubreg)
1140           addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs,
1141                             MRI, LIS);
1142       }
1143     }
1144 
1145     // For physregs, we only mark the start slot idx. DwarfDebug will see it
1146     // as if the DBG_VALUE is valid up until the end of the basic block, or
1147     // the next def of the physical register. So we do not need to extend the
1148     // range. It might actually happen that the DBG_VALUE is the last use of
1149     // the physical register (e.g. if this is an unused input argument to a
1150     // function).
1151   }
1152 
1153   // The computed intervals may extend beyond the range of the debug
1154   // location's lexical scope. In this case, splitting of an interval
1155   // can result in an interval outside of the scope being created,
1156   // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
1157   // this, trim the intervals to the lexical scope in the case of inlined
1158   // variables, since heavy inlining may cause production of dramatically big
1159   // number of DBG_VALUEs to be generated.
1160   if (!dl.getInlinedAt())
1161     return;
1162 
1163   LexicalScope *Scope = LS.findLexicalScope(dl);
1164   if (!Scope)
1165     return;
1166 
1167   SlotIndex PrevEnd;
1168   LocMap::iterator I = locInts.begin();
1169 
1170   // Iterate over the lexical scope ranges. Each time round the loop
1171   // we check the intervals for overlap with the end of the previous
1172   // range and the start of the next. The first range is handled as
1173   // a special case where there is no PrevEnd.
1174   for (const InsnRange &Range : Scope->getRanges()) {
1175     SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
1176     SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
1177 
1178     // Variable locations at the first instruction of a block should be
1179     // based on the block's SlotIndex, not the first instruction's index.
1180     if (Range.first == Range.first->getParent()->begin())
1181       RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
1182 
1183     // At the start of each iteration I has been advanced so that
1184     // I.stop() >= PrevEnd. Check for overlap.
1185     if (PrevEnd && I.start() < PrevEnd) {
1186       SlotIndex IStop = I.stop();
1187       DbgVariableValue DbgValue = I.value();
1188 
1189       // Stop overlaps previous end - trim the end of the interval to
1190       // the scope range.
1191       I.setStopUnchecked(PrevEnd);
1192       ++I;
1193 
1194       // If the interval also overlaps the start of the "next" (i.e.
1195       // current) range create a new interval for the remainder (which
1196       // may be further trimmed).
1197       if (RStart < IStop)
1198         I.insert(RStart, IStop, DbgValue);
1199     }
1200 
1201     // Advance I so that I.stop() >= RStart, and check for overlap.
1202     I.advanceTo(RStart);
1203     if (!I.valid())
1204       return;
1205 
1206     if (I.start() < RStart) {
1207       // Interval start overlaps range - trim to the scope range.
1208       I.setStartUnchecked(RStart);
1209       // Remember that this interval was trimmed.
1210       trimmedDefs.insert(RStart);
1211     }
1212 
1213     // The end of a lexical scope range is the last instruction in the
1214     // range. To convert to an interval we need the index of the
1215     // instruction after it.
1216     REnd = REnd.getNextIndex();
1217 
1218     // Advance I to first interval outside current range.
1219     I.advanceTo(REnd);
1220     if (!I.valid())
1221       return;
1222 
1223     PrevEnd = REnd;
1224   }
1225 
1226   // Check for overlap with end of final range.
1227   if (PrevEnd && I.start() < PrevEnd)
1228     I.setStopUnchecked(PrevEnd);
1229 }
1230 
1231 void LDVImpl::computeIntervals() {
1232   LexicalScopes LS;
1233   LS.initialize(*MF);
1234 
1235   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
1236     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
1237     userValues[i]->mapVirtRegs(this);
1238   }
1239 }
1240 
1241 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
1242   clear();
1243   MF = &mf;
1244   LIS = &pass.getAnalysis<LiveIntervals>();
1245   TRI = mf.getSubtarget().getRegisterInfo();
1246   LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
1247                     << mf.getName() << " **********\n");
1248 
1249   bool Changed = collectDebugValues(mf);
1250   computeIntervals();
1251   LLVM_DEBUG(print(dbgs()));
1252 
1253   // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive
1254   // VRegs too, for when we're notified of a range split.
1255   SlotIndexes *Slots = LIS->getSlotIndexes();
1256   for (const auto &PHIIt : MF->DebugPHIPositions) {
1257     const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
1258     MachineBasicBlock *MBB = Position.MBB;
1259     Register Reg = Position.Reg;
1260     unsigned SubReg = Position.SubReg;
1261     SlotIndex SI = Slots->getMBBStartIdx(MBB);
1262     PHIValPos VP = {SI, Reg, SubReg};
1263     PHIValToPos.insert(std::make_pair(PHIIt.first, VP));
1264     RegToPHIIdx[Reg].push_back(PHIIt.first);
1265   }
1266 
1267   ModifiedMF = Changed;
1268   return Changed;
1269 }
1270 
1271 static void removeDebugInstrs(MachineFunction &mf) {
1272   for (MachineBasicBlock &MBB : mf) {
1273     for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
1274       if (!MBBI->isDebugInstr()) {
1275         ++MBBI;
1276         continue;
1277       }
1278       MBBI = MBB.erase(MBBI);
1279     }
1280   }
1281 }
1282 
1283 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
1284   if (!EnableLDV)
1285     return false;
1286   if (!mf.getFunction().getSubprogram()) {
1287     removeDebugInstrs(mf);
1288     return false;
1289   }
1290   if (!pImpl)
1291     pImpl = new LDVImpl(this);
1292   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
1293 }
1294 
1295 void LiveDebugVariables::releaseMemory() {
1296   if (pImpl)
1297     static_cast<LDVImpl*>(pImpl)->clear();
1298 }
1299 
1300 LiveDebugVariables::~LiveDebugVariables() {
1301   if (pImpl)
1302     delete static_cast<LDVImpl*>(pImpl);
1303 }
1304 
1305 //===----------------------------------------------------------------------===//
1306 //                           Live Range Splitting
1307 //===----------------------------------------------------------------------===//
1308 
1309 bool
1310 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
1311                          LiveIntervals& LIS) {
1312   LLVM_DEBUG({
1313     dbgs() << "Splitting Loc" << OldLocNo << '\t';
1314     print(dbgs(), nullptr);
1315   });
1316   bool DidChange = false;
1317   LocMap::iterator LocMapI;
1318   LocMapI.setMap(locInts);
1319   for (unsigned i = 0; i != NewRegs.size(); ++i) {
1320     LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
1321     if (LI->empty())
1322       continue;
1323 
1324     // Don't allocate the new LocNo until it is needed.
1325     unsigned NewLocNo = UndefLocNo;
1326 
1327     // Iterate over the overlaps between locInts and LI.
1328     LocMapI.find(LI->beginIndex());
1329     if (!LocMapI.valid())
1330       continue;
1331     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
1332     LiveInterval::iterator LIE = LI->end();
1333     while (LocMapI.valid() && LII != LIE) {
1334       // At this point, we know that LocMapI.stop() > LII->start.
1335       LII = LI->advanceTo(LII, LocMapI.start());
1336       if (LII == LIE)
1337         break;
1338 
1339       // Now LII->end > LocMapI.start(). Do we have an overlap?
1340       if (LocMapI.value().containsLocNo(OldLocNo) &&
1341           LII->start < LocMapI.stop()) {
1342         // Overlapping correct location. Allocate NewLocNo now.
1343         if (NewLocNo == UndefLocNo) {
1344           MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false);
1345           MO.setSubReg(locations[OldLocNo].getSubReg());
1346           NewLocNo = getLocationNo(MO);
1347           DidChange = true;
1348         }
1349 
1350         SlotIndex LStart = LocMapI.start();
1351         SlotIndex LStop = LocMapI.stop();
1352         DbgVariableValue OldDbgValue = LocMapI.value();
1353 
1354         // Trim LocMapI down to the LII overlap.
1355         if (LStart < LII->start)
1356           LocMapI.setStartUnchecked(LII->start);
1357         if (LStop > LII->end)
1358           LocMapI.setStopUnchecked(LII->end);
1359 
1360         // Change the value in the overlap. This may trigger coalescing.
1361         LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
1362 
1363         // Re-insert any removed OldDbgValue ranges.
1364         if (LStart < LocMapI.start()) {
1365           LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
1366           ++LocMapI;
1367           assert(LocMapI.valid() && "Unexpected coalescing");
1368         }
1369         if (LStop > LocMapI.stop()) {
1370           ++LocMapI;
1371           LocMapI.insert(LII->end, LStop, OldDbgValue);
1372           --LocMapI;
1373         }
1374       }
1375 
1376       // Advance to the next overlap.
1377       if (LII->end < LocMapI.stop()) {
1378         if (++LII == LIE)
1379           break;
1380         LocMapI.advanceTo(LII->start);
1381       } else {
1382         ++LocMapI;
1383         if (!LocMapI.valid())
1384           break;
1385         LII = LI->advanceTo(LII, LocMapI.start());
1386       }
1387     }
1388   }
1389 
1390   // Finally, remove OldLocNo unless it is still used by some interval in the
1391   // locInts map. One case when OldLocNo still is in use is when the register
1392   // has been spilled. In such situations the spilled register is kept as a
1393   // location until rewriteLocations is called (VirtRegMap is mapping the old
1394   // register to the spill slot). So for a while we can have locations that map
1395   // to virtual registers that have been removed from both the MachineFunction
1396   // and from LiveIntervals.
1397   //
1398   // We may also just be using the location for a value with a different
1399   // expression.
1400   removeLocationIfUnused(OldLocNo);
1401 
1402   LLVM_DEBUG({
1403     dbgs() << "Split result: \t";
1404     print(dbgs(), nullptr);
1405   });
1406   return DidChange;
1407 }
1408 
1409 bool
1410 UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
1411                          LiveIntervals &LIS) {
1412   bool DidChange = false;
1413   // Split locations referring to OldReg. Iterate backwards so splitLocation can
1414   // safely erase unused locations.
1415   for (unsigned i = locations.size(); i ; --i) {
1416     unsigned LocNo = i-1;
1417     const MachineOperand *Loc = &locations[LocNo];
1418     if (!Loc->isReg() || Loc->getReg() != OldReg)
1419       continue;
1420     DidChange |= splitLocation(LocNo, NewRegs, LIS);
1421   }
1422   return DidChange;
1423 }
1424 
1425 void LDVImpl::splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1426   auto RegIt = RegToPHIIdx.find(OldReg);
1427   if (RegIt == RegToPHIIdx.end())
1428     return;
1429 
1430   std::vector<std::pair<Register, unsigned>> NewRegIdxes;
1431   // Iterate over all the debug instruction numbers affected by this split.
1432   for (unsigned InstrID : RegIt->second) {
1433     auto PHIIt = PHIValToPos.find(InstrID);
1434     assert(PHIIt != PHIValToPos.end());
1435     const SlotIndex &Slot = PHIIt->second.SI;
1436     assert(OldReg == PHIIt->second.Reg);
1437 
1438     // Find the new register that covers this position.
1439     for (auto NewReg : NewRegs) {
1440       const LiveInterval &LI = LIS->getInterval(NewReg);
1441       auto LII = LI.find(Slot);
1442       if (LII != LI.end() && LII->start <= Slot) {
1443         // This new register covers this PHI position, record this for indexing.
1444         NewRegIdxes.push_back(std::make_pair(NewReg, InstrID));
1445         // Record that this value lives in a different VReg now.
1446         PHIIt->second.Reg = NewReg;
1447         break;
1448       }
1449     }
1450 
1451     // If we do not find a new register covering this PHI, then register
1452     // allocation has dropped its location, for example because it's not live.
1453     // The old VReg will not be mapped to a physreg, and the instruction
1454     // number will have been optimized out.
1455   }
1456 
1457   // Re-create register index using the new register numbers.
1458   RegToPHIIdx.erase(RegIt);
1459   for (auto &RegAndInstr : NewRegIdxes)
1460     RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second);
1461 }
1462 
1463 void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1464   // Consider whether this split range affects any PHI locations.
1465   splitPHIRegister(OldReg, NewRegs);
1466 
1467   // Check whether any intervals mapped by a DBG_VALUE were split and need
1468   // updating.
1469   bool DidChange = false;
1470   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
1471     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
1472 
1473   if (!DidChange)
1474     return;
1475 
1476   // Map all of the new virtual registers.
1477   UserValue *UV = lookupVirtReg(OldReg);
1478   for (unsigned i = 0; i != NewRegs.size(); ++i)
1479     mapVirtReg(NewRegs[i], UV);
1480 }
1481 
1482 void LiveDebugVariables::
1483 splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
1484   if (pImpl)
1485     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
1486 }
1487 
1488 void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1489                                  const TargetInstrInfo &TII,
1490                                  const TargetRegisterInfo &TRI,
1491                                  SpillOffsetMap &SpillOffsets) {
1492   // Build a set of new locations with new numbers so we can coalesce our
1493   // IntervalMap if two vreg intervals collapse to the same physical location.
1494   // Use MapVector instead of SetVector because MapVector::insert returns the
1495   // position of the previously or newly inserted element. The boolean value
1496   // tracks if the location was produced by a spill.
1497   // FIXME: This will be problematic if we ever support direct and indirect
1498   // frame index locations, i.e. expressing both variables in memory and
1499   // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1500   MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
1501   SmallVector<unsigned, 4> LocNoMap(locations.size());
1502   for (unsigned I = 0, E = locations.size(); I != E; ++I) {
1503     bool Spilled = false;
1504     unsigned SpillOffset = 0;
1505     MachineOperand Loc = locations[I];
1506     // Only virtual registers are rewritten.
1507     if (Loc.isReg() && Loc.getReg() &&
1508         Register::isVirtualRegister(Loc.getReg())) {
1509       Register VirtReg = Loc.getReg();
1510       if (VRM.isAssignedReg(VirtReg) &&
1511           Register::isPhysicalRegister(VRM.getPhys(VirtReg))) {
1512         // This can create a %noreg operand in rare cases when the sub-register
1513         // index is no longer available. That means the user value is in a
1514         // non-existent sub-register, and %noreg is exactly what we want.
1515         Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1516       } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1517         // Retrieve the stack slot offset.
1518         unsigned SpillSize;
1519         const MachineRegisterInfo &MRI = MF.getRegInfo();
1520         const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
1521         bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
1522                                              SpillOffset, MF);
1523 
1524         // FIXME: Invalidate the location if the offset couldn't be calculated.
1525         (void)Success;
1526 
1527         Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
1528         Spilled = true;
1529       } else {
1530         Loc.setReg(0);
1531         Loc.setSubReg(0);
1532       }
1533     }
1534 
1535     // Insert this location if it doesn't already exist and record a mapping
1536     // from the old number to the new number.
1537     auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
1538     unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1539     LocNoMap[I] = NewLocNo;
1540   }
1541 
1542   // Rewrite the locations and record the stack slot offsets for spills.
1543   locations.clear();
1544   SpillOffsets.clear();
1545   for (auto &Pair : NewLocations) {
1546     bool Spilled;
1547     unsigned SpillOffset;
1548     std::tie(Spilled, SpillOffset) = Pair.second;
1549     locations.push_back(Pair.first);
1550     if (Spilled) {
1551       unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1552       SpillOffsets[NewLocNo] = SpillOffset;
1553     }
1554   }
1555 
1556   // Update the interval map, but only coalesce left, since intervals to the
1557   // right use the old location numbers. This should merge two contiguous
1558   // DBG_VALUE intervals with different vregs that were allocated to the same
1559   // physical register.
1560   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1561     I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
1562     I.setStart(I.start());
1563   }
1564 }
1565 
1566 /// Find an iterator for inserting a DBG_VALUE instruction.
1567 static MachineBasicBlock::iterator
1568 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS,
1569                    BlockSkipInstsMap &BBSkipInstsMap) {
1570   SlotIndex Start = LIS.getMBBStartIdx(MBB);
1571   Idx = Idx.getBaseIndex();
1572 
1573   // Try to find an insert location by going backwards from Idx.
1574   MachineInstr *MI;
1575   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1576     // We've reached the beginning of MBB.
1577     if (Idx == Start) {
1578       // Retrieve the last PHI/Label/Debug location found when calling
1579       // SkipPHIsLabelsAndDebug last time. Start searching from there.
1580       //
1581       // Note the iterator kept in BBSkipInstsMap is one step back based
1582       // on the iterator returned by SkipPHIsLabelsAndDebug last time.
1583       // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
1584       // BBSkipInstsMap won't save it. This is to consider the case that
1585       // new instructions may be inserted at the beginning of MBB after
1586       // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
1587       // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
1588       // are inserted at the beginning of the MBB, the iterator in
1589       // BBSkipInstsMap won't point to the beginning of the MBB anymore.
1590       // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
1591       // newly added instructions and that is unwanted.
1592       MachineBasicBlock::iterator BeginIt;
1593       auto MapIt = BBSkipInstsMap.find(MBB);
1594       if (MapIt == BBSkipInstsMap.end())
1595         BeginIt = MBB->begin();
1596       else
1597         BeginIt = std::next(MapIt->second);
1598       auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt);
1599       if (I != BeginIt)
1600         BBSkipInstsMap[MBB] = std::prev(I);
1601       return I;
1602     }
1603     Idx = Idx.getPrevIndex();
1604   }
1605 
1606   // Don't insert anything after the first terminator, though.
1607   return MI->isTerminator() ? MBB->getFirstTerminator() :
1608                               std::next(MachineBasicBlock::iterator(MI));
1609 }
1610 
1611 /// Find an iterator for inserting the next DBG_VALUE instruction
1612 /// (or end if no more insert locations found).
1613 static MachineBasicBlock::iterator
1614 findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I,
1615                        SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
1616                        LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
1617   SmallVector<Register, 4> Regs;
1618   for (const MachineOperand &LocMO : LocMOs)
1619     if (LocMO.isReg())
1620       Regs.push_back(LocMO.getReg());
1621   if (Regs.empty())
1622     return MBB->instr_end();
1623 
1624   // Find the next instruction in the MBB that define the register Reg.
1625   while (I != MBB->end() && !I->isTerminator()) {
1626     if (!LIS.isNotInMIMap(*I) &&
1627         SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
1628       break;
1629     if (any_of(Regs, [&I, &TRI](Register &Reg) {
1630           return I->definesRegister(Reg, &TRI);
1631         }))
1632       // The insert location is directly after the instruction/bundle.
1633       return std::next(I);
1634     ++I;
1635   }
1636   return MBB->end();
1637 }
1638 
1639 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1640                                  SlotIndex StopIdx, DbgVariableValue DbgValue,
1641                                  ArrayRef<bool> LocSpills,
1642                                  ArrayRef<unsigned> SpillOffsets,
1643                                  LiveIntervals &LIS, const TargetInstrInfo &TII,
1644                                  const TargetRegisterInfo &TRI,
1645                                  BlockSkipInstsMap &BBSkipInstsMap) {
1646   SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1647   // Only search within the current MBB.
1648   StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1649   MachineBasicBlock::iterator I =
1650       findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap);
1651   // Undef values don't exist in locations so create new "noreg" register MOs
1652   // for them. See getLocationNo().
1653   SmallVector<MachineOperand, 8> MOs;
1654   if (DbgValue.isUndef()) {
1655     MOs.assign(DbgValue.loc_nos().size(),
1656                MachineOperand::CreateReg(
1657                    /* Reg */ 0, /* isDef */ false, /* isImp */ false,
1658                    /* isKill */ false, /* isDead */ false,
1659                    /* isUndef */ false, /* isEarlyClobber */ false,
1660                    /* SubReg */ 0, /* isDebug */ true));
1661   } else {
1662     for (unsigned LocNo : DbgValue.loc_nos())
1663       MOs.push_back(locations[LocNo]);
1664   }
1665 
1666   ++NumInsertedDebugValues;
1667 
1668   assert(cast<DILocalVariable>(Variable)
1669              ->isValidLocationForIntrinsic(getDebugLoc()) &&
1670          "Expected inlined-at fields to agree");
1671 
1672   // If the location was spilled, the new DBG_VALUE will be indirect. If the
1673   // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1674   // that the original virtual register was a pointer. Also, add the stack slot
1675   // offset for the spilled register to the expression.
1676   const DIExpression *Expr = DbgValue.getExpression();
1677   bool IsIndirect = DbgValue.getWasIndirect();
1678   bool IsList = DbgValue.getWasList();
1679   for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
1680     if (LocSpills[I]) {
1681       if (!IsList) {
1682         uint8_t DIExprFlags = DIExpression::ApplyOffset;
1683         if (IsIndirect)
1684           DIExprFlags |= DIExpression::DerefAfter;
1685         Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]);
1686         IsIndirect = true;
1687       } else {
1688         SmallVector<uint64_t, 4> Ops;
1689         DIExpression::appendOffset(Ops, SpillOffsets[I]);
1690         Ops.push_back(dwarf::DW_OP_deref);
1691         Expr = DIExpression::appendOpsToArg(Expr, Ops, I);
1692       }
1693     }
1694 
1695     assert((!LocSpills[I] || MOs[I].isFI()) &&
1696            "a spilled location must be a frame index");
1697   }
1698 
1699   unsigned DbgValueOpcode =
1700       IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
1701   do {
1702     BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs,
1703             Variable, Expr);
1704 
1705     // Continue and insert DBG_VALUES after every redefinition of a register
1706     // associated with the debug value within the range
1707     I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI);
1708   } while (I != MBB->end());
1709 }
1710 
1711 void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1712                                  LiveIntervals &LIS, const TargetInstrInfo &TII,
1713                                  BlockSkipInstsMap &BBSkipInstsMap) {
1714   MachineBasicBlock::iterator I =
1715       findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
1716   ++NumInsertedDebugLabels;
1717   BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
1718       .addMetadata(Label);
1719 }
1720 
1721 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1722                                 const TargetInstrInfo &TII,
1723                                 const TargetRegisterInfo &TRI,
1724                                 const SpillOffsetMap &SpillOffsets,
1725                                 BlockSkipInstsMap &BBSkipInstsMap) {
1726   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1727 
1728   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1729     SlotIndex Start = I.start();
1730     SlotIndex Stop = I.stop();
1731     DbgVariableValue DbgValue = I.value();
1732 
1733     SmallVector<bool> SpilledLocs;
1734     SmallVector<unsigned> LocSpillOffsets;
1735     for (unsigned LocNo : DbgValue.loc_nos()) {
1736       auto SpillIt =
1737           !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end();
1738       bool Spilled = SpillIt != SpillOffsets.end();
1739       SpilledLocs.push_back(Spilled);
1740       LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0);
1741     }
1742 
1743     // If the interval start was trimmed to the lexical scope insert the
1744     // DBG_VALUE at the previous index (otherwise it appears after the
1745     // first instruction in the range).
1746     if (trimmedDefs.count(Start))
1747       Start = Start.getPrevIndex();
1748 
1749     LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
1750                DbgValue.printLocNos(dbg));
1751     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1752     SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1753 
1754     LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1755     insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets,
1756                      LIS, TII, TRI, BBSkipInstsMap);
1757     // This interval may span multiple basic blocks.
1758     // Insert a DBG_VALUE into each one.
1759     while (Stop > MBBEnd) {
1760       // Move to the next block.
1761       Start = MBBEnd;
1762       if (++MBB == MFEnd)
1763         break;
1764       MBBEnd = LIS.getMBBEndIdx(&*MBB);
1765       LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1766       insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs,
1767                        LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
1768     }
1769     LLVM_DEBUG(dbgs() << '\n');
1770     if (MBB == MFEnd)
1771       break;
1772 
1773     ++I;
1774   }
1775 }
1776 
1777 void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
1778                                BlockSkipInstsMap &BBSkipInstsMap) {
1779   LLVM_DEBUG(dbgs() << "\t" << loc);
1780   MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
1781 
1782   LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1783   insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap);
1784 
1785   LLVM_DEBUG(dbgs() << '\n');
1786 }
1787 
1788 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1789   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1790   if (!MF)
1791     return;
1792 
1793   BlockSkipInstsMap BBSkipInstsMap;
1794   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1795   SpillOffsetMap SpillOffsets;
1796   for (auto &userValue : userValues) {
1797     LLVM_DEBUG(userValue->print(dbgs(), TRI));
1798     userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
1799     userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
1800                                BBSkipInstsMap);
1801   }
1802   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
1803   for (auto &userLabel : userLabels) {
1804     LLVM_DEBUG(userLabel->print(dbgs(), TRI));
1805     userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap);
1806   }
1807 
1808   LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
1809 
1810   auto Slots = LIS->getSlotIndexes();
1811   for (auto &It : PHIValToPos) {
1812     // For each ex-PHI, identify its physreg location or stack slot, and emit
1813     // a DBG_PHI for it.
1814     unsigned InstNum = It.first;
1815     auto Slot = It.second.SI;
1816     Register Reg = It.second.Reg;
1817     unsigned SubReg = It.second.SubReg;
1818 
1819     MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot);
1820     if (VRM->isAssignedReg(Reg) &&
1821         Register::isPhysicalRegister(VRM->getPhys(Reg))) {
1822       unsigned PhysReg = VRM->getPhys(Reg);
1823       if (SubReg != 0)
1824         PhysReg = TRI->getSubReg(PhysReg, SubReg);
1825 
1826       auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1827                              TII->get(TargetOpcode::DBG_PHI));
1828       Builder.addReg(PhysReg);
1829       Builder.addImm(InstNum);
1830     } else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) {
1831       const MachineRegisterInfo &MRI = MF->getRegInfo();
1832       const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
1833       unsigned SpillSize, SpillOffset;
1834 
1835       // Test whether this location is legal with the given subreg.
1836       bool Success =
1837           TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF);
1838 
1839       if (Success) {
1840         auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1841                                TII->get(TargetOpcode::DBG_PHI));
1842         Builder.addFrameIndex(VRM->getStackSlot(Reg));
1843         Builder.addImm(InstNum);
1844       }
1845     }
1846     // If there was no mapping for a value ID, it's optimized out. Create no
1847     // DBG_PHI, and any variables using this value will become optimized out.
1848   }
1849   MF->DebugPHIPositions.clear();
1850 
1851   LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
1852 
1853   // Re-insert any DBG_INSTR_REFs back in the position they were. Ordering
1854   // is preserved by vector.
1855   const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_INSTR_REF);
1856   for (auto &P : StashedInstrReferences) {
1857     const SlotIndex &Idx = P.first;
1858     auto *MBB = Slots->getMBBFromIndex(Idx);
1859     MachineBasicBlock::iterator insertPos =
1860         findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
1861     for (auto &Stashed : P.second) {
1862       auto MIB = BuildMI(*MF, std::get<4>(Stashed), RefII);
1863       MIB.addImm(std::get<0>(Stashed));
1864       MIB.addImm(std::get<1>(Stashed));
1865       MIB.addMetadata(std::get<2>(Stashed));
1866       MIB.addMetadata(std::get<3>(Stashed));
1867       MachineInstr *New = MIB;
1868       MBB->insert(insertPos, New);
1869     }
1870   }
1871 
1872   EmitDone = true;
1873   BBSkipInstsMap.clear();
1874 }
1875 
1876 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1877   if (pImpl)
1878     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1879 }
1880 
1881 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1882 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
1883   if (pImpl)
1884     static_cast<LDVImpl*>(pImpl)->print(dbgs());
1885 }
1886 #endif
1887