xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/LiveDebugValues/VarLocBasedImpl.cpp (revision 762dcf10641251c55dda2e6950fef8bb698027ad)
1  //===- VarLocBasedImpl.cpp - Tracking Debug Value MIs with VarLoc class----===//
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  /// \file VarLocBasedImpl.cpp
10  ///
11  /// LiveDebugValues is an optimistic "available expressions" dataflow
12  /// algorithm. The set of expressions is the set of machine locations
13  /// (registers, spill slots, constants) that a variable fragment might be
14  /// located, qualified by a DIExpression and indirect-ness flag, while each
15  /// variable is identified by a DebugVariable object. The availability of an
16  /// expression begins when a DBG_VALUE instruction specifies the location of a
17  /// DebugVariable, and continues until that location is clobbered or
18  /// re-specified by a different DBG_VALUE for the same DebugVariable.
19  ///
20  /// The output of LiveDebugValues is additional DBG_VALUE instructions,
21  /// placed to extend variable locations as far they're available. This file
22  /// and the VarLocBasedLDV class is an implementation that explicitly tracks
23  /// locations, using the VarLoc class.
24  ///
25  /// The canonical "available expressions" problem doesn't have expression
26  /// clobbering, instead when a variable is re-assigned, any expressions using
27  /// that variable get invalidated. LiveDebugValues can map onto "available
28  /// expressions" by having every register represented by a variable, which is
29  /// used in an expression that becomes available at a DBG_VALUE instruction.
30  /// When the register is clobbered, its variable is effectively reassigned, and
31  /// expressions computed from it become unavailable. A similar construct is
32  /// needed when a DebugVariable has its location re-specified, to invalidate
33  /// all other locations for that DebugVariable.
34  ///
35  /// Using the dataflow analysis to compute the available expressions, we create
36  /// a DBG_VALUE at the beginning of each block where the expression is
37  /// live-in. This propagates variable locations into every basic block where
38  /// the location can be determined, rather than only having DBG_VALUEs in blocks
39  /// where locations are specified due to an assignment or some optimization.
40  /// Movements of values between registers and spill slots are annotated with
41  /// DBG_VALUEs too to track variable values bewteen locations. All this allows
42  /// DbgEntityHistoryCalculator to focus on only the locations within individual
43  /// blocks, facilitating testing and improving modularity.
44  ///
45  /// We follow an optimisic dataflow approach, with this lattice:
46  ///
47  /// \verbatim
48  ///                    ┬ "Unknown"
49  ///                          |
50  ///                          v
51  ///                         True
52  ///                          |
53  ///                          v
54  ///                      ⊥ False
55  /// \endverbatim With "True" signifying that the expression is available (and
56  /// thus a DebugVariable's location is the corresponding register), while
57  /// "False" signifies that the expression is unavailable. "Unknown"s never
58  /// survive to the end of the analysis (see below).
59  ///
60  /// Formally, all DebugVariable locations that are live-out of a block are
61  /// initialized to \top.  A blocks live-in values take the meet of the lattice
62  /// value for every predecessors live-outs, except for the entry block, where
63  /// all live-ins are \bot. The usual dataflow propagation occurs: the transfer
64  /// function for a block assigns an expression for a DebugVariable to be "True"
65  /// if a DBG_VALUE in the block specifies it; "False" if the location is
66  /// clobbered; or the live-in value if it is unaffected by the block. We
67  /// visit each block in reverse post order until a fixedpoint is reached. The
68  /// solution produced is maximal.
69  ///
70  /// Intuitively, we start by assuming that every expression / variable location
71  /// is at least "True", and then propagate "False" from the entry block and any
72  /// clobbers until there are no more changes to make. This gives us an accurate
73  /// solution because all incorrect locations will have a "False" propagated into
74  /// them. It also gives us a solution that copes well with loops by assuming
75  /// that variable locations are live-through every loop, and then removing those
76  /// that are not through dataflow.
77  ///
78  /// Within LiveDebugValues: each variable location is represented by a
79  /// VarLoc object that identifies the source variable, the set of
80  /// machine-locations that currently describe it (a single location for
81  /// DBG_VALUE or multiple for DBG_VALUE_LIST), and the DBG_VALUE inst that
82  /// specifies the location. Each VarLoc is indexed in the (function-scope) \p
83  /// VarLocMap, giving each VarLoc a set of unique indexes, each of which
84  /// corresponds to one of the VarLoc's machine-locations and can be used to
85  /// lookup the VarLoc in the VarLocMap. Rather than operate directly on machine
86  /// locations, the dataflow analysis in this pass identifies locations by their
87  /// indices in the VarLocMap, meaning all the variable locations in a block can
88  /// be described by a sparse vector of VarLocMap indicies.
89  ///
90  /// All the storage for the dataflow analysis is local to the ExtendRanges
91  /// method and passed down to helper methods. "OutLocs" and "InLocs" record the
92  /// in and out lattice values for each block. "OpenRanges" maintains a list of
93  /// variable locations and, with the "process" method, evaluates the transfer
94  /// function of each block. "flushPendingLocs" installs debug value instructions
95  /// for each live-in location at the start of blocks, while "Transfers" records
96  /// transfers of values between machine-locations.
97  ///
98  /// We avoid explicitly representing the "Unknown" (\top) lattice value in the
99  /// implementation. Instead, unvisited blocks implicitly have all lattice
100  /// values set as "Unknown". After being visited, there will be path back to
101  /// the entry block where the lattice value is "False", and as the transfer
102  /// function cannot make new "Unknown" locations, there are no scenarios where
103  /// a block can have an "Unknown" location after being visited. Similarly, we
104  /// don't enumerate all possible variable locations before exploring the
105  /// function: when a new location is discovered, all blocks previously explored
106  /// were implicitly "False" but unrecorded, and become explicitly "False" when
107  /// a new VarLoc is created with its bit not set in predecessor InLocs or
108  /// OutLocs.
109  ///
110  //===----------------------------------------------------------------------===//
111  
112  #include "LiveDebugValues.h"
113  
114  #include "llvm/ADT/CoalescingBitVector.h"
115  #include "llvm/ADT/DenseMap.h"
116  #include "llvm/ADT/PostOrderIterator.h"
117  #include "llvm/ADT/SmallPtrSet.h"
118  #include "llvm/ADT/SmallSet.h"
119  #include "llvm/ADT/SmallVector.h"
120  #include "llvm/ADT/Statistic.h"
121  #include "llvm/ADT/UniqueVector.h"
122  #include "llvm/CodeGen/LexicalScopes.h"
123  #include "llvm/CodeGen/MachineBasicBlock.h"
124  #include "llvm/CodeGen/MachineFrameInfo.h"
125  #include "llvm/CodeGen/MachineFunction.h"
126  #include "llvm/CodeGen/MachineFunctionPass.h"
127  #include "llvm/CodeGen/MachineInstr.h"
128  #include "llvm/CodeGen/MachineInstrBuilder.h"
129  #include "llvm/CodeGen/MachineMemOperand.h"
130  #include "llvm/CodeGen/MachineOperand.h"
131  #include "llvm/CodeGen/PseudoSourceValue.h"
132  #include "llvm/CodeGen/RegisterScavenging.h"
133  #include "llvm/CodeGen/TargetFrameLowering.h"
134  #include "llvm/CodeGen/TargetInstrInfo.h"
135  #include "llvm/CodeGen/TargetLowering.h"
136  #include "llvm/CodeGen/TargetPassConfig.h"
137  #include "llvm/CodeGen/TargetRegisterInfo.h"
138  #include "llvm/CodeGen/TargetSubtargetInfo.h"
139  #include "llvm/Config/llvm-config.h"
140  #include "llvm/IR/DIBuilder.h"
141  #include "llvm/IR/DebugInfoMetadata.h"
142  #include "llvm/IR/DebugLoc.h"
143  #include "llvm/IR/Function.h"
144  #include "llvm/IR/Module.h"
145  #include "llvm/InitializePasses.h"
146  #include "llvm/MC/MCRegisterInfo.h"
147  #include "llvm/Pass.h"
148  #include "llvm/Support/Casting.h"
149  #include "llvm/Support/Compiler.h"
150  #include "llvm/Support/Debug.h"
151  #include "llvm/Support/TypeSize.h"
152  #include "llvm/Support/raw_ostream.h"
153  #include "llvm/Target/TargetMachine.h"
154  #include <algorithm>
155  #include <cassert>
156  #include <cstdint>
157  #include <functional>
158  #include <map>
159  #include <queue>
160  #include <tuple>
161  #include <utility>
162  #include <vector>
163  
164  using namespace llvm;
165  
166  #define DEBUG_TYPE "livedebugvalues"
167  
168  STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
169  
170  /// If \p Op is a stack or frame register return true, otherwise return false.
171  /// This is used to avoid basing the debug entry values on the registers, since
172  /// we do not support it at the moment.
173  static bool isRegOtherThanSPAndFP(const MachineOperand &Op,
174                                    const MachineInstr &MI,
175                                    const TargetRegisterInfo *TRI) {
176    if (!Op.isReg())
177      return false;
178  
179    const MachineFunction *MF = MI.getParent()->getParent();
180    const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
181    Register SP = TLI->getStackPointerRegisterToSaveRestore();
182    Register FP = TRI->getFrameRegister(*MF);
183    Register Reg = Op.getReg();
184  
185    return Reg && Reg != SP && Reg != FP;
186  }
187  
188  namespace {
189  
190  // Max out the number of statically allocated elements in DefinedRegsSet, as
191  // this prevents fallback to std::set::count() operations.
192  using DefinedRegsSet = SmallSet<Register, 32>;
193  
194  // The IDs in this set correspond to MachineLocs in VarLocs, as well as VarLocs
195  // that represent Entry Values; every VarLoc in the set will also appear
196  // exactly once at Location=0.
197  // As a result, each VarLoc may appear more than once in this "set", but each
198  // range corresponding to a Reg, SpillLoc, or EntryValue type will still be a
199  // "true" set (i.e. each VarLoc may appear only once), and the range Location=0
200  // is the set of all VarLocs.
201  using VarLocSet = CoalescingBitVector<uint64_t>;
202  
203  /// A type-checked pair of {Register Location (or 0), Index}, used to index
204  /// into a \ref VarLocMap. This can be efficiently converted to a 64-bit int
205  /// for insertion into a \ref VarLocSet, and efficiently converted back. The
206  /// type-checker helps ensure that the conversions aren't lossy.
207  ///
208  /// Why encode a location /into/ the VarLocMap index? This makes it possible
209  /// to find the open VarLocs killed by a register def very quickly. This is a
210  /// performance-critical operation for LiveDebugValues.
211  struct LocIndex {
212    using u32_location_t = uint32_t;
213    using u32_index_t = uint32_t;
214  
215    u32_location_t Location; // Physical registers live in the range [1;2^30) (see
216                             // \ref MCRegister), so we have plenty of range left
217                             // here to encode non-register locations.
218    u32_index_t Index;
219  
220    /// The location that has an entry for every VarLoc in the map.
221    static constexpr u32_location_t kUniversalLocation = 0;
222  
223    /// The first location that is reserved for VarLocs with locations of kind
224    /// RegisterKind.
225    static constexpr u32_location_t kFirstRegLocation = 1;
226  
227    /// The first location greater than 0 that is not reserved for VarLocs with
228    /// locations of kind RegisterKind.
229    static constexpr u32_location_t kFirstInvalidRegLocation = 1 << 30;
230  
231    /// A special location reserved for VarLocs with locations of kind
232    /// SpillLocKind.
233    static constexpr u32_location_t kSpillLocation = kFirstInvalidRegLocation;
234  
235    /// A special location reserved for VarLocs of kind EntryValueBackupKind and
236    /// EntryValueCopyBackupKind.
237    static constexpr u32_location_t kEntryValueBackupLocation =
238        kFirstInvalidRegLocation + 1;
239  
240    LocIndex(u32_location_t Location, u32_index_t Index)
241        : Location(Location), Index(Index) {}
242  
243    uint64_t getAsRawInteger() const {
244      return (static_cast<uint64_t>(Location) << 32) | Index;
245    }
246  
247    template<typename IntT> static LocIndex fromRawInteger(IntT ID) {
248      static_assert(std::is_unsigned<IntT>::value &&
249                        sizeof(ID) == sizeof(uint64_t),
250                    "Cannot convert raw integer to LocIndex");
251      return {static_cast<u32_location_t>(ID >> 32),
252              static_cast<u32_index_t>(ID)};
253    }
254  
255    /// Get the start of the interval reserved for VarLocs of kind RegisterKind
256    /// which reside in \p Reg. The end is at rawIndexForReg(Reg+1)-1.
257    static uint64_t rawIndexForReg(Register Reg) {
258      return LocIndex(Reg, 0).getAsRawInteger();
259    }
260  
261    /// Return a range covering all set indices in the interval reserved for
262    /// \p Location in \p Set.
263    static auto indexRangeForLocation(const VarLocSet &Set,
264                                      u32_location_t Location) {
265      uint64_t Start = LocIndex(Location, 0).getAsRawInteger();
266      uint64_t End = LocIndex(Location + 1, 0).getAsRawInteger();
267      return Set.half_open_range(Start, End);
268    }
269  };
270  
271  // Simple Set for storing all the VarLoc Indices at a Location bucket.
272  using VarLocsInRange = SmallSet<LocIndex::u32_index_t, 32>;
273  // Vector of all `LocIndex`s for a given VarLoc; the same Location should not
274  // appear in any two of these, as each VarLoc appears at most once in any
275  // Location bucket.
276  using LocIndices = SmallVector<LocIndex, 2>;
277  
278  class VarLocBasedLDV : public LDVImpl {
279  private:
280    const TargetRegisterInfo *TRI;
281    const TargetInstrInfo *TII;
282    const TargetFrameLowering *TFI;
283    TargetPassConfig *TPC;
284    BitVector CalleeSavedRegs;
285    LexicalScopes LS;
286    VarLocSet::Allocator Alloc;
287  
288    const MachineInstr *LastNonDbgMI;
289  
290    enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
291  
292    using FragmentInfo = DIExpression::FragmentInfo;
293    using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
294  
295    /// A pair of debug variable and value location.
296    struct VarLoc {
297      // The location at which a spilled variable resides. It consists of a
298      // register and an offset.
299      struct SpillLoc {
300        unsigned SpillBase;
301        StackOffset SpillOffset;
302        bool operator==(const SpillLoc &Other) const {
303          return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
304        }
305        bool operator!=(const SpillLoc &Other) const {
306          return !(*this == Other);
307        }
308      };
309  
310      /// Identity of the variable at this location.
311      const DebugVariable Var;
312  
313      /// The expression applied to this location.
314      const DIExpression *Expr;
315  
316      /// DBG_VALUE to clone var/expr information from if this location
317      /// is moved.
318      const MachineInstr &MI;
319  
320      enum class MachineLocKind {
321        InvalidKind = 0,
322        RegisterKind,
323        SpillLocKind,
324        ImmediateKind
325      };
326  
327      enum class EntryValueLocKind {
328        NonEntryValueKind = 0,
329        EntryValueKind,
330        EntryValueBackupKind,
331        EntryValueCopyBackupKind
332      } EVKind = EntryValueLocKind::NonEntryValueKind;
333  
334      /// The value location. Stored separately to avoid repeatedly
335      /// extracting it from MI.
336      union MachineLocValue {
337        uint64_t RegNo;
338        SpillLoc SpillLocation;
339        uint64_t Hash;
340        int64_t Immediate;
341        const ConstantFP *FPImm;
342        const ConstantInt *CImm;
343        MachineLocValue() : Hash(0) {}
344      };
345  
346      /// A single machine location; its Kind is either a register, spill
347      /// location, or immediate value.
348      /// If the VarLoc is not a NonEntryValueKind, then it will use only a
349      /// single MachineLoc of RegisterKind.
350      struct MachineLoc {
351        MachineLocKind Kind;
352        MachineLocValue Value;
353        bool operator==(const MachineLoc &Other) const {
354          if (Kind != Other.Kind)
355            return false;
356          switch (Kind) {
357          case MachineLocKind::SpillLocKind:
358            return Value.SpillLocation == Other.Value.SpillLocation;
359          case MachineLocKind::RegisterKind:
360          case MachineLocKind::ImmediateKind:
361            return Value.Hash == Other.Value.Hash;
362          default:
363            llvm_unreachable("Invalid kind");
364          }
365        }
366        bool operator<(const MachineLoc &Other) const {
367          switch (Kind) {
368          case MachineLocKind::SpillLocKind:
369            return std::make_tuple(
370                       Kind, Value.SpillLocation.SpillBase,
371                       Value.SpillLocation.SpillOffset.getFixed(),
372                       Value.SpillLocation.SpillOffset.getScalable()) <
373                   std::make_tuple(
374                       Other.Kind, Other.Value.SpillLocation.SpillBase,
375                       Other.Value.SpillLocation.SpillOffset.getFixed(),
376                       Other.Value.SpillLocation.SpillOffset.getScalable());
377          case MachineLocKind::RegisterKind:
378          case MachineLocKind::ImmediateKind:
379            return std::tie(Kind, Value.Hash) <
380                   std::tie(Other.Kind, Other.Value.Hash);
381          default:
382            llvm_unreachable("Invalid kind");
383          }
384        }
385      };
386  
387      /// The set of machine locations used to determine the variable's value, in
388      /// conjunction with Expr. Initially populated with MI's debug operands,
389      /// but may be transformed independently afterwards.
390      SmallVector<MachineLoc, 8> Locs;
391      /// Used to map the index of each location in Locs back to the index of its
392      /// original debug operand in MI. Used when multiple location operands are
393      /// coalesced and the original MI's operands need to be accessed while
394      /// emitting a debug value.
395      SmallVector<unsigned, 8> OrigLocMap;
396  
397      VarLoc(const MachineInstr &MI, LexicalScopes &LS)
398          : Var(MI.getDebugVariable(), MI.getDebugExpression(),
399                MI.getDebugLoc()->getInlinedAt()),
400            Expr(MI.getDebugExpression()), MI(MI) {
401        assert(MI.isDebugValue() && "not a DBG_VALUE");
402        assert((MI.isDebugValueList() || MI.getNumOperands() == 4) &&
403               "malformed DBG_VALUE");
404        for (const MachineOperand &Op : MI.debug_operands()) {
405          MachineLoc ML = GetLocForOp(Op);
406          auto It = find(Locs, ML);
407          if (It == Locs.end()) {
408            Locs.push_back(ML);
409            OrigLocMap.push_back(MI.getDebugOperandIndex(&Op));
410          } else {
411            // ML duplicates an element in Locs; replace references to Op
412            // with references to the duplicating element.
413            unsigned OpIdx = Locs.size();
414            unsigned DuplicatingIdx = std::distance(Locs.begin(), It);
415            Expr = DIExpression::replaceArg(Expr, OpIdx, DuplicatingIdx);
416          }
417        }
418  
419        // We create the debug entry values from the factory functions rather
420        // than from this ctor.
421        assert(EVKind != EntryValueLocKind::EntryValueKind &&
422               !isEntryBackupLoc());
423      }
424  
425      static MachineLoc GetLocForOp(const MachineOperand &Op) {
426        MachineLocKind Kind;
427        MachineLocValue Loc;
428        if (Op.isReg()) {
429          Kind = MachineLocKind::RegisterKind;
430          Loc.RegNo = Op.getReg();
431        } else if (Op.isImm()) {
432          Kind = MachineLocKind::ImmediateKind;
433          Loc.Immediate = Op.getImm();
434        } else if (Op.isFPImm()) {
435          Kind = MachineLocKind::ImmediateKind;
436          Loc.FPImm = Op.getFPImm();
437        } else if (Op.isCImm()) {
438          Kind = MachineLocKind::ImmediateKind;
439          Loc.CImm = Op.getCImm();
440        } else
441          llvm_unreachable("Invalid Op kind for MachineLoc.");
442        return {Kind, Loc};
443      }
444  
445      /// Take the variable and machine-location in DBG_VALUE MI, and build an
446      /// entry location using the given expression.
447      static VarLoc CreateEntryLoc(const MachineInstr &MI, LexicalScopes &LS,
448                                   const DIExpression *EntryExpr, Register Reg) {
449        VarLoc VL(MI, LS);
450        assert(VL.Locs.size() == 1 &&
451               VL.Locs[0].Kind == MachineLocKind::RegisterKind);
452        VL.EVKind = EntryValueLocKind::EntryValueKind;
453        VL.Expr = EntryExpr;
454        VL.Locs[0].Value.RegNo = Reg;
455        return VL;
456      }
457  
458      /// Take the variable and machine-location from the DBG_VALUE (from the
459      /// function entry), and build an entry value backup location. The backup
460      /// location will turn into the normal location if the backup is valid at
461      /// the time of the primary location clobbering.
462      static VarLoc CreateEntryBackupLoc(const MachineInstr &MI,
463                                         LexicalScopes &LS,
464                                         const DIExpression *EntryExpr) {
465        VarLoc VL(MI, LS);
466        assert(VL.Locs.size() == 1 &&
467               VL.Locs[0].Kind == MachineLocKind::RegisterKind);
468        VL.EVKind = EntryValueLocKind::EntryValueBackupKind;
469        VL.Expr = EntryExpr;
470        return VL;
471      }
472  
473      /// Take the variable and machine-location from the DBG_VALUE (from the
474      /// function entry), and build a copy of an entry value backup location by
475      /// setting the register location to NewReg.
476      static VarLoc CreateEntryCopyBackupLoc(const MachineInstr &MI,
477                                             LexicalScopes &LS,
478                                             const DIExpression *EntryExpr,
479                                             Register NewReg) {
480        VarLoc VL(MI, LS);
481        assert(VL.Locs.size() == 1 &&
482               VL.Locs[0].Kind == MachineLocKind::RegisterKind);
483        VL.EVKind = EntryValueLocKind::EntryValueCopyBackupKind;
484        VL.Expr = EntryExpr;
485        VL.Locs[0].Value.RegNo = NewReg;
486        return VL;
487      }
488  
489      /// Copy the register location in DBG_VALUE MI, updating the register to
490      /// be NewReg.
491      static VarLoc CreateCopyLoc(const VarLoc &OldVL, const MachineLoc &OldML,
492                                  Register NewReg) {
493        VarLoc VL = OldVL;
494        for (MachineLoc &ML : VL.Locs)
495          if (ML == OldML) {
496            ML.Kind = MachineLocKind::RegisterKind;
497            ML.Value.RegNo = NewReg;
498            return VL;
499          }
500        llvm_unreachable("Should have found OldML in new VarLoc.");
501      }
502  
503      /// Take the variable described by DBG_VALUE* MI, and create a VarLoc
504      /// locating it in the specified spill location.
505      static VarLoc CreateSpillLoc(const VarLoc &OldVL, const MachineLoc &OldML,
506                                   unsigned SpillBase, StackOffset SpillOffset) {
507        VarLoc VL = OldVL;
508        for (MachineLoc &ML : VL.Locs)
509          if (ML == OldML) {
510            ML.Kind = MachineLocKind::SpillLocKind;
511            ML.Value.SpillLocation = {SpillBase, SpillOffset};
512            return VL;
513          }
514        llvm_unreachable("Should have found OldML in new VarLoc.");
515      }
516  
517      /// Create a DBG_VALUE representing this VarLoc in the given function.
518      /// Copies variable-specific information such as DILocalVariable and
519      /// inlining information from the original DBG_VALUE instruction, which may
520      /// have been several transfers ago.
521      MachineInstr *BuildDbgValue(MachineFunction &MF) const {
522        assert(!isEntryBackupLoc() &&
523               "Tried to produce DBG_VALUE for backup VarLoc");
524        const DebugLoc &DbgLoc = MI.getDebugLoc();
525        bool Indirect = MI.isIndirectDebugValue();
526        const auto &IID = MI.getDesc();
527        const DILocalVariable *Var = MI.getDebugVariable();
528        NumInserted++;
529  
530        const DIExpression *DIExpr = Expr;
531        SmallVector<MachineOperand, 8> MOs;
532        for (unsigned I = 0, E = Locs.size(); I < E; ++I) {
533          MachineLocKind LocKind = Locs[I].Kind;
534          MachineLocValue Loc = Locs[I].Value;
535          const MachineOperand &Orig = MI.getDebugOperand(OrigLocMap[I]);
536          switch (LocKind) {
537          case MachineLocKind::RegisterKind:
538            // An entry value is a register location -- but with an updated
539            // expression. The register location of such DBG_VALUE is always the
540            // one from the entry DBG_VALUE, it does not matter if the entry value
541            // was copied in to another register due to some optimizations.
542            // Non-entry value register locations are like the source
543            // DBG_VALUE, but with the register number from this VarLoc.
544            MOs.push_back(MachineOperand::CreateReg(
545                EVKind == EntryValueLocKind::EntryValueKind ? Orig.getReg()
546                                                            : Register(Loc.RegNo),
547                false));
548            break;
549          case MachineLocKind::SpillLocKind: {
550            // Spills are indirect DBG_VALUEs, with a base register and offset.
551            // Use the original DBG_VALUEs expression to build the spilt location
552            // on top of. FIXME: spill locations created before this pass runs
553            // are not recognized, and not handled here.
554            unsigned Base = Loc.SpillLocation.SpillBase;
555            auto *TRI = MF.getSubtarget().getRegisterInfo();
556            if (MI.isNonListDebugValue()) {
557              auto Deref = Indirect ? DIExpression::DerefAfter : 0;
558              DIExpr = TRI->prependOffsetExpression(
559                  DIExpr, DIExpression::ApplyOffset | Deref,
560                  Loc.SpillLocation.SpillOffset);
561              Indirect = true;
562            } else {
563              SmallVector<uint64_t, 4> Ops;
564              TRI->getOffsetOpcodes(Loc.SpillLocation.SpillOffset, Ops);
565              Ops.push_back(dwarf::DW_OP_deref);
566              DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, I);
567            }
568            MOs.push_back(MachineOperand::CreateReg(Base, false));
569            break;
570          }
571          case MachineLocKind::ImmediateKind: {
572            MOs.push_back(Orig);
573            break;
574          }
575          case MachineLocKind::InvalidKind:
576            llvm_unreachable("Tried to produce DBG_VALUE for invalid VarLoc");
577          }
578        }
579        return BuildMI(MF, DbgLoc, IID, Indirect, MOs, Var, DIExpr);
580      }
581  
582      /// Is the Loc field a constant or constant object?
583      bool isConstant(MachineLocKind Kind) const {
584        return Kind == MachineLocKind::ImmediateKind;
585      }
586  
587      /// Check if the Loc field is an entry backup location.
588      bool isEntryBackupLoc() const {
589        return EVKind == EntryValueLocKind::EntryValueBackupKind ||
590               EVKind == EntryValueLocKind::EntryValueCopyBackupKind;
591      }
592  
593      /// If this variable is described by register \p Reg holding the entry
594      /// value, return true.
595      bool isEntryValueBackupReg(Register Reg) const {
596        return EVKind == EntryValueLocKind::EntryValueBackupKind && usesReg(Reg);
597      }
598  
599      /// If this variable is described by register \p Reg holding a copy of the
600      /// entry value, return true.
601      bool isEntryValueCopyBackupReg(Register Reg) const {
602        return EVKind == EntryValueLocKind::EntryValueCopyBackupKind &&
603               usesReg(Reg);
604      }
605  
606      /// If this variable is described in whole or part by \p Reg, return true.
607      bool usesReg(Register Reg) const {
608        MachineLoc RegML;
609        RegML.Kind = MachineLocKind::RegisterKind;
610        RegML.Value.RegNo = Reg;
611        return is_contained(Locs, RegML);
612      }
613  
614      /// If this variable is described in whole or part by \p Reg, return true.
615      unsigned getRegIdx(Register Reg) const {
616        for (unsigned Idx = 0; Idx < Locs.size(); ++Idx)
617          if (Locs[Idx].Kind == MachineLocKind::RegisterKind &&
618              Register{static_cast<unsigned>(Locs[Idx].Value.RegNo)} == Reg)
619            return Idx;
620        llvm_unreachable("Could not find given Reg in Locs");
621      }
622  
623      /// If this variable is described in whole or part by 1 or more registers,
624      /// add each of them to \p Regs and return true.
625      bool getDescribingRegs(SmallVectorImpl<uint32_t> &Regs) const {
626        bool AnyRegs = false;
627        for (const auto &Loc : Locs)
628          if (Loc.Kind == MachineLocKind::RegisterKind) {
629            Regs.push_back(Loc.Value.RegNo);
630            AnyRegs = true;
631          }
632        return AnyRegs;
633      }
634  
635      bool containsSpillLocs() const {
636        return any_of(Locs, [](VarLoc::MachineLoc ML) {
637          return ML.Kind == VarLoc::MachineLocKind::SpillLocKind;
638        });
639      }
640  
641      /// If this variable is described in whole or part by \p SpillLocation,
642      /// return true.
643      bool usesSpillLoc(SpillLoc SpillLocation) const {
644        MachineLoc SpillML;
645        SpillML.Kind = MachineLocKind::SpillLocKind;
646        SpillML.Value.SpillLocation = SpillLocation;
647        return is_contained(Locs, SpillML);
648      }
649  
650      /// If this variable is described in whole or part by \p SpillLocation,
651      /// return the index .
652      unsigned getSpillLocIdx(SpillLoc SpillLocation) const {
653        for (unsigned Idx = 0; Idx < Locs.size(); ++Idx)
654          if (Locs[Idx].Kind == MachineLocKind::SpillLocKind &&
655              Locs[Idx].Value.SpillLocation == SpillLocation)
656            return Idx;
657        llvm_unreachable("Could not find given SpillLoc in Locs");
658      }
659  
660      /// Determine whether the lexical scope of this value's debug location
661      /// dominates MBB.
662      bool dominates(LexicalScopes &LS, MachineBasicBlock &MBB) const {
663        return LS.dominates(MI.getDebugLoc().get(), &MBB);
664      }
665  
666  #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
667      // TRI can be null.
668      void dump(const TargetRegisterInfo *TRI, raw_ostream &Out = dbgs()) const {
669        Out << "VarLoc(";
670        for (const MachineLoc &MLoc : Locs) {
671          if (Locs.begin() != &MLoc)
672            Out << ", ";
673          switch (MLoc.Kind) {
674          case MachineLocKind::RegisterKind:
675            Out << printReg(MLoc.Value.RegNo, TRI);
676            break;
677          case MachineLocKind::SpillLocKind:
678            Out << printReg(MLoc.Value.SpillLocation.SpillBase, TRI);
679            Out << "[" << MLoc.Value.SpillLocation.SpillOffset.getFixed() << " + "
680                << MLoc.Value.SpillLocation.SpillOffset.getScalable()
681                << "x vscale"
682                << "]";
683            break;
684          case MachineLocKind::ImmediateKind:
685            Out << MLoc.Value.Immediate;
686            break;
687          case MachineLocKind::InvalidKind:
688            llvm_unreachable("Invalid VarLoc in dump method");
689          }
690        }
691  
692        Out << ", \"" << Var.getVariable()->getName() << "\", " << *Expr << ", ";
693        if (Var.getInlinedAt())
694          Out << "!" << Var.getInlinedAt()->getMetadataID() << ")\n";
695        else
696          Out << "(null))";
697  
698        if (isEntryBackupLoc())
699          Out << " (backup loc)\n";
700        else
701          Out << "\n";
702      }
703  #endif
704  
705      bool operator==(const VarLoc &Other) const {
706        return std::tie(EVKind, Var, Expr, Locs) ==
707               std::tie(Other.EVKind, Other.Var, Other.Expr, Other.Locs);
708      }
709  
710      /// This operator guarantees that VarLocs are sorted by Variable first.
711      bool operator<(const VarLoc &Other) const {
712        return std::tie(Var, EVKind, Locs, Expr) <
713               std::tie(Other.Var, Other.EVKind, Other.Locs, Other.Expr);
714      }
715    };
716  
717  #ifndef NDEBUG
718    using VarVec = SmallVector<VarLoc, 32>;
719  #endif
720  
721    /// VarLocMap is used for two things:
722    /// 1) Assigning LocIndices to a VarLoc. The LocIndices can be used to
723    ///    virtually insert a VarLoc into a VarLocSet.
724    /// 2) Given a LocIndex, look up the unique associated VarLoc.
725    class VarLocMap {
726      /// Map a VarLoc to an index within the vector reserved for its location
727      /// within Loc2Vars.
728      std::map<VarLoc, LocIndices> Var2Indices;
729  
730      /// Map a location to a vector which holds VarLocs which live in that
731      /// location.
732      SmallDenseMap<LocIndex::u32_location_t, std::vector<VarLoc>> Loc2Vars;
733  
734    public:
735      /// Retrieve LocIndices for \p VL.
736      LocIndices insert(const VarLoc &VL) {
737        LocIndices &Indices = Var2Indices[VL];
738        // If Indices is not empty, VL is already in the map.
739        if (!Indices.empty())
740          return Indices;
741        SmallVector<LocIndex::u32_location_t, 4> Locations;
742        // LocIndices are determined by EVKind and MLs; each Register has a
743        // unique location, while all SpillLocs use a single bucket, and any EV
744        // VarLocs use only the Backup bucket or none at all (except the
745        // compulsory entry at the universal location index). LocIndices will
746        // always have an index at the universal location index as the last index.
747        if (VL.EVKind == VarLoc::EntryValueLocKind::NonEntryValueKind) {
748          VL.getDescribingRegs(Locations);
749          assert(all_of(Locations,
750                        [](auto RegNo) {
751                          return RegNo < LocIndex::kFirstInvalidRegLocation;
752                        }) &&
753                 "Physreg out of range?");
754          if (VL.containsSpillLocs()) {
755            LocIndex::u32_location_t Loc = LocIndex::kSpillLocation;
756            Locations.push_back(Loc);
757          }
758        } else if (VL.EVKind != VarLoc::EntryValueLocKind::EntryValueKind) {
759          LocIndex::u32_location_t Loc = LocIndex::kEntryValueBackupLocation;
760          Locations.push_back(Loc);
761        }
762        Locations.push_back(LocIndex::kUniversalLocation);
763        for (LocIndex::u32_location_t Location : Locations) {
764          auto &Vars = Loc2Vars[Location];
765          Indices.push_back(
766              {Location, static_cast<LocIndex::u32_index_t>(Vars.size())});
767          Vars.push_back(VL);
768        }
769        return Indices;
770      }
771  
772      LocIndices getAllIndices(const VarLoc &VL) const {
773        auto IndIt = Var2Indices.find(VL);
774        assert(IndIt != Var2Indices.end() && "VarLoc not tracked");
775        return IndIt->second;
776      }
777  
778      /// Retrieve the unique VarLoc associated with \p ID.
779      const VarLoc &operator[](LocIndex ID) const {
780        auto LocIt = Loc2Vars.find(ID.Location);
781        assert(LocIt != Loc2Vars.end() && "Location not tracked");
782        return LocIt->second[ID.Index];
783      }
784    };
785  
786    using VarLocInMBB =
787        SmallDenseMap<const MachineBasicBlock *, std::unique_ptr<VarLocSet>>;
788    struct TransferDebugPair {
789      MachineInstr *TransferInst; ///< Instruction where this transfer occurs.
790      LocIndex LocationID;        ///< Location number for the transfer dest.
791    };
792    using TransferMap = SmallVector<TransferDebugPair, 4>;
793    // Types for recording Entry Var Locations emitted by a single MachineInstr,
794    // as well as recording MachineInstr which last defined a register.
795    using InstToEntryLocMap = std::multimap<const MachineInstr *, LocIndex>;
796    using RegDefToInstMap = DenseMap<Register, MachineInstr *>;
797  
798    // Types for recording sets of variable fragments that overlap. For a given
799    // local variable, we record all other fragments of that variable that could
800    // overlap it, to reduce search time.
801    using FragmentOfVar =
802        std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
803    using OverlapMap =
804        DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
805  
806    // Helper while building OverlapMap, a map of all fragments seen for a given
807    // DILocalVariable.
808    using VarToFragments =
809        DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
810  
811    /// Collects all VarLocs from \p CollectFrom. Each unique VarLoc is added
812    /// to \p Collected once, in order of insertion into \p VarLocIDs.
813    static void collectAllVarLocs(SmallVectorImpl<VarLoc> &Collected,
814                                  const VarLocSet &CollectFrom,
815                                  const VarLocMap &VarLocIDs);
816  
817    /// Get the registers which are used by VarLocs of kind RegisterKind tracked
818    /// by \p CollectFrom.
819    void getUsedRegs(const VarLocSet &CollectFrom,
820                     SmallVectorImpl<Register> &UsedRegs) const;
821  
822    /// This holds the working set of currently open ranges. For fast
823    /// access, this is done both as a set of VarLocIDs, and a map of
824    /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
825    /// previous open ranges for the same variable. In addition, we keep
826    /// two different maps (Vars/EntryValuesBackupVars), so erase/insert
827    /// methods act differently depending on whether a VarLoc is primary
828    /// location or backup one. In the case the VarLoc is backup location
829    /// we will erase/insert from the EntryValuesBackupVars map, otherwise
830    /// we perform the operation on the Vars.
831    class OpenRangesSet {
832      VarLocSet::Allocator &Alloc;
833      VarLocSet VarLocs;
834      // Map the DebugVariable to recent primary location ID.
835      SmallDenseMap<DebugVariable, LocIndices, 8> Vars;
836      // Map the DebugVariable to recent backup location ID.
837      SmallDenseMap<DebugVariable, LocIndices, 8> EntryValuesBackupVars;
838      OverlapMap &OverlappingFragments;
839  
840    public:
841      OpenRangesSet(VarLocSet::Allocator &Alloc, OverlapMap &_OLapMap)
842          : Alloc(Alloc), VarLocs(Alloc), OverlappingFragments(_OLapMap) {}
843  
844      const VarLocSet &getVarLocs() const { return VarLocs; }
845  
846      // Fetches all VarLocs in \p VarLocIDs and inserts them into \p Collected.
847      // This method is needed to get every VarLoc once, as each VarLoc may have
848      // multiple indices in a VarLocMap (corresponding to each applicable
849      // location), but all VarLocs appear exactly once at the universal location
850      // index.
851      void getUniqueVarLocs(SmallVectorImpl<VarLoc> &Collected,
852                            const VarLocMap &VarLocIDs) const {
853        collectAllVarLocs(Collected, VarLocs, VarLocIDs);
854      }
855  
856      /// Terminate all open ranges for VL.Var by removing it from the set.
857      void erase(const VarLoc &VL);
858  
859      /// Terminate all open ranges listed as indices in \c KillSet with
860      /// \c Location by removing them from the set.
861      void erase(const VarLocsInRange &KillSet, const VarLocMap &VarLocIDs,
862                 LocIndex::u32_location_t Location);
863  
864      /// Insert a new range into the set.
865      void insert(LocIndices VarLocIDs, const VarLoc &VL);
866  
867      /// Insert a set of ranges.
868      void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map);
869  
870      llvm::Optional<LocIndices> getEntryValueBackup(DebugVariable Var);
871  
872      /// Empty the set.
873      void clear() {
874        VarLocs.clear();
875        Vars.clear();
876        EntryValuesBackupVars.clear();
877      }
878  
879      /// Return whether the set is empty or not.
880      bool empty() const {
881        assert(Vars.empty() == EntryValuesBackupVars.empty() &&
882               Vars.empty() == VarLocs.empty() &&
883               "open ranges are inconsistent");
884        return VarLocs.empty();
885      }
886  
887      /// Get an empty range of VarLoc IDs.
888      auto getEmptyVarLocRange() const {
889        return iterator_range<VarLocSet::const_iterator>(getVarLocs().end(),
890                                                         getVarLocs().end());
891      }
892  
893      /// Get all set IDs for VarLocs with MLs of kind RegisterKind in \p Reg.
894      auto getRegisterVarLocs(Register Reg) const {
895        return LocIndex::indexRangeForLocation(getVarLocs(), Reg);
896      }
897  
898      /// Get all set IDs for VarLocs with MLs of kind SpillLocKind.
899      auto getSpillVarLocs() const {
900        return LocIndex::indexRangeForLocation(getVarLocs(),
901                                               LocIndex::kSpillLocation);
902      }
903  
904      /// Get all set IDs for VarLocs of EVKind EntryValueBackupKind or
905      /// EntryValueCopyBackupKind.
906      auto getEntryValueBackupVarLocs() const {
907        return LocIndex::indexRangeForLocation(
908            getVarLocs(), LocIndex::kEntryValueBackupLocation);
909      }
910    };
911  
912    /// Collect all VarLoc IDs from \p CollectFrom for VarLocs with MLs of kind
913    /// RegisterKind which are located in any reg in \p Regs. The IDs for each
914    /// VarLoc correspond to entries in the universal location bucket, which every
915    /// VarLoc has exactly 1 entry for. Insert collected IDs into \p Collected.
916    static void collectIDsForRegs(VarLocsInRange &Collected,
917                                  const DefinedRegsSet &Regs,
918                                  const VarLocSet &CollectFrom,
919                                  const VarLocMap &VarLocIDs);
920  
921    VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB, VarLocInMBB &Locs) {
922      std::unique_ptr<VarLocSet> &VLS = Locs[MBB];
923      if (!VLS)
924        VLS = std::make_unique<VarLocSet>(Alloc);
925      return *VLS.get();
926    }
927  
928    const VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB,
929                                     const VarLocInMBB &Locs) const {
930      auto It = Locs.find(MBB);
931      assert(It != Locs.end() && "MBB not in map");
932      return *It->second.get();
933    }
934  
935    /// Tests whether this instruction is a spill to a stack location.
936    bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
937  
938    /// Decide if @MI is a spill instruction and return true if it is. We use 2
939    /// criteria to make this decision:
940    /// - Is this instruction a store to a spill slot?
941    /// - Is there a register operand that is both used and killed?
942    /// TODO: Store optimization can fold spills into other stores (including
943    /// other spills). We do not handle this yet (more than one memory operand).
944    bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
945                         Register &Reg);
946  
947    /// Returns true if the given machine instruction is a debug value which we
948    /// can emit entry values for.
949    ///
950    /// Currently, we generate debug entry values only for parameters that are
951    /// unmodified throughout the function and located in a register.
952    bool isEntryValueCandidate(const MachineInstr &MI,
953                               const DefinedRegsSet &Regs) const;
954  
955    /// If a given instruction is identified as a spill, return the spill location
956    /// and set \p Reg to the spilled register.
957    Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
958                                                    MachineFunction *MF,
959                                                    Register &Reg);
960    /// Given a spill instruction, extract the register and offset used to
961    /// address the spill location in a target independent way.
962    VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
963    void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
964                                 TransferMap &Transfers, VarLocMap &VarLocIDs,
965                                 LocIndex OldVarID, TransferKind Kind,
966                                 const VarLoc::MachineLoc &OldLoc,
967                                 Register NewReg = Register());
968  
969    void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
970                            VarLocMap &VarLocIDs,
971                            InstToEntryLocMap &EntryValTransfers,
972                            RegDefToInstMap &RegSetInstrs);
973    void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
974                                    VarLocMap &VarLocIDs, TransferMap &Transfers);
975    void cleanupEntryValueTransfers(const MachineInstr *MI,
976                                    OpenRangesSet &OpenRanges,
977                                    VarLocMap &VarLocIDs, const VarLoc &EntryVL,
978                                    InstToEntryLocMap &EntryValTransfers);
979    void removeEntryValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
980                          VarLocMap &VarLocIDs, const VarLoc &EntryVL,
981                          InstToEntryLocMap &EntryValTransfers,
982                          RegDefToInstMap &RegSetInstrs);
983    void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
984                         VarLocMap &VarLocIDs,
985                         InstToEntryLocMap &EntryValTransfers,
986                         VarLocsInRange &KillSet);
987    void recordEntryValue(const MachineInstr &MI,
988                          const DefinedRegsSet &DefinedRegs,
989                          OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs);
990    void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
991                              VarLocMap &VarLocIDs, TransferMap &Transfers);
992    void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
993                             VarLocMap &VarLocIDs,
994                             InstToEntryLocMap &EntryValTransfers,
995                             RegDefToInstMap &RegSetInstrs);
996    bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
997                            VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
998  
999    void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
1000                 VarLocMap &VarLocIDs, TransferMap &Transfers,
1001                 InstToEntryLocMap &EntryValTransfers,
1002                 RegDefToInstMap &RegSetInstrs);
1003  
1004    void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
1005                               OverlapMap &OLapMap);
1006  
1007    bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1008              const VarLocMap &VarLocIDs,
1009              SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1010              SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
1011  
1012    /// Create DBG_VALUE insts for inlocs that have been propagated but
1013    /// had their instruction creation deferred.
1014    void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
1015  
1016    bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree,
1017                      TargetPassConfig *TPC, unsigned InputBBLimit,
1018                      unsigned InputDbgValLimit) override;
1019  
1020  public:
1021    /// Default construct and initialize the pass.
1022    VarLocBasedLDV();
1023  
1024    ~VarLocBasedLDV();
1025  
1026    /// Print to ostream with a message.
1027    void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
1028                          const VarLocMap &VarLocIDs, const char *msg,
1029                          raw_ostream &Out) const;
1030  };
1031  
1032  } // end anonymous namespace
1033  
1034  //===----------------------------------------------------------------------===//
1035  //            Implementation
1036  //===----------------------------------------------------------------------===//
1037  
1038  VarLocBasedLDV::VarLocBasedLDV() { }
1039  
1040  VarLocBasedLDV::~VarLocBasedLDV() { }
1041  
1042  /// Erase a variable from the set of open ranges, and additionally erase any
1043  /// fragments that may overlap it. If the VarLoc is a backup location, erase
1044  /// the variable from the EntryValuesBackupVars set, indicating we should stop
1045  /// tracking its backup entry location. Otherwise, if the VarLoc is primary
1046  /// location, erase the variable from the Vars set.
1047  void VarLocBasedLDV::OpenRangesSet::erase(const VarLoc &VL) {
1048    // Erasure helper.
1049    auto DoErase = [VL, this](DebugVariable VarToErase) {
1050      auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1051      auto It = EraseFrom->find(VarToErase);
1052      if (It != EraseFrom->end()) {
1053        LocIndices IDs = It->second;
1054        for (LocIndex ID : IDs)
1055          VarLocs.reset(ID.getAsRawInteger());
1056        EraseFrom->erase(It);
1057      }
1058    };
1059  
1060    DebugVariable Var = VL.Var;
1061  
1062    // Erase the variable/fragment that ends here.
1063    DoErase(Var);
1064  
1065    // Extract the fragment. Interpret an empty fragment as one that covers all
1066    // possible bits.
1067    FragmentInfo ThisFragment = Var.getFragmentOrDefault();
1068  
1069    // There may be fragments that overlap the designated fragment. Look them up
1070    // in the pre-computed overlap map, and erase them too.
1071    auto MapIt = OverlappingFragments.find({Var.getVariable(), ThisFragment});
1072    if (MapIt != OverlappingFragments.end()) {
1073      for (auto Fragment : MapIt->second) {
1074        VarLocBasedLDV::OptFragmentInfo FragmentHolder;
1075        if (!DebugVariable::isDefaultFragment(Fragment))
1076          FragmentHolder = VarLocBasedLDV::OptFragmentInfo(Fragment);
1077        DoErase({Var.getVariable(), FragmentHolder, Var.getInlinedAt()});
1078      }
1079    }
1080  }
1081  
1082  void VarLocBasedLDV::OpenRangesSet::erase(const VarLocsInRange &KillSet,
1083                                            const VarLocMap &VarLocIDs,
1084                                            LocIndex::u32_location_t Location) {
1085    VarLocSet RemoveSet(Alloc);
1086    for (LocIndex::u32_index_t ID : KillSet) {
1087      const VarLoc &VL = VarLocIDs[LocIndex(Location, ID)];
1088      auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1089      EraseFrom->erase(VL.Var);
1090      LocIndices VLI = VarLocIDs.getAllIndices(VL);
1091      for (LocIndex ID : VLI)
1092        RemoveSet.set(ID.getAsRawInteger());
1093    }
1094    VarLocs.intersectWithComplement(RemoveSet);
1095  }
1096  
1097  void VarLocBasedLDV::OpenRangesSet::insertFromLocSet(const VarLocSet &ToLoad,
1098                                                       const VarLocMap &Map) {
1099    VarLocsInRange UniqueVarLocIDs;
1100    DefinedRegsSet Regs;
1101    Regs.insert(LocIndex::kUniversalLocation);
1102    collectIDsForRegs(UniqueVarLocIDs, Regs, ToLoad, Map);
1103    for (uint64_t ID : UniqueVarLocIDs) {
1104      LocIndex Idx = LocIndex::fromRawInteger(ID);
1105      const VarLoc &VarL = Map[Idx];
1106      const LocIndices Indices = Map.getAllIndices(VarL);
1107      insert(Indices, VarL);
1108    }
1109  }
1110  
1111  void VarLocBasedLDV::OpenRangesSet::insert(LocIndices VarLocIDs,
1112                                             const VarLoc &VL) {
1113    auto *InsertInto = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1114    for (LocIndex ID : VarLocIDs)
1115      VarLocs.set(ID.getAsRawInteger());
1116    InsertInto->insert({VL.Var, VarLocIDs});
1117  }
1118  
1119  /// Return the Loc ID of an entry value backup location, if it exists for the
1120  /// variable.
1121  llvm::Optional<LocIndices>
1122  VarLocBasedLDV::OpenRangesSet::getEntryValueBackup(DebugVariable Var) {
1123    auto It = EntryValuesBackupVars.find(Var);
1124    if (It != EntryValuesBackupVars.end())
1125      return It->second;
1126  
1127    return llvm::None;
1128  }
1129  
1130  void VarLocBasedLDV::collectIDsForRegs(VarLocsInRange &Collected,
1131                                         const DefinedRegsSet &Regs,
1132                                         const VarLocSet &CollectFrom,
1133                                         const VarLocMap &VarLocIDs) {
1134    assert(!Regs.empty() && "Nothing to collect");
1135    SmallVector<Register, 32> SortedRegs;
1136    append_range(SortedRegs, Regs);
1137    array_pod_sort(SortedRegs.begin(), SortedRegs.end());
1138    auto It = CollectFrom.find(LocIndex::rawIndexForReg(SortedRegs.front()));
1139    auto End = CollectFrom.end();
1140    for (Register Reg : SortedRegs) {
1141      // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains
1142      // all possible VarLoc IDs for VarLocs with MLs of kind RegisterKind which
1143      // live in Reg.
1144      uint64_t FirstIndexForReg = LocIndex::rawIndexForReg(Reg);
1145      uint64_t FirstInvalidIndex = LocIndex::rawIndexForReg(Reg + 1);
1146      It.advanceToLowerBound(FirstIndexForReg);
1147  
1148      // Iterate through that half-open interval and collect all the set IDs.
1149      for (; It != End && *It < FirstInvalidIndex; ++It) {
1150        LocIndex ItIdx = LocIndex::fromRawInteger(*It);
1151        const VarLoc &VL = VarLocIDs[ItIdx];
1152        LocIndices LI = VarLocIDs.getAllIndices(VL);
1153        // For now, the back index is always the universal location index.
1154        assert(LI.back().Location == LocIndex::kUniversalLocation &&
1155               "Unexpected order of LocIndices for VarLoc; was it inserted into "
1156               "the VarLocMap correctly?");
1157        Collected.insert(LI.back().Index);
1158      }
1159  
1160      if (It == End)
1161        return;
1162    }
1163  }
1164  
1165  void VarLocBasedLDV::getUsedRegs(const VarLocSet &CollectFrom,
1166                                   SmallVectorImpl<Register> &UsedRegs) const {
1167    // All register-based VarLocs are assigned indices greater than or equal to
1168    // FirstRegIndex.
1169    uint64_t FirstRegIndex =
1170        LocIndex::rawIndexForReg(LocIndex::kFirstRegLocation);
1171    uint64_t FirstInvalidIndex =
1172        LocIndex::rawIndexForReg(LocIndex::kFirstInvalidRegLocation);
1173    for (auto It = CollectFrom.find(FirstRegIndex),
1174              End = CollectFrom.find(FirstInvalidIndex);
1175         It != End;) {
1176      // We found a VarLoc ID for a VarLoc that lives in a register. Figure out
1177      // which register and add it to UsedRegs.
1178      uint32_t FoundReg = LocIndex::fromRawInteger(*It).Location;
1179      assert((UsedRegs.empty() || FoundReg != UsedRegs.back()) &&
1180             "Duplicate used reg");
1181      UsedRegs.push_back(FoundReg);
1182  
1183      // Skip to the next /set/ register. Note that this finds a lower bound, so
1184      // even if there aren't any VarLocs living in `FoundReg+1`, we're still
1185      // guaranteed to move on to the next register (or to end()).
1186      uint64_t NextRegIndex = LocIndex::rawIndexForReg(FoundReg + 1);
1187      It.advanceToLowerBound(NextRegIndex);
1188    }
1189  }
1190  
1191  //===----------------------------------------------------------------------===//
1192  //            Debug Range Extension Implementation
1193  //===----------------------------------------------------------------------===//
1194  
1195  #ifndef NDEBUG
1196  void VarLocBasedLDV::printVarLocInMBB(const MachineFunction &MF,
1197                                         const VarLocInMBB &V,
1198                                         const VarLocMap &VarLocIDs,
1199                                         const char *msg,
1200                                         raw_ostream &Out) const {
1201    Out << '\n' << msg << '\n';
1202    for (const MachineBasicBlock &BB : MF) {
1203      if (!V.count(&BB))
1204        continue;
1205      const VarLocSet &L = getVarLocsInMBB(&BB, V);
1206      if (L.empty())
1207        continue;
1208      SmallVector<VarLoc, 32> VarLocs;
1209      collectAllVarLocs(VarLocs, L, VarLocIDs);
1210      Out << "MBB: " << BB.getNumber() << ":\n";
1211      for (const VarLoc &VL : VarLocs) {
1212        Out << " Var: " << VL.Var.getVariable()->getName();
1213        Out << " MI: ";
1214        VL.dump(TRI, Out);
1215      }
1216    }
1217    Out << "\n";
1218  }
1219  #endif
1220  
1221  VarLocBasedLDV::VarLoc::SpillLoc
1222  VarLocBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1223    assert(MI.hasOneMemOperand() &&
1224           "Spill instruction does not have exactly one memory operand?");
1225    auto MMOI = MI.memoperands_begin();
1226    const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1227    assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1228           "Inconsistent memory operand in spill instruction");
1229    int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1230    const MachineBasicBlock *MBB = MI.getParent();
1231    Register Reg;
1232    StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1233    return {Reg, Offset};
1234  }
1235  
1236  /// Do cleanup of \p EntryValTransfers created by \p TRInst, by removing the
1237  /// Transfer, which uses the to-be-deleted \p EntryVL.
1238  void VarLocBasedLDV::cleanupEntryValueTransfers(
1239      const MachineInstr *TRInst, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
1240      const VarLoc &EntryVL, InstToEntryLocMap &EntryValTransfers) {
1241    if (EntryValTransfers.empty() || TRInst == nullptr)
1242      return;
1243  
1244    auto TransRange = EntryValTransfers.equal_range(TRInst);
1245    for (auto TDPair : llvm::make_range(TransRange.first, TransRange.second)) {
1246      const VarLoc &EmittedEV = VarLocIDs[TDPair.second];
1247      if (std::tie(EntryVL.Var, EntryVL.Locs[0].Value.RegNo, EntryVL.Expr) ==
1248          std::tie(EmittedEV.Var, EmittedEV.Locs[0].Value.RegNo,
1249                   EmittedEV.Expr)) {
1250        OpenRanges.erase(EmittedEV);
1251        EntryValTransfers.erase(TRInst);
1252        break;
1253      }
1254    }
1255  }
1256  
1257  /// Try to salvage the debug entry value if we encounter a new debug value
1258  /// describing the same parameter, otherwise stop tracking the value. Return
1259  /// true if we should stop tracking the entry value and do the cleanup of
1260  /// emitted Entry Value Transfers, otherwise return false.
1261  void VarLocBasedLDV::removeEntryValue(const MachineInstr &MI,
1262                                        OpenRangesSet &OpenRanges,
1263                                        VarLocMap &VarLocIDs,
1264                                        const VarLoc &EntryVL,
1265                                        InstToEntryLocMap &EntryValTransfers,
1266                                        RegDefToInstMap &RegSetInstrs) {
1267    // Skip the DBG_VALUE which is the debug entry value itself.
1268    if (&MI == &EntryVL.MI)
1269      return;
1270  
1271    // If the parameter's location is not register location, we can not track
1272    // the entry value any more. It doesn't have the TransferInst which defines
1273    // register, so no Entry Value Transfers have been emitted already.
1274    if (!MI.getDebugOperand(0).isReg())
1275      return;
1276  
1277    // Try to get non-debug instruction responsible for the DBG_VALUE.
1278    const MachineInstr *TransferInst = nullptr;
1279    Register Reg = MI.getDebugOperand(0).getReg();
1280    if (Reg.isValid() && RegSetInstrs.find(Reg) != RegSetInstrs.end())
1281      TransferInst = RegSetInstrs.find(Reg)->second;
1282  
1283    // Case of the parameter's DBG_VALUE at the start of entry MBB.
1284    if (!TransferInst && !LastNonDbgMI && MI.getParent()->isEntryBlock())
1285      return;
1286  
1287    // If the debug expression from the DBG_VALUE is not empty, we can assume the
1288    // parameter's value has changed indicating that we should stop tracking its
1289    // entry value as well.
1290    if (MI.getDebugExpression()->getNumElements() == 0 && TransferInst) {
1291      // If the DBG_VALUE comes from a copy instruction that copies the entry
1292      // value, it means the parameter's value has not changed and we should be
1293      // able to use its entry value.
1294      // TODO: Try to keep tracking of an entry value if we encounter a propagated
1295      // DBG_VALUE describing the copy of the entry value. (Propagated entry value
1296      // does not indicate the parameter modification.)
1297      auto DestSrc = TII->isCopyInstr(*TransferInst);
1298      if (DestSrc) {
1299        const MachineOperand *SrcRegOp, *DestRegOp;
1300        SrcRegOp = DestSrc->Source;
1301        DestRegOp = DestSrc->Destination;
1302        if (Reg == DestRegOp->getReg()) {
1303          for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
1304            const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(ID)];
1305            if (VL.isEntryValueCopyBackupReg(Reg) &&
1306                // Entry Values should not be variadic.
1307                VL.MI.getDebugOperand(0).getReg() == SrcRegOp->getReg())
1308              return;
1309          }
1310        }
1311      }
1312    }
1313  
1314    LLVM_DEBUG(dbgs() << "Deleting a DBG entry value because of: ";
1315               MI.print(dbgs(), /*IsStandalone*/ false,
1316                        /*SkipOpers*/ false, /*SkipDebugLoc*/ false,
1317                        /*AddNewLine*/ true, TII));
1318    cleanupEntryValueTransfers(TransferInst, OpenRanges, VarLocIDs, EntryVL,
1319                               EntryValTransfers);
1320    OpenRanges.erase(EntryVL);
1321  }
1322  
1323  /// End all previous ranges related to @MI and start a new range from @MI
1324  /// if it is a DBG_VALUE instr.
1325  void VarLocBasedLDV::transferDebugValue(const MachineInstr &MI,
1326                                          OpenRangesSet &OpenRanges,
1327                                          VarLocMap &VarLocIDs,
1328                                          InstToEntryLocMap &EntryValTransfers,
1329                                          RegDefToInstMap &RegSetInstrs) {
1330    if (!MI.isDebugValue())
1331      return;
1332    const DILocalVariable *Var = MI.getDebugVariable();
1333    const DIExpression *Expr = MI.getDebugExpression();
1334    const DILocation *DebugLoc = MI.getDebugLoc();
1335    const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1336    assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1337           "Expected inlined-at fields to agree");
1338  
1339    DebugVariable V(Var, Expr, InlinedAt);
1340  
1341    // Check if this DBG_VALUE indicates a parameter's value changing.
1342    // If that is the case, we should stop tracking its entry value.
1343    auto EntryValBackupID = OpenRanges.getEntryValueBackup(V);
1344    if (Var->isParameter() && EntryValBackupID) {
1345      const VarLoc &EntryVL = VarLocIDs[EntryValBackupID->back()];
1346      removeEntryValue(MI, OpenRanges, VarLocIDs, EntryVL, EntryValTransfers,
1347                       RegSetInstrs);
1348    }
1349  
1350    if (all_of(MI.debug_operands(), [](const MachineOperand &MO) {
1351          return (MO.isReg() && MO.getReg()) || MO.isImm() || MO.isFPImm() ||
1352                 MO.isCImm();
1353        })) {
1354      // Use normal VarLoc constructor for registers and immediates.
1355      VarLoc VL(MI, LS);
1356      // End all previous ranges of VL.Var.
1357      OpenRanges.erase(VL);
1358  
1359      LocIndices IDs = VarLocIDs.insert(VL);
1360      // Add the VarLoc to OpenRanges from this DBG_VALUE.
1361      OpenRanges.insert(IDs, VL);
1362    } else if (MI.memoperands().size() > 0) {
1363      llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
1364    } else {
1365      // This must be an undefined location. If it has an open range, erase it.
1366      assert(MI.isUndefDebugValue() &&
1367             "Unexpected non-undef DBG_VALUE encountered");
1368      VarLoc VL(MI, LS);
1369      OpenRanges.erase(VL);
1370    }
1371  }
1372  
1373  // This should be removed later, doesn't fit the new design.
1374  void VarLocBasedLDV::collectAllVarLocs(SmallVectorImpl<VarLoc> &Collected,
1375                                         const VarLocSet &CollectFrom,
1376                                         const VarLocMap &VarLocIDs) {
1377    // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains all
1378    // possible VarLoc IDs for VarLocs with MLs of kind RegisterKind which live
1379    // in Reg.
1380    uint64_t FirstIndex = LocIndex::rawIndexForReg(LocIndex::kUniversalLocation);
1381    uint64_t FirstInvalidIndex =
1382        LocIndex::rawIndexForReg(LocIndex::kUniversalLocation + 1);
1383    // Iterate through that half-open interval and collect all the set IDs.
1384    for (auto It = CollectFrom.find(FirstIndex), End = CollectFrom.end();
1385         It != End && *It < FirstInvalidIndex; ++It) {
1386      LocIndex RegIdx = LocIndex::fromRawInteger(*It);
1387      Collected.push_back(VarLocIDs[RegIdx]);
1388    }
1389  }
1390  
1391  /// Turn the entry value backup locations into primary locations.
1392  void VarLocBasedLDV::emitEntryValues(MachineInstr &MI,
1393                                       OpenRangesSet &OpenRanges,
1394                                       VarLocMap &VarLocIDs,
1395                                       InstToEntryLocMap &EntryValTransfers,
1396                                       VarLocsInRange &KillSet) {
1397    // Do not insert entry value locations after a terminator.
1398    if (MI.isTerminator())
1399      return;
1400  
1401    for (uint32_t ID : KillSet) {
1402      // The KillSet IDs are indices for the universal location bucket.
1403      LocIndex Idx = LocIndex(LocIndex::kUniversalLocation, ID);
1404      const VarLoc &VL = VarLocIDs[Idx];
1405      if (!VL.Var.getVariable()->isParameter())
1406        continue;
1407  
1408      auto DebugVar = VL.Var;
1409      Optional<LocIndices> EntryValBackupIDs =
1410          OpenRanges.getEntryValueBackup(DebugVar);
1411  
1412      // If the parameter has the entry value backup, it means we should
1413      // be able to use its entry value.
1414      if (!EntryValBackupIDs)
1415        continue;
1416  
1417      const VarLoc &EntryVL = VarLocIDs[EntryValBackupIDs->back()];
1418      VarLoc EntryLoc = VarLoc::CreateEntryLoc(EntryVL.MI, LS, EntryVL.Expr,
1419                                               EntryVL.Locs[0].Value.RegNo);
1420      LocIndices EntryValueIDs = VarLocIDs.insert(EntryLoc);
1421      assert(EntryValueIDs.size() == 1 &&
1422             "EntryValue loc should not be variadic");
1423      EntryValTransfers.insert({&MI, EntryValueIDs.back()});
1424      OpenRanges.insert(EntryValueIDs, EntryLoc);
1425    }
1426  }
1427  
1428  /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
1429  /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
1430  /// new VarLoc. If \p NewReg is different than default zero value then the
1431  /// new location will be register location created by the copy like instruction,
1432  /// otherwise it is variable's location on the stack.
1433  void VarLocBasedLDV::insertTransferDebugPair(
1434      MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
1435      VarLocMap &VarLocIDs, LocIndex OldVarID, TransferKind Kind,
1436      const VarLoc::MachineLoc &OldLoc, Register NewReg) {
1437    const VarLoc &OldVarLoc = VarLocIDs[OldVarID];
1438  
1439    auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &VarLocIDs](VarLoc &VL) {
1440      LocIndices LocIds = VarLocIDs.insert(VL);
1441  
1442      // Close this variable's previous location range.
1443      OpenRanges.erase(VL);
1444  
1445      // Record the new location as an open range, and a postponed transfer
1446      // inserting a DBG_VALUE for this location.
1447      OpenRanges.insert(LocIds, VL);
1448      assert(!MI.isTerminator() && "Cannot insert DBG_VALUE after terminator");
1449      TransferDebugPair MIP = {&MI, LocIds.back()};
1450      Transfers.push_back(MIP);
1451    };
1452  
1453    // End all previous ranges of VL.Var.
1454    OpenRanges.erase(VarLocIDs[OldVarID]);
1455    switch (Kind) {
1456    case TransferKind::TransferCopy: {
1457      assert(NewReg &&
1458             "No register supplied when handling a copy of a debug value");
1459      // Create a DBG_VALUE instruction to describe the Var in its new
1460      // register location.
1461      VarLoc VL = VarLoc::CreateCopyLoc(OldVarLoc, OldLoc, NewReg);
1462      ProcessVarLoc(VL);
1463      LLVM_DEBUG({
1464        dbgs() << "Creating VarLoc for register copy:";
1465        VL.dump(TRI);
1466      });
1467      return;
1468    }
1469    case TransferKind::TransferSpill: {
1470      // Create a DBG_VALUE instruction to describe the Var in its spilled
1471      // location.
1472      VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
1473      VarLoc VL = VarLoc::CreateSpillLoc(
1474          OldVarLoc, OldLoc, SpillLocation.SpillBase, SpillLocation.SpillOffset);
1475      ProcessVarLoc(VL);
1476      LLVM_DEBUG({
1477        dbgs() << "Creating VarLoc for spill:";
1478        VL.dump(TRI);
1479      });
1480      return;
1481    }
1482    case TransferKind::TransferRestore: {
1483      assert(NewReg &&
1484             "No register supplied when handling a restore of a debug value");
1485      // DebugInstr refers to the pre-spill location, therefore we can reuse
1486      // its expression.
1487      VarLoc VL = VarLoc::CreateCopyLoc(OldVarLoc, OldLoc, NewReg);
1488      ProcessVarLoc(VL);
1489      LLVM_DEBUG({
1490        dbgs() << "Creating VarLoc for restore:";
1491        VL.dump(TRI);
1492      });
1493      return;
1494    }
1495    }
1496    llvm_unreachable("Invalid transfer kind");
1497  }
1498  
1499  /// A definition of a register may mark the end of a range.
1500  void VarLocBasedLDV::transferRegisterDef(MachineInstr &MI,
1501                                           OpenRangesSet &OpenRanges,
1502                                           VarLocMap &VarLocIDs,
1503                                           InstToEntryLocMap &EntryValTransfers,
1504                                           RegDefToInstMap &RegSetInstrs) {
1505  
1506    // Meta Instructions do not affect the debug liveness of any register they
1507    // define.
1508    if (MI.isMetaInstruction())
1509      return;
1510  
1511    MachineFunction *MF = MI.getMF();
1512    const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1513    Register SP = TLI->getStackPointerRegisterToSaveRestore();
1514  
1515    // Find the regs killed by MI, and find regmasks of preserved regs.
1516    DefinedRegsSet DeadRegs;
1517    SmallVector<const uint32_t *, 4> RegMasks;
1518    for (const MachineOperand &MO : MI.operands()) {
1519      // Determine whether the operand is a register def.
1520      if (MO.isReg() && MO.isDef() && MO.getReg() &&
1521          Register::isPhysicalRegister(MO.getReg()) &&
1522          !(MI.isCall() && MO.getReg() == SP)) {
1523        // Remove ranges of all aliased registers.
1524        for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1525          // FIXME: Can we break out of this loop early if no insertion occurs?
1526          DeadRegs.insert(*RAI);
1527        RegSetInstrs.erase(MO.getReg());
1528        RegSetInstrs.insert({MO.getReg(), &MI});
1529      } else if (MO.isRegMask()) {
1530        RegMasks.push_back(MO.getRegMask());
1531      }
1532    }
1533  
1534    // Erase VarLocs which reside in one of the dead registers. For performance
1535    // reasons, it's critical to not iterate over the full set of open VarLocs.
1536    // Iterate over the set of dying/used regs instead.
1537    if (!RegMasks.empty()) {
1538      SmallVector<Register, 32> UsedRegs;
1539      getUsedRegs(OpenRanges.getVarLocs(), UsedRegs);
1540      for (Register Reg : UsedRegs) {
1541        // Remove ranges of all clobbered registers. Register masks don't usually
1542        // list SP as preserved. Assume that call instructions never clobber SP,
1543        // because some backends (e.g., AArch64) never list SP in the regmask.
1544        // While the debug info may be off for an instruction or two around
1545        // callee-cleanup calls, transferring the DEBUG_VALUE across the call is
1546        // still a better user experience.
1547        if (Reg == SP)
1548          continue;
1549        bool AnyRegMaskKillsReg =
1550            any_of(RegMasks, [Reg](const uint32_t *RegMask) {
1551              return MachineOperand::clobbersPhysReg(RegMask, Reg);
1552            });
1553        if (AnyRegMaskKillsReg)
1554          DeadRegs.insert(Reg);
1555        if (AnyRegMaskKillsReg) {
1556          RegSetInstrs.erase(Reg);
1557          RegSetInstrs.insert({Reg, &MI});
1558        }
1559      }
1560    }
1561  
1562    if (DeadRegs.empty())
1563      return;
1564  
1565    VarLocsInRange KillSet;
1566    collectIDsForRegs(KillSet, DeadRegs, OpenRanges.getVarLocs(), VarLocIDs);
1567    OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kUniversalLocation);
1568  
1569    if (TPC) {
1570      auto &TM = TPC->getTM<TargetMachine>();
1571      if (TM.Options.ShouldEmitDebugEntryValues())
1572        emitEntryValues(MI, OpenRanges, VarLocIDs, EntryValTransfers, KillSet);
1573    }
1574  }
1575  
1576  bool VarLocBasedLDV::isSpillInstruction(const MachineInstr &MI,
1577                                           MachineFunction *MF) {
1578    // TODO: Handle multiple stores folded into one.
1579    if (!MI.hasOneMemOperand())
1580      return false;
1581  
1582    if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1583      return false; // This is not a spill instruction, since no valid size was
1584                    // returned from either function.
1585  
1586    return true;
1587  }
1588  
1589  bool VarLocBasedLDV::isLocationSpill(const MachineInstr &MI,
1590                                        MachineFunction *MF, Register &Reg) {
1591    if (!isSpillInstruction(MI, MF))
1592      return false;
1593  
1594    auto isKilledReg = [&](const MachineOperand MO, Register &Reg) {
1595      if (!MO.isReg() || !MO.isUse()) {
1596        Reg = 0;
1597        return false;
1598      }
1599      Reg = MO.getReg();
1600      return MO.isKill();
1601    };
1602  
1603    for (const MachineOperand &MO : MI.operands()) {
1604      // In a spill instruction generated by the InlineSpiller the spilled
1605      // register has its kill flag set.
1606      if (isKilledReg(MO, Reg))
1607        return true;
1608      if (Reg != 0) {
1609        // Check whether next instruction kills the spilled register.
1610        // FIXME: Current solution does not cover search for killed register in
1611        // bundles and instructions further down the chain.
1612        auto NextI = std::next(MI.getIterator());
1613        // Skip next instruction that points to basic block end iterator.
1614        if (MI.getParent()->end() == NextI)
1615          continue;
1616        Register RegNext;
1617        for (const MachineOperand &MONext : NextI->operands()) {
1618          // Return true if we came across the register from the
1619          // previous spill instruction that is killed in NextI.
1620          if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1621            return true;
1622        }
1623      }
1624    }
1625    // Return false if we didn't find spilled register.
1626    return false;
1627  }
1628  
1629  Optional<VarLocBasedLDV::VarLoc::SpillLoc>
1630  VarLocBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1631                                        MachineFunction *MF, Register &Reg) {
1632    if (!MI.hasOneMemOperand())
1633      return None;
1634  
1635    // FIXME: Handle folded restore instructions with more than one memory
1636    // operand.
1637    if (MI.getRestoreSize(TII)) {
1638      Reg = MI.getOperand(0).getReg();
1639      return extractSpillBaseRegAndOffset(MI);
1640    }
1641    return None;
1642  }
1643  
1644  /// A spilled register may indicate that we have to end the current range of
1645  /// a variable and create a new one for the spill location.
1646  /// A restored register may indicate the reverse situation.
1647  /// We don't want to insert any instructions in process(), so we just create
1648  /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
1649  /// It will be inserted into the BB when we're done iterating over the
1650  /// instructions.
1651  void VarLocBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI,
1652                                                   OpenRangesSet &OpenRanges,
1653                                                   VarLocMap &VarLocIDs,
1654                                                   TransferMap &Transfers) {
1655    MachineFunction *MF = MI.getMF();
1656    TransferKind TKind;
1657    Register Reg;
1658    Optional<VarLoc::SpillLoc> Loc;
1659  
1660    LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1661  
1662    // First, if there are any DBG_VALUEs pointing at a spill slot that is
1663    // written to, then close the variable location. The value in memory
1664    // will have changed.
1665    VarLocsInRange KillSet;
1666    if (isSpillInstruction(MI, MF)) {
1667      Loc = extractSpillBaseRegAndOffset(MI);
1668      for (uint64_t ID : OpenRanges.getSpillVarLocs()) {
1669        LocIndex Idx = LocIndex::fromRawInteger(ID);
1670        const VarLoc &VL = VarLocIDs[Idx];
1671        assert(VL.containsSpillLocs() && "Broken VarLocSet?");
1672        if (VL.usesSpillLoc(*Loc)) {
1673          // This location is overwritten by the current instruction -- terminate
1674          // the open range, and insert an explicit DBG_VALUE $noreg.
1675          //
1676          // Doing this at a later stage would require re-interpreting all
1677          // DBG_VALUes and DIExpressions to identify whether they point at
1678          // memory, and then analysing all memory writes to see if they
1679          // overwrite that memory, which is expensive.
1680          //
1681          // At this stage, we already know which DBG_VALUEs are for spills and
1682          // where they are located; it's best to fix handle overwrites now.
1683          KillSet.insert(ID);
1684          unsigned SpillLocIdx = VL.getSpillLocIdx(*Loc);
1685          VarLoc::MachineLoc OldLoc = VL.Locs[SpillLocIdx];
1686          VarLoc UndefVL = VarLoc::CreateCopyLoc(VL, OldLoc, 0);
1687          LocIndices UndefLocIDs = VarLocIDs.insert(UndefVL);
1688          Transfers.push_back({&MI, UndefLocIDs.back()});
1689        }
1690      }
1691      OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kSpillLocation);
1692    }
1693  
1694    // Try to recognise spill and restore instructions that may create a new
1695    // variable location.
1696    if (isLocationSpill(MI, MF, Reg)) {
1697      TKind = TransferKind::TransferSpill;
1698      LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
1699      LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1700                        << "\n");
1701    } else {
1702      if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
1703        return;
1704      TKind = TransferKind::TransferRestore;
1705      LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
1706      LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1707                        << "\n");
1708    }
1709    // Check if the register or spill location is the location of a debug value.
1710    auto TransferCandidates = OpenRanges.getEmptyVarLocRange();
1711    if (TKind == TransferKind::TransferSpill)
1712      TransferCandidates = OpenRanges.getRegisterVarLocs(Reg);
1713    else if (TKind == TransferKind::TransferRestore)
1714      TransferCandidates = OpenRanges.getSpillVarLocs();
1715    for (uint64_t ID : TransferCandidates) {
1716      LocIndex Idx = LocIndex::fromRawInteger(ID);
1717      const VarLoc &VL = VarLocIDs[Idx];
1718      unsigned LocIdx;
1719      if (TKind == TransferKind::TransferSpill) {
1720        assert(VL.usesReg(Reg) && "Broken VarLocSet?");
1721        LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
1722                          << VL.Var.getVariable()->getName() << ")\n");
1723        LocIdx = VL.getRegIdx(Reg);
1724      } else {
1725        assert(TKind == TransferKind::TransferRestore && VL.containsSpillLocs() &&
1726               "Broken VarLocSet?");
1727        if (!VL.usesSpillLoc(*Loc))
1728          // The spill location is not the location of a debug value.
1729          continue;
1730        LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
1731                          << VL.Var.getVariable()->getName() << ")\n");
1732        LocIdx = VL.getSpillLocIdx(*Loc);
1733      }
1734      VarLoc::MachineLoc MLoc = VL.Locs[LocIdx];
1735      insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx, TKind,
1736                              MLoc, Reg);
1737      // FIXME: A comment should explain why it's correct to return early here,
1738      // if that is in fact correct.
1739      return;
1740    }
1741  }
1742  
1743  /// If \p MI is a register copy instruction, that copies a previously tracked
1744  /// value from one register to another register that is callee saved, we
1745  /// create new DBG_VALUE instruction  described with copy destination register.
1746  void VarLocBasedLDV::transferRegisterCopy(MachineInstr &MI,
1747                                             OpenRangesSet &OpenRanges,
1748                                             VarLocMap &VarLocIDs,
1749                                             TransferMap &Transfers) {
1750    auto DestSrc = TII->isCopyInstr(MI);
1751    if (!DestSrc)
1752      return;
1753  
1754    const MachineOperand *DestRegOp = DestSrc->Destination;
1755    const MachineOperand *SrcRegOp = DestSrc->Source;
1756  
1757    if (!DestRegOp->isDef())
1758      return;
1759  
1760    auto isCalleeSavedReg = [&](Register Reg) {
1761      for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1762        if (CalleeSavedRegs.test(*RAI))
1763          return true;
1764      return false;
1765    };
1766  
1767    Register SrcReg = SrcRegOp->getReg();
1768    Register DestReg = DestRegOp->getReg();
1769  
1770    // We want to recognize instructions where destination register is callee
1771    // saved register. If register that could be clobbered by the call is
1772    // included, there would be a great chance that it is going to be clobbered
1773    // soon. It is more likely that previous register location, which is callee
1774    // saved, is going to stay unclobbered longer, even if it is killed.
1775    if (!isCalleeSavedReg(DestReg))
1776      return;
1777  
1778    // Remember an entry value movement. If we encounter a new debug value of
1779    // a parameter describing only a moving of the value around, rather then
1780    // modifying it, we are still able to use the entry value if needed.
1781    if (isRegOtherThanSPAndFP(*DestRegOp, MI, TRI)) {
1782      for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
1783        LocIndex Idx = LocIndex::fromRawInteger(ID);
1784        const VarLoc &VL = VarLocIDs[Idx];
1785        if (VL.isEntryValueBackupReg(SrcReg)) {
1786          LLVM_DEBUG(dbgs() << "Copy of the entry value: "; MI.dump(););
1787          VarLoc EntryValLocCopyBackup =
1788              VarLoc::CreateEntryCopyBackupLoc(VL.MI, LS, VL.Expr, DestReg);
1789          // Stop tracking the original entry value.
1790          OpenRanges.erase(VL);
1791  
1792          // Start tracking the entry value copy.
1793          LocIndices EntryValCopyLocIDs = VarLocIDs.insert(EntryValLocCopyBackup);
1794          OpenRanges.insert(EntryValCopyLocIDs, EntryValLocCopyBackup);
1795          break;
1796        }
1797      }
1798    }
1799  
1800    if (!SrcRegOp->isKill())
1801      return;
1802  
1803    for (uint64_t ID : OpenRanges.getRegisterVarLocs(SrcReg)) {
1804      LocIndex Idx = LocIndex::fromRawInteger(ID);
1805      assert(VarLocIDs[Idx].usesReg(SrcReg) && "Broken VarLocSet?");
1806      VarLoc::MachineLocValue Loc;
1807      Loc.RegNo = SrcReg;
1808      VarLoc::MachineLoc MLoc{VarLoc::MachineLocKind::RegisterKind, Loc};
1809      insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx,
1810                              TransferKind::TransferCopy, MLoc, DestReg);
1811      // FIXME: A comment should explain why it's correct to return early here,
1812      // if that is in fact correct.
1813      return;
1814    }
1815  }
1816  
1817  /// Terminate all open ranges at the end of the current basic block.
1818  bool VarLocBasedLDV::transferTerminator(MachineBasicBlock *CurMBB,
1819                                           OpenRangesSet &OpenRanges,
1820                                           VarLocInMBB &OutLocs,
1821                                           const VarLocMap &VarLocIDs) {
1822    bool Changed = false;
1823    LLVM_DEBUG({
1824      VarVec VarLocs;
1825      OpenRanges.getUniqueVarLocs(VarLocs, VarLocIDs);
1826      for (VarLoc &VL : VarLocs) {
1827        // Copy OpenRanges to OutLocs, if not already present.
1828        dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ":  ";
1829        VL.dump(TRI);
1830      }
1831    });
1832    VarLocSet &VLS = getVarLocsInMBB(CurMBB, OutLocs);
1833    Changed = VLS != OpenRanges.getVarLocs();
1834    // New OutLocs set may be different due to spill, restore or register
1835    // copy instruction processing.
1836    if (Changed)
1837      VLS = OpenRanges.getVarLocs();
1838    OpenRanges.clear();
1839    return Changed;
1840  }
1841  
1842  /// Accumulate a mapping between each DILocalVariable fragment and other
1843  /// fragments of that DILocalVariable which overlap. This reduces work during
1844  /// the data-flow stage from "Find any overlapping fragments" to "Check if the
1845  /// known-to-overlap fragments are present".
1846  /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
1847  ///           fragment usage.
1848  /// \param SeenFragments Map from DILocalVariable to all fragments of that
1849  ///           Variable which are known to exist.
1850  /// \param OverlappingFragments The overlap map being constructed, from one
1851  ///           Var/Fragment pair to a vector of fragments known to overlap.
1852  void VarLocBasedLDV::accumulateFragmentMap(MachineInstr &MI,
1853                                              VarToFragments &SeenFragments,
1854                                              OverlapMap &OverlappingFragments) {
1855    DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1856                        MI.getDebugLoc()->getInlinedAt());
1857    FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1858  
1859    // If this is the first sighting of this variable, then we are guaranteed
1860    // there are currently no overlapping fragments either. Initialize the set
1861    // of seen fragments, record no overlaps for the current one, and return.
1862    auto SeenIt = SeenFragments.find(MIVar.getVariable());
1863    if (SeenIt == SeenFragments.end()) {
1864      SmallSet<FragmentInfo, 4> OneFragment;
1865      OneFragment.insert(ThisFragment);
1866      SeenFragments.insert({MIVar.getVariable(), OneFragment});
1867  
1868      OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1869      return;
1870    }
1871  
1872    // If this particular Variable/Fragment pair already exists in the overlap
1873    // map, it has already been accounted for.
1874    auto IsInOLapMap =
1875        OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1876    if (!IsInOLapMap.second)
1877      return;
1878  
1879    auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1880    auto &AllSeenFragments = SeenIt->second;
1881  
1882    // Otherwise, examine all other seen fragments for this variable, with "this"
1883    // fragment being a previously unseen fragment. Record any pair of
1884    // overlapping fragments.
1885    for (auto &ASeenFragment : AllSeenFragments) {
1886      // Does this previously seen fragment overlap?
1887      if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1888        // Yes: Mark the current fragment as being overlapped.
1889        ThisFragmentsOverlaps.push_back(ASeenFragment);
1890        // Mark the previously seen fragment as being overlapped by the current
1891        // one.
1892        auto ASeenFragmentsOverlaps =
1893            OverlappingFragments.find({MIVar.getVariable(), ASeenFragment});
1894        assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
1895               "Previously seen var fragment has no vector of overlaps");
1896        ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1897      }
1898    }
1899  
1900    AllSeenFragments.insert(ThisFragment);
1901  }
1902  
1903  /// This routine creates OpenRanges.
1904  void VarLocBasedLDV::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
1905                               VarLocMap &VarLocIDs, TransferMap &Transfers,
1906                               InstToEntryLocMap &EntryValTransfers,
1907                               RegDefToInstMap &RegSetInstrs) {
1908    if (!MI.isDebugInstr())
1909      LastNonDbgMI = &MI;
1910    transferDebugValue(MI, OpenRanges, VarLocIDs, EntryValTransfers,
1911                       RegSetInstrs);
1912    transferRegisterDef(MI, OpenRanges, VarLocIDs, EntryValTransfers,
1913                        RegSetInstrs);
1914    transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
1915    transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
1916  }
1917  
1918  /// This routine joins the analysis results of all incoming edges in @MBB by
1919  /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1920  /// source variable in all the predecessors of @MBB reside in the same location.
1921  bool VarLocBasedLDV::join(
1922      MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1923      const VarLocMap &VarLocIDs,
1924      SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1925      SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
1926    LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
1927  
1928    VarLocSet InLocsT(Alloc); // Temporary incoming locations.
1929  
1930    // For all predecessors of this MBB, find the set of VarLocs that
1931    // can be joined.
1932    int NumVisited = 0;
1933    for (auto p : MBB.predecessors()) {
1934      // Ignore backedges if we have not visited the predecessor yet. As the
1935      // predecessor hasn't yet had locations propagated into it, most locations
1936      // will not yet be valid, so treat them as all being uninitialized and
1937      // potentially valid. If a location guessed to be correct here is
1938      // invalidated later, we will remove it when we revisit this block.
1939      if (!Visited.count(p)) {
1940        LLVM_DEBUG(dbgs() << "  ignoring unvisited pred MBB: " << p->getNumber()
1941                          << "\n");
1942        continue;
1943      }
1944      auto OL = OutLocs.find(p);
1945      // Join is null in case of empty OutLocs from any of the pred.
1946      if (OL == OutLocs.end())
1947        return false;
1948  
1949      // Just copy over the Out locs to incoming locs for the first visited
1950      // predecessor, and for all other predecessors join the Out locs.
1951      VarLocSet &OutLocVLS = *OL->second.get();
1952      if (!NumVisited)
1953        InLocsT = OutLocVLS;
1954      else
1955        InLocsT &= OutLocVLS;
1956  
1957      LLVM_DEBUG({
1958        if (!InLocsT.empty()) {
1959          VarVec VarLocs;
1960          collectAllVarLocs(VarLocs, InLocsT, VarLocIDs);
1961          for (const VarLoc &VL : VarLocs)
1962            dbgs() << "  gathered candidate incoming var: "
1963                   << VL.Var.getVariable()->getName() << "\n";
1964        }
1965      });
1966  
1967      NumVisited++;
1968    }
1969  
1970    // Filter out DBG_VALUES that are out of scope.
1971    VarLocSet KillSet(Alloc);
1972    bool IsArtificial = ArtificialBlocks.count(&MBB);
1973    if (!IsArtificial) {
1974      for (uint64_t ID : InLocsT) {
1975        LocIndex Idx = LocIndex::fromRawInteger(ID);
1976        if (!VarLocIDs[Idx].dominates(LS, MBB)) {
1977          KillSet.set(ID);
1978          LLVM_DEBUG({
1979            auto Name = VarLocIDs[Idx].Var.getVariable()->getName();
1980            dbgs() << "  killing " << Name << ", it doesn't dominate MBB\n";
1981          });
1982        }
1983      }
1984    }
1985    InLocsT.intersectWithComplement(KillSet);
1986  
1987    // As we are processing blocks in reverse post-order we
1988    // should have processed at least one predecessor, unless it
1989    // is the entry block which has no predecessor.
1990    assert((NumVisited || MBB.pred_empty()) &&
1991           "Should have processed at least one predecessor");
1992  
1993    VarLocSet &ILS = getVarLocsInMBB(&MBB, InLocs);
1994    bool Changed = false;
1995    if (ILS != InLocsT) {
1996      ILS = InLocsT;
1997      Changed = true;
1998    }
1999  
2000    return Changed;
2001  }
2002  
2003  void VarLocBasedLDV::flushPendingLocs(VarLocInMBB &PendingInLocs,
2004                                         VarLocMap &VarLocIDs) {
2005    // PendingInLocs records all locations propagated into blocks, which have
2006    // not had DBG_VALUE insts created. Go through and create those insts now.
2007    for (auto &Iter : PendingInLocs) {
2008      // Map is keyed on a constant pointer, unwrap it so we can insert insts.
2009      auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
2010      VarLocSet &Pending = *Iter.second.get();
2011  
2012      SmallVector<VarLoc, 32> VarLocs;
2013      collectAllVarLocs(VarLocs, Pending, VarLocIDs);
2014  
2015      for (VarLoc DiffIt : VarLocs) {
2016        // The ID location is live-in to MBB -- work out what kind of machine
2017        // location it is and create a DBG_VALUE.
2018        if (DiffIt.isEntryBackupLoc())
2019          continue;
2020        MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent());
2021        MBB.insert(MBB.instr_begin(), MI);
2022  
2023        (void)MI;
2024        LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
2025      }
2026    }
2027  }
2028  
2029  bool VarLocBasedLDV::isEntryValueCandidate(
2030      const MachineInstr &MI, const DefinedRegsSet &DefinedRegs) const {
2031    assert(MI.isDebugValue() && "This must be DBG_VALUE.");
2032  
2033    // TODO: Add support for local variables that are expressed in terms of
2034    // parameters entry values.
2035    // TODO: Add support for modified arguments that can be expressed
2036    // by using its entry value.
2037    auto *DIVar = MI.getDebugVariable();
2038    if (!DIVar->isParameter())
2039      return false;
2040  
2041    // Do not consider parameters that belong to an inlined function.
2042    if (MI.getDebugLoc()->getInlinedAt())
2043      return false;
2044  
2045    // Only consider parameters that are described using registers. Parameters
2046    // that are passed on the stack are not yet supported, so ignore debug
2047    // values that are described by the frame or stack pointer.
2048    if (!isRegOtherThanSPAndFP(MI.getDebugOperand(0), MI, TRI))
2049      return false;
2050  
2051    // If a parameter's value has been propagated from the caller, then the
2052    // parameter's DBG_VALUE may be described using a register defined by some
2053    // instruction in the entry block, in which case we shouldn't create an
2054    // entry value.
2055    if (DefinedRegs.count(MI.getDebugOperand(0).getReg()))
2056      return false;
2057  
2058    // TODO: Add support for parameters that have a pre-existing debug expressions
2059    // (e.g. fragments).
2060    if (MI.getDebugExpression()->getNumElements() > 0)
2061      return false;
2062  
2063    return true;
2064  }
2065  
2066  /// Collect all register defines (including aliases) for the given instruction.
2067  static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs,
2068                             const TargetRegisterInfo *TRI) {
2069    for (const MachineOperand &MO : MI.operands())
2070      if (MO.isReg() && MO.isDef() && MO.getReg())
2071        for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
2072          Regs.insert(*AI);
2073  }
2074  
2075  /// This routine records the entry values of function parameters. The values
2076  /// could be used as backup values. If we loose the track of some unmodified
2077  /// parameters, the backup values will be used as a primary locations.
2078  void VarLocBasedLDV::recordEntryValue(const MachineInstr &MI,
2079                                         const DefinedRegsSet &DefinedRegs,
2080                                         OpenRangesSet &OpenRanges,
2081                                         VarLocMap &VarLocIDs) {
2082    if (TPC) {
2083      auto &TM = TPC->getTM<TargetMachine>();
2084      if (!TM.Options.ShouldEmitDebugEntryValues())
2085        return;
2086    }
2087  
2088    DebugVariable V(MI.getDebugVariable(), MI.getDebugExpression(),
2089                    MI.getDebugLoc()->getInlinedAt());
2090  
2091    if (!isEntryValueCandidate(MI, DefinedRegs) ||
2092        OpenRanges.getEntryValueBackup(V))
2093      return;
2094  
2095    LLVM_DEBUG(dbgs() << "Creating the backup entry location: "; MI.dump(););
2096  
2097    // Create the entry value and use it as a backup location until it is
2098    // valid. It is valid until a parameter is not changed.
2099    DIExpression *NewExpr =
2100        DIExpression::prepend(MI.getDebugExpression(), DIExpression::EntryValue);
2101    VarLoc EntryValLocAsBackup = VarLoc::CreateEntryBackupLoc(MI, LS, NewExpr);
2102    LocIndices EntryValLocIDs = VarLocIDs.insert(EntryValLocAsBackup);
2103    OpenRanges.insert(EntryValLocIDs, EntryValLocAsBackup);
2104  }
2105  
2106  /// Calculate the liveness information for the given machine function and
2107  /// extend ranges across basic blocks.
2108  bool VarLocBasedLDV::ExtendRanges(MachineFunction &MF,
2109                                    MachineDominatorTree *DomTree,
2110                                    TargetPassConfig *TPC, unsigned InputBBLimit,
2111                                    unsigned InputDbgValLimit) {
2112    (void)DomTree;
2113    LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
2114  
2115    if (!MF.getFunction().getSubprogram())
2116      // VarLocBaseLDV will already have removed all DBG_VALUEs.
2117      return false;
2118  
2119    // Skip functions from NoDebug compilation units.
2120    if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
2121        DICompileUnit::NoDebug)
2122      return false;
2123  
2124    TRI = MF.getSubtarget().getRegisterInfo();
2125    TII = MF.getSubtarget().getInstrInfo();
2126    TFI = MF.getSubtarget().getFrameLowering();
2127    TFI->getCalleeSaves(MF, CalleeSavedRegs);
2128    this->TPC = TPC;
2129    LS.initialize(MF);
2130  
2131    bool Changed = false;
2132    bool OLChanged = false;
2133    bool MBBJoined = false;
2134  
2135    VarLocMap VarLocIDs;         // Map VarLoc<>unique ID for use in bitvectors.
2136    OverlapMap OverlapFragments; // Map of overlapping variable fragments.
2137    OpenRangesSet OpenRanges(Alloc, OverlapFragments);
2138                                // Ranges that are open until end of bb.
2139    VarLocInMBB OutLocs;        // Ranges that exist beyond bb.
2140    VarLocInMBB InLocs;         // Ranges that are incoming after joining.
2141    TransferMap Transfers;      // DBG_VALUEs associated with transfers (such as
2142                                // spills, copies and restores).
2143    // Map responsible MI to attached Transfer emitted from Backup Entry Value.
2144    InstToEntryLocMap EntryValTransfers;
2145    // Map a Register to the last MI which clobbered it.
2146    RegDefToInstMap RegSetInstrs;
2147  
2148    VarToFragments SeenFragments;
2149  
2150    // Blocks which are artificial, i.e. blocks which exclusively contain
2151    // instructions without locations, or with line 0 locations.
2152    SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
2153  
2154    DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
2155    DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
2156    std::priority_queue<unsigned int, std::vector<unsigned int>,
2157                        std::greater<unsigned int>>
2158        Worklist;
2159    std::priority_queue<unsigned int, std::vector<unsigned int>,
2160                        std::greater<unsigned int>>
2161        Pending;
2162  
2163    // Set of register defines that are seen when traversing the entry block
2164    // looking for debug entry value candidates.
2165    DefinedRegsSet DefinedRegs;
2166  
2167    // Only in the case of entry MBB collect DBG_VALUEs representing
2168    // function parameters in order to generate debug entry values for them.
2169    MachineBasicBlock &First_MBB = *(MF.begin());
2170    for (auto &MI : First_MBB) {
2171      collectRegDefs(MI, DefinedRegs, TRI);
2172      if (MI.isDebugValue())
2173        recordEntryValue(MI, DefinedRegs, OpenRanges, VarLocIDs);
2174    }
2175  
2176    // Initialize per-block structures and scan for fragment overlaps.
2177    for (auto &MBB : MF)
2178      for (auto &MI : MBB)
2179        if (MI.isDebugValue())
2180          accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
2181  
2182    auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
2183      if (const DebugLoc &DL = MI.getDebugLoc())
2184        return DL.getLine() != 0;
2185      return false;
2186    };
2187    for (auto &MBB : MF)
2188      if (none_of(MBB.instrs(), hasNonArtificialLocation))
2189        ArtificialBlocks.insert(&MBB);
2190  
2191    LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
2192                                "OutLocs after initialization", dbgs()));
2193  
2194    ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
2195    unsigned int RPONumber = 0;
2196    for (MachineBasicBlock *MBB : RPOT) {
2197      OrderToBB[RPONumber] = MBB;
2198      BBToOrder[MBB] = RPONumber;
2199      Worklist.push(RPONumber);
2200      ++RPONumber;
2201    }
2202  
2203    if (RPONumber > InputBBLimit) {
2204      unsigned NumInputDbgValues = 0;
2205      for (auto &MBB : MF)
2206        for (auto &MI : MBB)
2207          if (MI.isDebugValue())
2208            ++NumInputDbgValues;
2209      if (NumInputDbgValues > InputDbgValLimit) {
2210        LLVM_DEBUG(dbgs() << "Disabling VarLocBasedLDV: " << MF.getName()
2211                          << " has " << RPONumber << " basic blocks and "
2212                          << NumInputDbgValues
2213                          << " input DBG_VALUEs, exceeding limits.\n");
2214        return false;
2215      }
2216    }
2217  
2218    // This is a standard "union of predecessor outs" dataflow problem.
2219    // To solve it, we perform join() and process() using the two worklist method
2220    // until the ranges converge.
2221    // Ranges have converged when both worklists are empty.
2222    SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2223    while (!Worklist.empty() || !Pending.empty()) {
2224      // We track what is on the pending worklist to avoid inserting the same
2225      // thing twice.  We could avoid this with a custom priority queue, but this
2226      // is probably not worth it.
2227      SmallPtrSet<MachineBasicBlock *, 16> OnPending;
2228      LLVM_DEBUG(dbgs() << "Processing Worklist\n");
2229      while (!Worklist.empty()) {
2230        MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2231        Worklist.pop();
2232        MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
2233                         ArtificialBlocks);
2234        MBBJoined |= Visited.insert(MBB).second;
2235        if (MBBJoined) {
2236          MBBJoined = false;
2237          Changed = true;
2238          // Now that we have started to extend ranges across BBs we need to
2239          // examine spill, copy and restore instructions to see whether they
2240          // operate with registers that correspond to user variables.
2241          // First load any pending inlocs.
2242          OpenRanges.insertFromLocSet(getVarLocsInMBB(MBB, InLocs), VarLocIDs);
2243          LastNonDbgMI = nullptr;
2244          RegSetInstrs.clear();
2245          for (auto &MI : *MBB)
2246            process(MI, OpenRanges, VarLocIDs, Transfers, EntryValTransfers,
2247                    RegSetInstrs);
2248          OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
2249  
2250          LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
2251                                      "OutLocs after propagating", dbgs()));
2252          LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
2253                                      "InLocs after propagating", dbgs()));
2254  
2255          if (OLChanged) {
2256            OLChanged = false;
2257            for (auto s : MBB->successors())
2258              if (OnPending.insert(s).second) {
2259                Pending.push(BBToOrder[s]);
2260              }
2261          }
2262        }
2263      }
2264      Worklist.swap(Pending);
2265      // At this point, pending must be empty, since it was just the empty
2266      // worklist
2267      assert(Pending.empty() && "Pending should be empty");
2268    }
2269  
2270    // Add any DBG_VALUE instructions created by location transfers.
2271    for (auto &TR : Transfers) {
2272      assert(!TR.TransferInst->isTerminator() &&
2273             "Cannot insert DBG_VALUE after terminator");
2274      MachineBasicBlock *MBB = TR.TransferInst->getParent();
2275      const VarLoc &VL = VarLocIDs[TR.LocationID];
2276      MachineInstr *MI = VL.BuildDbgValue(MF);
2277      MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI);
2278    }
2279    Transfers.clear();
2280  
2281    // Add DBG_VALUEs created using Backup Entry Value location.
2282    for (auto &TR : EntryValTransfers) {
2283      MachineInstr *TRInst = const_cast<MachineInstr *>(TR.first);
2284      assert(!TRInst->isTerminator() &&
2285             "Cannot insert DBG_VALUE after terminator");
2286      MachineBasicBlock *MBB = TRInst->getParent();
2287      const VarLoc &VL = VarLocIDs[TR.second];
2288      MachineInstr *MI = VL.BuildDbgValue(MF);
2289      MBB->insertAfterBundle(TRInst->getIterator(), MI);
2290    }
2291    EntryValTransfers.clear();
2292  
2293    // Deferred inlocs will not have had any DBG_VALUE insts created; do
2294    // that now.
2295    flushPendingLocs(InLocs, VarLocIDs);
2296  
2297    LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
2298    LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
2299    return Changed;
2300  }
2301  
2302  LDVImpl *
2303  llvm::makeVarLocBasedLiveDebugValues()
2304  {
2305    return new VarLocBasedLDV();
2306  }
2307