10b57cec5SDimitry Andric //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the LiveDebugVariables analysis.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric // Remove all DBG_VALUE instructions referencing virtual registers and replace
120b57cec5SDimitry Andric // them with a data structure tracking where live user variables are kept - in a
130b57cec5SDimitry Andric // virtual register or in a stack slot.
140b57cec5SDimitry Andric //
150b57cec5SDimitry Andric // Allow the data structure to be updated during register allocation when values
160b57cec5SDimitry Andric // are moved between registers and stack slots. Finally emit new DBG_VALUE
170b57cec5SDimitry Andric // instructions after register allocation is complete.
180b57cec5SDimitry Andric //
190b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
200b57cec5SDimitry Andric 
210b57cec5SDimitry Andric #include "LiveDebugVariables.h"
220b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
230b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
240b57cec5SDimitry Andric #include "llvm/ADT/IntervalMap.h"
250b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
260b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
270b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
280b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
290b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
300b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
420b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
430b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
440b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
450b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
460b57cec5SDimitry Andric #include "llvm/CodeGen/VirtRegMap.h"
470b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
480b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
490b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
500b57cec5SDimitry Andric #include "llvm/IR/Function.h"
510b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
520b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
530b57cec5SDimitry Andric #include "llvm/Pass.h"
540b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
550b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
560b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
570b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
580b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
590b57cec5SDimitry Andric #include <algorithm>
600b57cec5SDimitry Andric #include <cassert>
610b57cec5SDimitry Andric #include <iterator>
620b57cec5SDimitry Andric #include <memory>
630b57cec5SDimitry Andric #include <utility>
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric using namespace llvm;
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric #define DEBUG_TYPE "livedebugvars"
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric static cl::opt<bool>
700b57cec5SDimitry Andric EnableLDV("live-debug-variables", cl::init(true),
710b57cec5SDimitry Andric           cl::desc("Enable the live debug variables pass"), cl::Hidden);
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
740b57cec5SDimitry Andric STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric char LiveDebugVariables::ID = 0;
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
790b57cec5SDimitry Andric                 "Debug Variable Analysis", false, false)
800b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
810b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
820b57cec5SDimitry Andric INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
830b57cec5SDimitry Andric                 "Debug Variable Analysis", false, false)
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
860b57cec5SDimitry Andric   AU.addRequired<MachineDominatorTree>();
870b57cec5SDimitry Andric   AU.addRequiredTransitive<LiveIntervals>();
880b57cec5SDimitry Andric   AU.setPreservesAll();
890b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
900b57cec5SDimitry Andric }
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
930b57cec5SDimitry Andric   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
940b57cec5SDimitry Andric }
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric enum : unsigned { UndefLocNo = ~0U };
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric /// Describes a location by number along with some flags about the original
990b57cec5SDimitry Andric /// usage of the location.
1000b57cec5SDimitry Andric class DbgValueLocation {
1010b57cec5SDimitry Andric public:
1020b57cec5SDimitry Andric   DbgValueLocation(unsigned LocNo, bool WasIndirect)
1030b57cec5SDimitry Andric       : LocNo(LocNo), WasIndirect(WasIndirect) {
1040b57cec5SDimitry Andric     static_assert(sizeof(*this) == sizeof(unsigned), "bad bitfield packing");
1050b57cec5SDimitry Andric     assert(locNo() == LocNo && "location truncation");
1060b57cec5SDimitry Andric   }
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   DbgValueLocation() : LocNo(0), WasIndirect(0) {}
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   unsigned locNo() const {
1110b57cec5SDimitry Andric     // Fix up the undef location number, which gets truncated.
1120b57cec5SDimitry Andric     return LocNo == INT_MAX ? UndefLocNo : LocNo;
1130b57cec5SDimitry Andric   }
1140b57cec5SDimitry Andric   bool wasIndirect() const { return WasIndirect; }
1150b57cec5SDimitry Andric   bool isUndef() const { return locNo() == UndefLocNo; }
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   DbgValueLocation changeLocNo(unsigned NewLocNo) const {
1180b57cec5SDimitry Andric     return DbgValueLocation(NewLocNo, WasIndirect);
1190b57cec5SDimitry Andric   }
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   friend inline bool operator==(const DbgValueLocation &LHS,
1220b57cec5SDimitry Andric                                 const DbgValueLocation &RHS) {
1230b57cec5SDimitry Andric     return LHS.LocNo == RHS.LocNo && LHS.WasIndirect == RHS.WasIndirect;
1240b57cec5SDimitry Andric   }
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric   friend inline bool operator!=(const DbgValueLocation &LHS,
1270b57cec5SDimitry Andric                                 const DbgValueLocation &RHS) {
1280b57cec5SDimitry Andric     return !(LHS == RHS);
1290b57cec5SDimitry Andric   }
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric private:
1320b57cec5SDimitry Andric   unsigned LocNo : 31;
1330b57cec5SDimitry Andric   unsigned WasIndirect : 1;
1340b57cec5SDimitry Andric };
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric /// Map of where a user value is live, and its location.
1370b57cec5SDimitry Andric using LocMap = IntervalMap<SlotIndex, DbgValueLocation, 4>;
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric /// Map of stack slot offsets for spilled locations.
1400b57cec5SDimitry Andric /// Non-spilled locations are not added to the map.
1410b57cec5SDimitry Andric using SpillOffsetMap = DenseMap<unsigned, unsigned>;
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric namespace {
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric class LDVImpl;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric /// A user value is a part of a debug info user variable.
1480b57cec5SDimitry Andric ///
1490b57cec5SDimitry Andric /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
1500b57cec5SDimitry Andric /// holds part of a user variable. The part is identified by a byte offset.
1510b57cec5SDimitry Andric ///
1520b57cec5SDimitry Andric /// UserValues are grouped into equivalence classes for easier searching. Two
1530b57cec5SDimitry Andric /// user values are related if they refer to the same variable, or if they are
1540b57cec5SDimitry Andric /// held by the same virtual register. The equivalence class is the transitive
1550b57cec5SDimitry Andric /// closure of that relation.
1560b57cec5SDimitry Andric class UserValue {
1570b57cec5SDimitry Andric   const DILocalVariable *Variable; ///< The debug info variable we are part of.
1580b57cec5SDimitry Andric   const DIExpression *Expression; ///< Any complex address expression.
1590b57cec5SDimitry Andric   DebugLoc dl;            ///< The debug location for the variable. This is
1600b57cec5SDimitry Andric                           ///< used by dwarf writer to find lexical scope.
1610b57cec5SDimitry Andric   UserValue *leader;      ///< Equivalence class leader.
1620b57cec5SDimitry Andric   UserValue *next = nullptr; ///< Next value in equivalence class, or null.
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   /// Numbered locations referenced by locmap.
1650b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> locations;
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric   /// Map of slot indices where this value is live.
1680b57cec5SDimitry Andric   LocMap locInts;
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   /// Insert a DBG_VALUE into MBB at Idx for LocNo.
1710b57cec5SDimitry Andric   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1720b57cec5SDimitry Andric                         SlotIndex StopIdx, DbgValueLocation Loc, bool Spilled,
1730b57cec5SDimitry Andric                         unsigned SpillOffset, LiveIntervals &LIS,
1740b57cec5SDimitry Andric                         const TargetInstrInfo &TII,
1750b57cec5SDimitry Andric                         const TargetRegisterInfo &TRI);
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
1780b57cec5SDimitry Andric   /// is live. Returns true if any changes were made.
1790b57cec5SDimitry Andric   bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
1800b57cec5SDimitry Andric                      LiveIntervals &LIS);
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric public:
1830b57cec5SDimitry Andric   /// Create a new UserValue.
1840b57cec5SDimitry Andric   UserValue(const DILocalVariable *var, const DIExpression *expr, DebugLoc L,
1850b57cec5SDimitry Andric             LocMap::Allocator &alloc)
1860b57cec5SDimitry Andric       : Variable(var), Expression(expr), dl(std::move(L)), leader(this),
1870b57cec5SDimitry Andric         locInts(alloc) {}
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric   /// Get the leader of this value's equivalence class.
1900b57cec5SDimitry Andric   UserValue *getLeader() {
1910b57cec5SDimitry Andric     UserValue *l = leader;
1920b57cec5SDimitry Andric     while (l != l->leader)
1930b57cec5SDimitry Andric       l = l->leader;
1940b57cec5SDimitry Andric     return leader = l;
1950b57cec5SDimitry Andric   }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   /// Return the next UserValue in the equivalence class.
1980b57cec5SDimitry Andric   UserValue *getNext() const { return next; }
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   /// Does this UserValue match the parameters?
2010b57cec5SDimitry Andric   bool match(const DILocalVariable *Var, const DIExpression *Expr,
2020b57cec5SDimitry Andric              const DILocation *IA) const {
2030b57cec5SDimitry Andric     // FIXME: The fragment should be part of the equivalence class, but not
2040b57cec5SDimitry Andric     // other things in the expression like stack values.
2050b57cec5SDimitry Andric     return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA;
2060b57cec5SDimitry Andric   }
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   /// Merge equivalence classes.
2090b57cec5SDimitry Andric   static UserValue *merge(UserValue *L1, UserValue *L2) {
2100b57cec5SDimitry Andric     L2 = L2->getLeader();
2110b57cec5SDimitry Andric     if (!L1)
2120b57cec5SDimitry Andric       return L2;
2130b57cec5SDimitry Andric     L1 = L1->getLeader();
2140b57cec5SDimitry Andric     if (L1 == L2)
2150b57cec5SDimitry Andric       return L1;
2160b57cec5SDimitry Andric     // Splice L2 before L1's members.
2170b57cec5SDimitry Andric     UserValue *End = L2;
2180b57cec5SDimitry Andric     while (End->next) {
2190b57cec5SDimitry Andric       End->leader = L1;
2200b57cec5SDimitry Andric       End = End->next;
2210b57cec5SDimitry Andric     }
2220b57cec5SDimitry Andric     End->leader = L1;
2230b57cec5SDimitry Andric     End->next = L1->next;
2240b57cec5SDimitry Andric     L1->next = L2;
2250b57cec5SDimitry Andric     return L1;
2260b57cec5SDimitry Andric   }
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   /// Return the location number that matches Loc.
2290b57cec5SDimitry Andric   ///
2300b57cec5SDimitry Andric   /// For undef values we always return location number UndefLocNo without
2310b57cec5SDimitry Andric   /// inserting anything in locations. Since locations is a vector and the
2320b57cec5SDimitry Andric   /// location number is the position in the vector and UndefLocNo is ~0,
2330b57cec5SDimitry Andric   /// we would need a very big vector to put the value at the right position.
2340b57cec5SDimitry Andric   unsigned getLocationNo(const MachineOperand &LocMO) {
2350b57cec5SDimitry Andric     if (LocMO.isReg()) {
2360b57cec5SDimitry Andric       if (LocMO.getReg() == 0)
2370b57cec5SDimitry Andric         return UndefLocNo;
2380b57cec5SDimitry Andric       // For register locations we dont care about use/def and other flags.
2390b57cec5SDimitry Andric       for (unsigned i = 0, e = locations.size(); i != e; ++i)
2400b57cec5SDimitry Andric         if (locations[i].isReg() &&
2410b57cec5SDimitry Andric             locations[i].getReg() == LocMO.getReg() &&
2420b57cec5SDimitry Andric             locations[i].getSubReg() == LocMO.getSubReg())
2430b57cec5SDimitry Andric           return i;
2440b57cec5SDimitry Andric     } else
2450b57cec5SDimitry Andric       for (unsigned i = 0, e = locations.size(); i != e; ++i)
2460b57cec5SDimitry Andric         if (LocMO.isIdenticalTo(locations[i]))
2470b57cec5SDimitry Andric           return i;
2480b57cec5SDimitry Andric     locations.push_back(LocMO);
2490b57cec5SDimitry Andric     // We are storing a MachineOperand outside a MachineInstr.
2500b57cec5SDimitry Andric     locations.back().clearParent();
2510b57cec5SDimitry Andric     // Don't store def operands.
2520b57cec5SDimitry Andric     if (locations.back().isReg()) {
2530b57cec5SDimitry Andric       if (locations.back().isDef())
2540b57cec5SDimitry Andric         locations.back().setIsDead(false);
2550b57cec5SDimitry Andric       locations.back().setIsUse();
2560b57cec5SDimitry Andric     }
2570b57cec5SDimitry Andric     return locations.size() - 1;
2580b57cec5SDimitry Andric   }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   /// Ensure that all virtual register locations are mapped.
2610b57cec5SDimitry Andric   void mapVirtRegs(LDVImpl *LDV);
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   /// Add a definition point to this value.
2640b57cec5SDimitry Andric   void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect) {
2650b57cec5SDimitry Andric     DbgValueLocation Loc(getLocationNo(LocMO), IsIndirect);
2660b57cec5SDimitry Andric     // Add a singular (Idx,Idx) -> Loc mapping.
2670b57cec5SDimitry Andric     LocMap::iterator I = locInts.find(Idx);
2680b57cec5SDimitry Andric     if (!I.valid() || I.start() != Idx)
2690b57cec5SDimitry Andric       I.insert(Idx, Idx.getNextSlot(), Loc);
2700b57cec5SDimitry Andric     else
2710b57cec5SDimitry Andric       // A later DBG_VALUE at the same SlotIndex overrides the old location.
2720b57cec5SDimitry Andric       I.setValue(Loc);
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   /// Extend the current definition as far as possible down.
2760b57cec5SDimitry Andric   ///
2770b57cec5SDimitry Andric   /// Stop when meeting an existing def or when leaving the live
2780b57cec5SDimitry Andric   /// range of VNI. End points where VNI is no longer live are added to Kills.
2790b57cec5SDimitry Andric   ///
2800b57cec5SDimitry Andric   /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
2810b57cec5SDimitry Andric   /// data-flow analysis to propagate them beyond basic block boundaries.
2820b57cec5SDimitry Andric   ///
2830b57cec5SDimitry Andric   /// \param Idx Starting point for the definition.
2840b57cec5SDimitry Andric   /// \param Loc Location number to propagate.
2850b57cec5SDimitry Andric   /// \param LR Restrict liveness to where LR has the value VNI. May be null.
2860b57cec5SDimitry Andric   /// \param VNI When LR is not null, this is the value to restrict to.
2870b57cec5SDimitry Andric   /// \param [out] Kills Append end points of VNI's live range to Kills.
2880b57cec5SDimitry Andric   /// \param LIS Live intervals analysis.
2890b57cec5SDimitry Andric   void extendDef(SlotIndex Idx, DbgValueLocation Loc,
2900b57cec5SDimitry Andric                  LiveRange *LR, const VNInfo *VNI,
2910b57cec5SDimitry Andric                  SmallVectorImpl<SlotIndex> *Kills,
2920b57cec5SDimitry Andric                  LiveIntervals &LIS);
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   /// The value in LI/LocNo may be copies to other registers. Determine if
2950b57cec5SDimitry Andric   /// any of the copies are available at the kill points, and add defs if
2960b57cec5SDimitry Andric   /// possible.
2970b57cec5SDimitry Andric   ///
2980b57cec5SDimitry Andric   /// \param LI Scan for copies of the value in LI->reg.
2990b57cec5SDimitry Andric   /// \param LocNo Location number of LI->reg.
3000b57cec5SDimitry Andric   /// \param WasIndirect Indicates if the original use of LI->reg was indirect
3010b57cec5SDimitry Andric   /// \param Kills Points where the range of LocNo could be extended.
3020b57cec5SDimitry Andric   /// \param [in,out] NewDefs Append (Idx, LocNo) of inserted defs here.
3030b57cec5SDimitry Andric   void addDefsFromCopies(
3040b57cec5SDimitry Andric       LiveInterval *LI, unsigned LocNo, bool WasIndirect,
3050b57cec5SDimitry Andric       const SmallVectorImpl<SlotIndex> &Kills,
3060b57cec5SDimitry Andric       SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
3070b57cec5SDimitry Andric       MachineRegisterInfo &MRI, LiveIntervals &LIS);
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric   /// Compute the live intervals of all locations after collecting all their
3100b57cec5SDimitry Andric   /// def points.
3110b57cec5SDimitry Andric   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
3120b57cec5SDimitry Andric                         LiveIntervals &LIS, LexicalScopes &LS);
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   /// Replace OldReg ranges with NewRegs ranges where NewRegs is
3150b57cec5SDimitry Andric   /// live. Returns true if any changes were made.
3160b57cec5SDimitry Andric   bool splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
3170b57cec5SDimitry Andric                      LiveIntervals &LIS);
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   /// Rewrite virtual register locations according to the provided virtual
3200b57cec5SDimitry Andric   /// register map. Record the stack slot offsets for the locations that
3210b57cec5SDimitry Andric   /// were spilled.
3220b57cec5SDimitry Andric   void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
3230b57cec5SDimitry Andric                         const TargetInstrInfo &TII,
3240b57cec5SDimitry Andric                         const TargetRegisterInfo &TRI,
3250b57cec5SDimitry Andric                         SpillOffsetMap &SpillOffsets);
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   /// Recreate DBG_VALUE instruction from data structures.
3280b57cec5SDimitry Andric   void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
3290b57cec5SDimitry Andric                        const TargetInstrInfo &TII,
3300b57cec5SDimitry Andric                        const TargetRegisterInfo &TRI,
3310b57cec5SDimitry Andric                        const SpillOffsetMap &SpillOffsets);
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric   /// Return DebugLoc of this UserValue.
3340b57cec5SDimitry Andric   DebugLoc getDebugLoc() { return dl;}
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   void print(raw_ostream &, const TargetRegisterInfo *);
3370b57cec5SDimitry Andric };
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric /// A user label is a part of a debug info user label.
3400b57cec5SDimitry Andric class UserLabel {
3410b57cec5SDimitry Andric   const DILabel *Label; ///< The debug info label we are part of.
3420b57cec5SDimitry Andric   DebugLoc dl;          ///< The debug location for the label. This is
3430b57cec5SDimitry Andric                         ///< used by dwarf writer to find lexical scope.
3440b57cec5SDimitry Andric   SlotIndex loc;        ///< Slot used by the debug label.
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   /// Insert a DBG_LABEL into MBB at Idx.
3470b57cec5SDimitry Andric   void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
3480b57cec5SDimitry Andric                         LiveIntervals &LIS, const TargetInstrInfo &TII);
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric public:
3510b57cec5SDimitry Andric   /// Create a new UserLabel.
3520b57cec5SDimitry Andric   UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
3530b57cec5SDimitry Andric       : Label(label), dl(std::move(L)), loc(Idx) {}
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   /// Does this UserLabel match the parameters?
3560b57cec5SDimitry Andric   bool match(const DILabel *L, const DILocation *IA,
3570b57cec5SDimitry Andric              const SlotIndex Index) const {
3580b57cec5SDimitry Andric     return Label == L && dl->getInlinedAt() == IA && loc == Index;
3590b57cec5SDimitry Andric   }
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   /// Recreate DBG_LABEL instruction from data structures.
3620b57cec5SDimitry Andric   void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII);
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   /// Return DebugLoc of this UserLabel.
3650b57cec5SDimitry Andric   DebugLoc getDebugLoc() { return dl; }
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   void print(raw_ostream &, const TargetRegisterInfo *);
3680b57cec5SDimitry Andric };
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric /// Implementation of the LiveDebugVariables pass.
3710b57cec5SDimitry Andric class LDVImpl {
3720b57cec5SDimitry Andric   LiveDebugVariables &pass;
3730b57cec5SDimitry Andric   LocMap::Allocator allocator;
3740b57cec5SDimitry Andric   MachineFunction *MF = nullptr;
3750b57cec5SDimitry Andric   LiveIntervals *LIS;
3760b57cec5SDimitry Andric   const TargetRegisterInfo *TRI;
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   /// Whether emitDebugValues is called.
3790b57cec5SDimitry Andric   bool EmitDone = false;
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric   /// Whether the machine function is modified during the pass.
3820b57cec5SDimitry Andric   bool ModifiedMF = false;
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric   /// All allocated UserValue instances.
3850b57cec5SDimitry Andric   SmallVector<std::unique_ptr<UserValue>, 8> userValues;
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric   /// All allocated UserLabel instances.
3880b57cec5SDimitry Andric   SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   /// Map virtual register to eq class leader.
3910b57cec5SDimitry Andric   using VRMap = DenseMap<unsigned, UserValue *>;
3920b57cec5SDimitry Andric   VRMap virtRegToEqClass;
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   /// Map user variable to eq class leader.
3950b57cec5SDimitry Andric   using UVMap = DenseMap<const DILocalVariable *, UserValue *>;
3960b57cec5SDimitry Andric   UVMap userVarMap;
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric   /// Find or create a UserValue.
3990b57cec5SDimitry Andric   UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr,
4000b57cec5SDimitry Andric                           const DebugLoc &DL);
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   /// Find the EC leader for VirtReg or null.
4030b57cec5SDimitry Andric   UserValue *lookupVirtReg(unsigned VirtReg);
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   /// Add DBG_VALUE instruction to our maps.
4060b57cec5SDimitry Andric   ///
4070b57cec5SDimitry Andric   /// \param MI DBG_VALUE instruction
4080b57cec5SDimitry Andric   /// \param Idx Last valid SLotIndex before instruction.
4090b57cec5SDimitry Andric   ///
4100b57cec5SDimitry Andric   /// \returns True if the DBG_VALUE instruction should be deleted.
4110b57cec5SDimitry Andric   bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   /// Add DBG_LABEL instruction to UserLabel.
4140b57cec5SDimitry Andric   ///
4150b57cec5SDimitry Andric   /// \param MI DBG_LABEL instruction
4160b57cec5SDimitry Andric   /// \param Idx Last valid SlotIndex before instruction.
4170b57cec5SDimitry Andric   ///
4180b57cec5SDimitry Andric   /// \returns True if the DBG_LABEL instruction should be deleted.
4190b57cec5SDimitry Andric   bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
4220b57cec5SDimitry Andric   /// for each instruction.
4230b57cec5SDimitry Andric   ///
4240b57cec5SDimitry Andric   /// \param mf MachineFunction to be scanned.
4250b57cec5SDimitry Andric   ///
4260b57cec5SDimitry Andric   /// \returns True if any debug values were found.
4270b57cec5SDimitry Andric   bool collectDebugValues(MachineFunction &mf);
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   /// Compute the live intervals of all user values after collecting all
4300b57cec5SDimitry Andric   /// their def points.
4310b57cec5SDimitry Andric   void computeIntervals();
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric public:
4340b57cec5SDimitry Andric   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &mf);
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   /// Release all memory.
4390b57cec5SDimitry Andric   void clear() {
4400b57cec5SDimitry Andric     MF = nullptr;
4410b57cec5SDimitry Andric     userValues.clear();
4420b57cec5SDimitry Andric     userLabels.clear();
4430b57cec5SDimitry Andric     virtRegToEqClass.clear();
4440b57cec5SDimitry Andric     userVarMap.clear();
4450b57cec5SDimitry Andric     // Make sure we call emitDebugValues if the machine function was modified.
4460b57cec5SDimitry Andric     assert((!ModifiedMF || EmitDone) &&
4470b57cec5SDimitry Andric            "Dbg values are not emitted in LDV");
4480b57cec5SDimitry Andric     EmitDone = false;
4490b57cec5SDimitry Andric     ModifiedMF = false;
4500b57cec5SDimitry Andric   }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   /// Map virtual register to an equivalence class.
4530b57cec5SDimitry Andric   void mapVirtReg(unsigned VirtReg, UserValue *EC);
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric   /// Replace all references to OldReg with NewRegs.
4560b57cec5SDimitry Andric   void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric   /// Recreate DBG_VALUE instruction from data structures.
4590b57cec5SDimitry Andric   void emitDebugValues(VirtRegMap *VRM);
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric   void print(raw_ostream&);
4620b57cec5SDimitry Andric };
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric } // end anonymous namespace
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4670b57cec5SDimitry Andric static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
4680b57cec5SDimitry Andric                           const LLVMContext &Ctx) {
4690b57cec5SDimitry Andric   if (!DL)
4700b57cec5SDimitry Andric     return;
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   auto *Scope = cast<DIScope>(DL.getScope());
4730b57cec5SDimitry Andric   // Omit the directory, because it's likely to be long and uninteresting.
4740b57cec5SDimitry Andric   CommentOS << Scope->getFilename();
4750b57cec5SDimitry Andric   CommentOS << ':' << DL.getLine();
4760b57cec5SDimitry Andric   if (DL.getCol() != 0)
4770b57cec5SDimitry Andric     CommentOS << ':' << DL.getCol();
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   DebugLoc InlinedAtDL = DL.getInlinedAt();
4800b57cec5SDimitry Andric   if (!InlinedAtDL)
4810b57cec5SDimitry Andric     return;
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   CommentOS << " @[ ";
4840b57cec5SDimitry Andric   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
4850b57cec5SDimitry Andric   CommentOS << " ]";
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric static void printExtendedName(raw_ostream &OS, const DINode *Node,
4890b57cec5SDimitry Andric                               const DILocation *DL) {
4900b57cec5SDimitry Andric   const LLVMContext &Ctx = Node->getContext();
4910b57cec5SDimitry Andric   StringRef Res;
4920b57cec5SDimitry Andric   unsigned Line;
4930b57cec5SDimitry Andric   if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
4940b57cec5SDimitry Andric     Res = V->getName();
4950b57cec5SDimitry Andric     Line = V->getLine();
4960b57cec5SDimitry Andric   } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
4970b57cec5SDimitry Andric     Res = L->getName();
4980b57cec5SDimitry Andric     Line = L->getLine();
4990b57cec5SDimitry Andric   }
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric   if (!Res.empty())
5020b57cec5SDimitry Andric     OS << Res << "," << Line;
5030b57cec5SDimitry Andric   auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
5040b57cec5SDimitry Andric   if (InlinedAt) {
5050b57cec5SDimitry Andric     if (DebugLoc InlinedAtDL = InlinedAt) {
5060b57cec5SDimitry Andric       OS << " @[";
5070b57cec5SDimitry Andric       printDebugLoc(InlinedAtDL, OS, Ctx);
5080b57cec5SDimitry Andric       OS << "]";
5090b57cec5SDimitry Andric     }
5100b57cec5SDimitry Andric   }
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
5140b57cec5SDimitry Andric   OS << "!\"";
5150b57cec5SDimitry Andric   printExtendedName(OS, Variable, dl);
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   OS << "\"\t";
5180b57cec5SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
5190b57cec5SDimitry Andric     OS << " [" << I.start() << ';' << I.stop() << "):";
5200b57cec5SDimitry Andric     if (I.value().isUndef())
5210b57cec5SDimitry Andric       OS << "undef";
5220b57cec5SDimitry Andric     else {
5230b57cec5SDimitry Andric       OS << I.value().locNo();
5240b57cec5SDimitry Andric       if (I.value().wasIndirect())
5250b57cec5SDimitry Andric         OS << " ind";
5260b57cec5SDimitry Andric     }
5270b57cec5SDimitry Andric   }
5280b57cec5SDimitry Andric   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
5290b57cec5SDimitry Andric     OS << " Loc" << i << '=';
5300b57cec5SDimitry Andric     locations[i].print(OS, TRI);
5310b57cec5SDimitry Andric   }
5320b57cec5SDimitry Andric   OS << '\n';
5330b57cec5SDimitry Andric }
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
5360b57cec5SDimitry Andric   OS << "!\"";
5370b57cec5SDimitry Andric   printExtendedName(OS, Label, dl);
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric   OS << "\"\t";
5400b57cec5SDimitry Andric   OS << loc;
5410b57cec5SDimitry Andric   OS << '\n';
5420b57cec5SDimitry Andric }
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric void LDVImpl::print(raw_ostream &OS) {
5450b57cec5SDimitry Andric   OS << "********** DEBUG VARIABLES **********\n";
5460b57cec5SDimitry Andric   for (auto &userValue : userValues)
5470b57cec5SDimitry Andric     userValue->print(OS, TRI);
5480b57cec5SDimitry Andric   OS << "********** DEBUG LABELS **********\n";
5490b57cec5SDimitry Andric   for (auto &userLabel : userLabels)
5500b57cec5SDimitry Andric     userLabel->print(OS, TRI);
5510b57cec5SDimitry Andric }
5520b57cec5SDimitry Andric #endif
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric void UserValue::mapVirtRegs(LDVImpl *LDV) {
5550b57cec5SDimitry Andric   for (unsigned i = 0, e = locations.size(); i != e; ++i)
5560b57cec5SDimitry Andric     if (locations[i].isReg() &&
5570b57cec5SDimitry Andric         TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
5580b57cec5SDimitry Andric       LDV->mapVirtReg(locations[i].getReg(), this);
5590b57cec5SDimitry Andric }
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
5620b57cec5SDimitry Andric                                  const DIExpression *Expr, const DebugLoc &DL) {
5630b57cec5SDimitry Andric   UserValue *&Leader = userVarMap[Var];
5640b57cec5SDimitry Andric   if (Leader) {
5650b57cec5SDimitry Andric     UserValue *UV = Leader->getLeader();
5660b57cec5SDimitry Andric     Leader = UV;
5670b57cec5SDimitry Andric     for (; UV; UV = UV->getNext())
5680b57cec5SDimitry Andric       if (UV->match(Var, Expr, DL->getInlinedAt()))
5690b57cec5SDimitry Andric         return UV;
5700b57cec5SDimitry Andric   }
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   userValues.push_back(
5730b57cec5SDimitry Andric       llvm::make_unique<UserValue>(Var, Expr, DL, allocator));
5740b57cec5SDimitry Andric   UserValue *UV = userValues.back().get();
5750b57cec5SDimitry Andric   Leader = UserValue::merge(Leader, UV);
5760b57cec5SDimitry Andric   return UV;
5770b57cec5SDimitry Andric }
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
5800b57cec5SDimitry Andric   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
5810b57cec5SDimitry Andric   UserValue *&Leader = virtRegToEqClass[VirtReg];
5820b57cec5SDimitry Andric   Leader = UserValue::merge(Leader, EC);
5830b57cec5SDimitry Andric }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
5860b57cec5SDimitry Andric   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
5870b57cec5SDimitry Andric     return UV->getLeader();
5880b57cec5SDimitry Andric   return nullptr;
5890b57cec5SDimitry Andric }
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
5920b57cec5SDimitry Andric   // DBG_VALUE loc, offset, variable
5930b57cec5SDimitry Andric   if (MI.getNumOperands() != 4 ||
5940b57cec5SDimitry Andric       !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
5950b57cec5SDimitry Andric       !MI.getOperand(2).isMetadata()) {
5960b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle " << MI);
5970b57cec5SDimitry Andric     return false;
5980b57cec5SDimitry Andric   }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric   // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
6010b57cec5SDimitry Andric   // register that hasn't been defined yet. If we do not remove those here, then
6020b57cec5SDimitry Andric   // the re-insertion of the DBG_VALUE instruction after register allocation
6030b57cec5SDimitry Andric   // will be incorrect.
6040b57cec5SDimitry Andric   // TODO: If earlier passes are corrected to generate sane debug information
6050b57cec5SDimitry Andric   // (and if the machine verifier is improved to catch this), then these checks
6060b57cec5SDimitry Andric   // could be removed or replaced by asserts.
6070b57cec5SDimitry Andric   bool Discard = false;
6080b57cec5SDimitry Andric   if (MI.getOperand(0).isReg() &&
6090b57cec5SDimitry Andric       TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg())) {
6100b57cec5SDimitry Andric     const unsigned Reg = MI.getOperand(0).getReg();
6110b57cec5SDimitry Andric     if (!LIS->hasInterval(Reg)) {
6120b57cec5SDimitry Andric       // The DBG_VALUE is described by a virtual register that does not have a
6130b57cec5SDimitry Andric       // live interval. Discard the DBG_VALUE.
6140b57cec5SDimitry Andric       Discard = true;
6150b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
6160b57cec5SDimitry Andric                         << " " << MI);
6170b57cec5SDimitry Andric     } else {
6180b57cec5SDimitry Andric       // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
6190b57cec5SDimitry Andric       // is defined dead at Idx (where Idx is the slot index for the instruction
6200b57cec5SDimitry Andric       // preceding the DBG_VALUE).
6210b57cec5SDimitry Andric       const LiveInterval &LI = LIS->getInterval(Reg);
6220b57cec5SDimitry Andric       LiveQueryResult LRQ = LI.Query(Idx);
6230b57cec5SDimitry Andric       if (!LRQ.valueOutOrDead()) {
6240b57cec5SDimitry Andric         // We have found a DBG_VALUE with the value in a virtual register that
6250b57cec5SDimitry Andric         // is not live. Discard the DBG_VALUE.
6260b57cec5SDimitry Andric         Discard = true;
6270b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
6280b57cec5SDimitry Andric                           << " " << MI);
6290b57cec5SDimitry Andric       }
6300b57cec5SDimitry Andric     }
6310b57cec5SDimitry Andric   }
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   // Get or create the UserValue for (variable,offset) here.
6340b57cec5SDimitry Andric   bool IsIndirect = MI.getOperand(1).isImm();
6350b57cec5SDimitry Andric   if (IsIndirect)
6360b57cec5SDimitry Andric     assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
6370b57cec5SDimitry Andric   const DILocalVariable *Var = MI.getDebugVariable();
6380b57cec5SDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
6390b57cec5SDimitry Andric   UserValue *UV =
6400b57cec5SDimitry Andric       getUserValue(Var, Expr, MI.getDebugLoc());
6410b57cec5SDimitry Andric   if (!Discard)
6420b57cec5SDimitry Andric     UV->addDef(Idx, MI.getOperand(0), IsIndirect);
6430b57cec5SDimitry Andric   else {
6440b57cec5SDimitry Andric     MachineOperand MO = MachineOperand::CreateReg(0U, false);
6450b57cec5SDimitry Andric     MO.setIsDebug();
6460b57cec5SDimitry Andric     UV->addDef(Idx, MO, false);
6470b57cec5SDimitry Andric   }
6480b57cec5SDimitry Andric   return true;
6490b57cec5SDimitry Andric }
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
6520b57cec5SDimitry Andric   // DBG_LABEL label
6530b57cec5SDimitry Andric   if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
6540b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle " << MI);
6550b57cec5SDimitry Andric     return false;
6560b57cec5SDimitry Andric   }
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   // Get or create the UserLabel for label here.
6590b57cec5SDimitry Andric   const DILabel *Label = MI.getDebugLabel();
6600b57cec5SDimitry Andric   const DebugLoc &DL = MI.getDebugLoc();
6610b57cec5SDimitry Andric   bool Found = false;
6620b57cec5SDimitry Andric   for (auto const &L : userLabels) {
6630b57cec5SDimitry Andric     if (L->match(Label, DL->getInlinedAt(), Idx)) {
6640b57cec5SDimitry Andric       Found = true;
6650b57cec5SDimitry Andric       break;
6660b57cec5SDimitry Andric     }
6670b57cec5SDimitry Andric   }
6680b57cec5SDimitry Andric   if (!Found)
6690b57cec5SDimitry Andric     userLabels.push_back(llvm::make_unique<UserLabel>(Label, DL, Idx));
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   return true;
6720b57cec5SDimitry Andric }
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric bool LDVImpl::collectDebugValues(MachineFunction &mf) {
6750b57cec5SDimitry Andric   bool Changed = false;
6760b57cec5SDimitry Andric   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
6770b57cec5SDimitry Andric        ++MFI) {
6780b57cec5SDimitry Andric     MachineBasicBlock *MBB = &*MFI;
6790b57cec5SDimitry Andric     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
6800b57cec5SDimitry Andric          MBBI != MBBE;) {
6810b57cec5SDimitry Andric       // Use the first debug instruction in the sequence to get a SlotIndex
6820b57cec5SDimitry Andric       // for following consecutive debug instructions.
6830b57cec5SDimitry Andric       if (!MBBI->isDebugInstr()) {
6840b57cec5SDimitry Andric         ++MBBI;
6850b57cec5SDimitry Andric         continue;
6860b57cec5SDimitry Andric       }
6870b57cec5SDimitry Andric       // Debug instructions has no slot index. Use the previous
6880b57cec5SDimitry Andric       // non-debug instruction's SlotIndex as its SlotIndex.
6890b57cec5SDimitry Andric       SlotIndex Idx =
6900b57cec5SDimitry Andric           MBBI == MBB->begin()
6910b57cec5SDimitry Andric               ? LIS->getMBBStartIdx(MBB)
6920b57cec5SDimitry Andric               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
6930b57cec5SDimitry Andric       // Handle consecutive debug instructions with the same slot index.
6940b57cec5SDimitry Andric       do {
6950b57cec5SDimitry Andric         // Only handle DBG_VALUE in handleDebugValue(). Skip all other
6960b57cec5SDimitry Andric         // kinds of debug instructions.
6970b57cec5SDimitry Andric         if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
6980b57cec5SDimitry Andric             (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
6990b57cec5SDimitry Andric           MBBI = MBB->erase(MBBI);
7000b57cec5SDimitry Andric           Changed = true;
7010b57cec5SDimitry Andric         } else
7020b57cec5SDimitry Andric           ++MBBI;
7030b57cec5SDimitry Andric       } while (MBBI != MBBE && MBBI->isDebugInstr());
7040b57cec5SDimitry Andric     }
7050b57cec5SDimitry Andric   }
7060b57cec5SDimitry Andric   return Changed;
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric void UserValue::extendDef(SlotIndex Idx, DbgValueLocation Loc, LiveRange *LR,
7100b57cec5SDimitry Andric                           const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
7110b57cec5SDimitry Andric                           LiveIntervals &LIS) {
7120b57cec5SDimitry Andric   SlotIndex Start = Idx;
7130b57cec5SDimitry Andric   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
7140b57cec5SDimitry Andric   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
7150b57cec5SDimitry Andric   LocMap::iterator I = locInts.find(Start);
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric   // Limit to VNI's live range.
7180b57cec5SDimitry Andric   bool ToEnd = true;
7190b57cec5SDimitry Andric   if (LR && VNI) {
7200b57cec5SDimitry Andric     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
7210b57cec5SDimitry Andric     if (!Segment || Segment->valno != VNI) {
7220b57cec5SDimitry Andric       if (Kills)
7230b57cec5SDimitry Andric         Kills->push_back(Start);
7240b57cec5SDimitry Andric       return;
7250b57cec5SDimitry Andric     }
7260b57cec5SDimitry Andric     if (Segment->end < Stop) {
7270b57cec5SDimitry Andric       Stop = Segment->end;
7280b57cec5SDimitry Andric       ToEnd = false;
7290b57cec5SDimitry Andric     }
7300b57cec5SDimitry Andric   }
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric   // There could already be a short def at Start.
7330b57cec5SDimitry Andric   if (I.valid() && I.start() <= Start) {
7340b57cec5SDimitry Andric     // Stop when meeting a different location or an already extended interval.
7350b57cec5SDimitry Andric     Start = Start.getNextSlot();
7360b57cec5SDimitry Andric     if (I.value() != Loc || I.stop() != Start)
7370b57cec5SDimitry Andric       return;
7380b57cec5SDimitry Andric     // This is a one-slot placeholder. Just skip it.
7390b57cec5SDimitry Andric     ++I;
7400b57cec5SDimitry Andric   }
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric   // Limited by the next def.
7430b57cec5SDimitry Andric   if (I.valid() && I.start() < Stop)
7440b57cec5SDimitry Andric     Stop = I.start();
7450b57cec5SDimitry Andric   // Limited by VNI's live range.
7460b57cec5SDimitry Andric   else if (!ToEnd && Kills)
7470b57cec5SDimitry Andric     Kills->push_back(Stop);
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric   if (Start < Stop)
7500b57cec5SDimitry Andric     I.insert(Start, Stop, Loc);
7510b57cec5SDimitry Andric }
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric void UserValue::addDefsFromCopies(
7540b57cec5SDimitry Andric     LiveInterval *LI, unsigned LocNo, bool WasIndirect,
7550b57cec5SDimitry Andric     const SmallVectorImpl<SlotIndex> &Kills,
7560b57cec5SDimitry Andric     SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs,
7570b57cec5SDimitry Andric     MachineRegisterInfo &MRI, LiveIntervals &LIS) {
7580b57cec5SDimitry Andric   if (Kills.empty())
7590b57cec5SDimitry Andric     return;
7600b57cec5SDimitry Andric   // Don't track copies from physregs, there are too many uses.
7610b57cec5SDimitry Andric   if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
7620b57cec5SDimitry Andric     return;
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   // Collect all the (vreg, valno) pairs that are copies of LI.
7650b57cec5SDimitry Andric   SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
7660b57cec5SDimitry Andric   for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
7670b57cec5SDimitry Andric     MachineInstr *MI = MO.getParent();
7680b57cec5SDimitry Andric     // Copies of the full value.
7690b57cec5SDimitry Andric     if (MO.getSubReg() || !MI->isCopy())
7700b57cec5SDimitry Andric       continue;
7710b57cec5SDimitry Andric     unsigned DstReg = MI->getOperand(0).getReg();
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric     // Don't follow copies to physregs. These are usually setting up call
7740b57cec5SDimitry Andric     // arguments, and the argument registers are always call clobbered. We are
7750b57cec5SDimitry Andric     // better off in the source register which could be a callee-saved register,
7760b57cec5SDimitry Andric     // or it could be spilled.
7770b57cec5SDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(DstReg))
7780b57cec5SDimitry Andric       continue;
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric     // Is LocNo extended to reach this copy? If not, another def may be blocking
7810b57cec5SDimitry Andric     // it, or we are looking at a wrong value of LI.
7820b57cec5SDimitry Andric     SlotIndex Idx = LIS.getInstructionIndex(*MI);
7830b57cec5SDimitry Andric     LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
7840b57cec5SDimitry Andric     if (!I.valid() || I.value().locNo() != LocNo)
7850b57cec5SDimitry Andric       continue;
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric     if (!LIS.hasInterval(DstReg))
7880b57cec5SDimitry Andric       continue;
7890b57cec5SDimitry Andric     LiveInterval *DstLI = &LIS.getInterval(DstReg);
7900b57cec5SDimitry Andric     const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
7910b57cec5SDimitry Andric     assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
7920b57cec5SDimitry Andric     CopyValues.push_back(std::make_pair(DstLI, DstVNI));
7930b57cec5SDimitry Andric   }
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric   if (CopyValues.empty())
7960b57cec5SDimitry Andric     return;
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI
7990b57cec5SDimitry Andric                     << '\n');
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric   // Try to add defs of the copied values for each kill point.
8020b57cec5SDimitry Andric   for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
8030b57cec5SDimitry Andric     SlotIndex Idx = Kills[i];
8040b57cec5SDimitry Andric     for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
8050b57cec5SDimitry Andric       LiveInterval *DstLI = CopyValues[j].first;
8060b57cec5SDimitry Andric       const VNInfo *DstVNI = CopyValues[j].second;
8070b57cec5SDimitry Andric       if (DstLI->getVNInfoAt(Idx) != DstVNI)
8080b57cec5SDimitry Andric         continue;
8090b57cec5SDimitry Andric       // Check that there isn't already a def at Idx
8100b57cec5SDimitry Andric       LocMap::iterator I = locInts.find(Idx);
8110b57cec5SDimitry Andric       if (I.valid() && I.start() <= Idx)
8120b57cec5SDimitry Andric         continue;
8130b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
8140b57cec5SDimitry Andric                         << DstVNI->id << " in " << *DstLI << '\n');
8150b57cec5SDimitry Andric       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
8160b57cec5SDimitry Andric       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
8170b57cec5SDimitry Andric       unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
8180b57cec5SDimitry Andric       DbgValueLocation NewLoc(LocNo, WasIndirect);
8190b57cec5SDimitry Andric       I.insert(Idx, Idx.getNextSlot(), NewLoc);
8200b57cec5SDimitry Andric       NewDefs.push_back(std::make_pair(Idx, NewLoc));
8210b57cec5SDimitry Andric       break;
8220b57cec5SDimitry Andric     }
8230b57cec5SDimitry Andric   }
8240b57cec5SDimitry Andric }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric void UserValue::computeIntervals(MachineRegisterInfo &MRI,
8270b57cec5SDimitry Andric                                  const TargetRegisterInfo &TRI,
8280b57cec5SDimitry Andric                                  LiveIntervals &LIS, LexicalScopes &LS) {
8290b57cec5SDimitry Andric   SmallVector<std::pair<SlotIndex, DbgValueLocation>, 16> Defs;
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   // Collect all defs to be extended (Skipping undefs).
8320b57cec5SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
8330b57cec5SDimitry Andric     if (!I.value().isUndef())
8340b57cec5SDimitry Andric       Defs.push_back(std::make_pair(I.start(), I.value()));
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   // Extend all defs, and possibly add new ones along the way.
8370b57cec5SDimitry Andric   for (unsigned i = 0; i != Defs.size(); ++i) {
8380b57cec5SDimitry Andric     SlotIndex Idx = Defs[i].first;
8390b57cec5SDimitry Andric     DbgValueLocation Loc = Defs[i].second;
8400b57cec5SDimitry Andric     const MachineOperand &LocMO = locations[Loc.locNo()];
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric     if (!LocMO.isReg()) {
8430b57cec5SDimitry Andric       extendDef(Idx, Loc, nullptr, nullptr, nullptr, LIS);
8440b57cec5SDimitry Andric       continue;
8450b57cec5SDimitry Andric     }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric     // Register locations are constrained to where the register value is live.
8480b57cec5SDimitry Andric     if (TargetRegisterInfo::isVirtualRegister(LocMO.getReg())) {
8490b57cec5SDimitry Andric       LiveInterval *LI = nullptr;
8500b57cec5SDimitry Andric       const VNInfo *VNI = nullptr;
8510b57cec5SDimitry Andric       if (LIS.hasInterval(LocMO.getReg())) {
8520b57cec5SDimitry Andric         LI = &LIS.getInterval(LocMO.getReg());
8530b57cec5SDimitry Andric         VNI = LI->getVNInfoAt(Idx);
8540b57cec5SDimitry Andric       }
8550b57cec5SDimitry Andric       SmallVector<SlotIndex, 16> Kills;
8560b57cec5SDimitry Andric       extendDef(Idx, Loc, LI, VNI, &Kills, LIS);
8570b57cec5SDimitry Andric       // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
8580b57cec5SDimitry Andric       // if the original location for example is %vreg0:sub_hi, and we find a
8590b57cec5SDimitry Andric       // full register copy in addDefsFromCopies (at the moment it only handles
8600b57cec5SDimitry Andric       // full register copies), then we must add the sub1 sub-register index to
8610b57cec5SDimitry Andric       // the new location. However, that is only possible if the new virtual
8620b57cec5SDimitry Andric       // register is of the same regclass (or if there is an equivalent
8630b57cec5SDimitry Andric       // sub-register in that regclass). For now, simply skip handling copies if
8640b57cec5SDimitry Andric       // a sub-register is involved.
8650b57cec5SDimitry Andric       if (LI && !LocMO.getSubReg())
8660b57cec5SDimitry Andric         addDefsFromCopies(LI, Loc.locNo(), Loc.wasIndirect(), Kills, Defs, MRI,
8670b57cec5SDimitry Andric                           LIS);
8680b57cec5SDimitry Andric       continue;
8690b57cec5SDimitry Andric     }
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric     // For physregs, we only mark the start slot idx. DwarfDebug will see it
8720b57cec5SDimitry Andric     // as if the DBG_VALUE is valid up until the end of the basic block, or
8730b57cec5SDimitry Andric     // the next def of the physical register. So we do not need to extend the
8740b57cec5SDimitry Andric     // range. It might actually happen that the DBG_VALUE is the last use of
8750b57cec5SDimitry Andric     // the physical register (e.g. if this is an unused input argument to a
8760b57cec5SDimitry Andric     // function).
8770b57cec5SDimitry Andric   }
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric   // The computed intervals may extend beyond the range of the debug
8800b57cec5SDimitry Andric   // location's lexical scope. In this case, splitting of an interval
8810b57cec5SDimitry Andric   // can result in an interval outside of the scope being created,
8820b57cec5SDimitry Andric   // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
8830b57cec5SDimitry Andric   // this, trim the intervals to the lexical scope.
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric   LexicalScope *Scope = LS.findLexicalScope(dl);
8860b57cec5SDimitry Andric   if (!Scope)
8870b57cec5SDimitry Andric     return;
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   SlotIndex PrevEnd;
8900b57cec5SDimitry Andric   LocMap::iterator I = locInts.begin();
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric   // Iterate over the lexical scope ranges. Each time round the loop
8930b57cec5SDimitry Andric   // we check the intervals for overlap with the end of the previous
8940b57cec5SDimitry Andric   // range and the start of the next. The first range is handled as
8950b57cec5SDimitry Andric   // a special case where there is no PrevEnd.
8960b57cec5SDimitry Andric   for (const InsnRange &Range : Scope->getRanges()) {
8970b57cec5SDimitry Andric     SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
8980b57cec5SDimitry Andric     SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric     // At the start of each iteration I has been advanced so that
9010b57cec5SDimitry Andric     // I.stop() >= PrevEnd. Check for overlap.
9020b57cec5SDimitry Andric     if (PrevEnd && I.start() < PrevEnd) {
9030b57cec5SDimitry Andric       SlotIndex IStop = I.stop();
9040b57cec5SDimitry Andric       DbgValueLocation Loc = I.value();
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric       // Stop overlaps previous end - trim the end of the interval to
9070b57cec5SDimitry Andric       // the scope range.
9080b57cec5SDimitry Andric       I.setStopUnchecked(PrevEnd);
9090b57cec5SDimitry Andric       ++I;
9100b57cec5SDimitry Andric 
9110b57cec5SDimitry Andric       // If the interval also overlaps the start of the "next" (i.e.
9120b57cec5SDimitry Andric       // current) range create a new interval for the remainder
9130b57cec5SDimitry Andric       if (RStart < IStop)
9140b57cec5SDimitry Andric         I.insert(RStart, IStop, Loc);
9150b57cec5SDimitry Andric     }
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric     // Advance I so that I.stop() >= RStart, and check for overlap.
9180b57cec5SDimitry Andric     I.advanceTo(RStart);
9190b57cec5SDimitry Andric     if (!I.valid())
9200b57cec5SDimitry Andric       return;
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric     // The end of a lexical scope range is the last instruction in the
9230b57cec5SDimitry Andric     // range. To convert to an interval we need the index of the
9240b57cec5SDimitry Andric     // instruction after it.
9250b57cec5SDimitry Andric     REnd = REnd.getNextIndex();
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric     // Advance I to first interval outside current range.
9280b57cec5SDimitry Andric     I.advanceTo(REnd);
9290b57cec5SDimitry Andric     if (!I.valid())
9300b57cec5SDimitry Andric       return;
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric     PrevEnd = REnd;
9330b57cec5SDimitry Andric   }
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric   // Check for overlap with end of final range.
9360b57cec5SDimitry Andric   if (PrevEnd && I.start() < PrevEnd)
9370b57cec5SDimitry Andric     I.setStopUnchecked(PrevEnd);
9380b57cec5SDimitry Andric }
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric void LDVImpl::computeIntervals() {
9410b57cec5SDimitry Andric   LexicalScopes LS;
9420b57cec5SDimitry Andric   LS.initialize(*MF);
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
9450b57cec5SDimitry Andric     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
9460b57cec5SDimitry Andric     userValues[i]->mapVirtRegs(this);
9470b57cec5SDimitry Andric   }
9480b57cec5SDimitry Andric }
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
9510b57cec5SDimitry Andric   clear();
9520b57cec5SDimitry Andric   MF = &mf;
9530b57cec5SDimitry Andric   LIS = &pass.getAnalysis<LiveIntervals>();
9540b57cec5SDimitry Andric   TRI = mf.getSubtarget().getRegisterInfo();
9550b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
9560b57cec5SDimitry Andric                     << mf.getName() << " **********\n");
9570b57cec5SDimitry Andric 
9580b57cec5SDimitry Andric   bool Changed = collectDebugValues(mf);
9590b57cec5SDimitry Andric   computeIntervals();
9600b57cec5SDimitry Andric   LLVM_DEBUG(print(dbgs()));
9610b57cec5SDimitry Andric   ModifiedMF = Changed;
9620b57cec5SDimitry Andric   return Changed;
9630b57cec5SDimitry Andric }
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric static void removeDebugValues(MachineFunction &mf) {
9660b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : mf) {
9670b57cec5SDimitry Andric     for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
9680b57cec5SDimitry Andric       if (!MBBI->isDebugValue()) {
9690b57cec5SDimitry Andric         ++MBBI;
9700b57cec5SDimitry Andric         continue;
9710b57cec5SDimitry Andric       }
9720b57cec5SDimitry Andric       MBBI = MBB.erase(MBBI);
9730b57cec5SDimitry Andric     }
9740b57cec5SDimitry Andric   }
9750b57cec5SDimitry Andric }
9760b57cec5SDimitry Andric 
9770b57cec5SDimitry Andric bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
9780b57cec5SDimitry Andric   if (!EnableLDV)
9790b57cec5SDimitry Andric     return false;
9800b57cec5SDimitry Andric   if (!mf.getFunction().getSubprogram()) {
9810b57cec5SDimitry Andric     removeDebugValues(mf);
9820b57cec5SDimitry Andric     return false;
9830b57cec5SDimitry Andric   }
9840b57cec5SDimitry Andric   if (!pImpl)
9850b57cec5SDimitry Andric     pImpl = new LDVImpl(this);
9860b57cec5SDimitry Andric   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
9870b57cec5SDimitry Andric }
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric void LiveDebugVariables::releaseMemory() {
9900b57cec5SDimitry Andric   if (pImpl)
9910b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->clear();
9920b57cec5SDimitry Andric }
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric LiveDebugVariables::~LiveDebugVariables() {
9950b57cec5SDimitry Andric   if (pImpl)
9960b57cec5SDimitry Andric     delete static_cast<LDVImpl*>(pImpl);
9970b57cec5SDimitry Andric }
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10000b57cec5SDimitry Andric //                           Live Range Splitting
10010b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric bool
10040b57cec5SDimitry Andric UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
10050b57cec5SDimitry Andric                          LiveIntervals& LIS) {
10060b57cec5SDimitry Andric   LLVM_DEBUG({
10070b57cec5SDimitry Andric     dbgs() << "Splitting Loc" << OldLocNo << '\t';
10080b57cec5SDimitry Andric     print(dbgs(), nullptr);
10090b57cec5SDimitry Andric   });
10100b57cec5SDimitry Andric   bool DidChange = false;
10110b57cec5SDimitry Andric   LocMap::iterator LocMapI;
10120b57cec5SDimitry Andric   LocMapI.setMap(locInts);
10130b57cec5SDimitry Andric   for (unsigned i = 0; i != NewRegs.size(); ++i) {
10140b57cec5SDimitry Andric     LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
10150b57cec5SDimitry Andric     if (LI->empty())
10160b57cec5SDimitry Andric       continue;
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric     // Don't allocate the new LocNo until it is needed.
10190b57cec5SDimitry Andric     unsigned NewLocNo = UndefLocNo;
10200b57cec5SDimitry Andric 
10210b57cec5SDimitry Andric     // Iterate over the overlaps between locInts and LI.
10220b57cec5SDimitry Andric     LocMapI.find(LI->beginIndex());
10230b57cec5SDimitry Andric     if (!LocMapI.valid())
10240b57cec5SDimitry Andric       continue;
10250b57cec5SDimitry Andric     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
10260b57cec5SDimitry Andric     LiveInterval::iterator LIE = LI->end();
10270b57cec5SDimitry Andric     while (LocMapI.valid() && LII != LIE) {
10280b57cec5SDimitry Andric       // At this point, we know that LocMapI.stop() > LII->start.
10290b57cec5SDimitry Andric       LII = LI->advanceTo(LII, LocMapI.start());
10300b57cec5SDimitry Andric       if (LII == LIE)
10310b57cec5SDimitry Andric         break;
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric       // Now LII->end > LocMapI.start(). Do we have an overlap?
10340b57cec5SDimitry Andric       if (LocMapI.value().locNo() == OldLocNo && LII->start < LocMapI.stop()) {
10350b57cec5SDimitry Andric         // Overlapping correct location. Allocate NewLocNo now.
10360b57cec5SDimitry Andric         if (NewLocNo == UndefLocNo) {
10370b57cec5SDimitry Andric           MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
10380b57cec5SDimitry Andric           MO.setSubReg(locations[OldLocNo].getSubReg());
10390b57cec5SDimitry Andric           NewLocNo = getLocationNo(MO);
10400b57cec5SDimitry Andric           DidChange = true;
10410b57cec5SDimitry Andric         }
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric         SlotIndex LStart = LocMapI.start();
10440b57cec5SDimitry Andric         SlotIndex LStop  = LocMapI.stop();
10450b57cec5SDimitry Andric         DbgValueLocation OldLoc = LocMapI.value();
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric         // Trim LocMapI down to the LII overlap.
10480b57cec5SDimitry Andric         if (LStart < LII->start)
10490b57cec5SDimitry Andric           LocMapI.setStartUnchecked(LII->start);
10500b57cec5SDimitry Andric         if (LStop > LII->end)
10510b57cec5SDimitry Andric           LocMapI.setStopUnchecked(LII->end);
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric         // Change the value in the overlap. This may trigger coalescing.
10540b57cec5SDimitry Andric         LocMapI.setValue(OldLoc.changeLocNo(NewLocNo));
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric         // Re-insert any removed OldLocNo ranges.
10570b57cec5SDimitry Andric         if (LStart < LocMapI.start()) {
10580b57cec5SDimitry Andric           LocMapI.insert(LStart, LocMapI.start(), OldLoc);
10590b57cec5SDimitry Andric           ++LocMapI;
10600b57cec5SDimitry Andric           assert(LocMapI.valid() && "Unexpected coalescing");
10610b57cec5SDimitry Andric         }
10620b57cec5SDimitry Andric         if (LStop > LocMapI.stop()) {
10630b57cec5SDimitry Andric           ++LocMapI;
10640b57cec5SDimitry Andric           LocMapI.insert(LII->end, LStop, OldLoc);
10650b57cec5SDimitry Andric           --LocMapI;
10660b57cec5SDimitry Andric         }
10670b57cec5SDimitry Andric       }
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric       // Advance to the next overlap.
10700b57cec5SDimitry Andric       if (LII->end < LocMapI.stop()) {
10710b57cec5SDimitry Andric         if (++LII == LIE)
10720b57cec5SDimitry Andric           break;
10730b57cec5SDimitry Andric         LocMapI.advanceTo(LII->start);
10740b57cec5SDimitry Andric       } else {
10750b57cec5SDimitry Andric         ++LocMapI;
10760b57cec5SDimitry Andric         if (!LocMapI.valid())
10770b57cec5SDimitry Andric           break;
10780b57cec5SDimitry Andric         LII = LI->advanceTo(LII, LocMapI.start());
10790b57cec5SDimitry Andric       }
10800b57cec5SDimitry Andric     }
10810b57cec5SDimitry Andric   }
10820b57cec5SDimitry Andric 
10830b57cec5SDimitry Andric   // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
10840b57cec5SDimitry Andric   locations.erase(locations.begin() + OldLocNo);
10850b57cec5SDimitry Andric   LocMapI.goToBegin();
10860b57cec5SDimitry Andric   while (LocMapI.valid()) {
10870b57cec5SDimitry Andric     DbgValueLocation v = LocMapI.value();
10880b57cec5SDimitry Andric     if (v.locNo() == OldLocNo) {
10890b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
10900b57cec5SDimitry Andric                         << LocMapI.stop() << ")\n");
10910b57cec5SDimitry Andric       LocMapI.erase();
10920b57cec5SDimitry Andric     } else {
10930b57cec5SDimitry Andric       // Undef values always have location number UndefLocNo, so don't change
10940b57cec5SDimitry Andric       // locNo in that case. See getLocationNo().
10950b57cec5SDimitry Andric       if (!v.isUndef() && v.locNo() > OldLocNo)
10960b57cec5SDimitry Andric         LocMapI.setValueUnchecked(v.changeLocNo(v.locNo() - 1));
10970b57cec5SDimitry Andric       ++LocMapI;
10980b57cec5SDimitry Andric     }
10990b57cec5SDimitry Andric   }
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   LLVM_DEBUG({
11020b57cec5SDimitry Andric     dbgs() << "Split result: \t";
11030b57cec5SDimitry Andric     print(dbgs(), nullptr);
11040b57cec5SDimitry Andric   });
11050b57cec5SDimitry Andric   return DidChange;
11060b57cec5SDimitry Andric }
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric bool
11090b57cec5SDimitry Andric UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
11100b57cec5SDimitry Andric                          LiveIntervals &LIS) {
11110b57cec5SDimitry Andric   bool DidChange = false;
11120b57cec5SDimitry Andric   // Split locations referring to OldReg. Iterate backwards so splitLocation can
11130b57cec5SDimitry Andric   // safely erase unused locations.
11140b57cec5SDimitry Andric   for (unsigned i = locations.size(); i ; --i) {
11150b57cec5SDimitry Andric     unsigned LocNo = i-1;
11160b57cec5SDimitry Andric     const MachineOperand *Loc = &locations[LocNo];
11170b57cec5SDimitry Andric     if (!Loc->isReg() || Loc->getReg() != OldReg)
11180b57cec5SDimitry Andric       continue;
11190b57cec5SDimitry Andric     DidChange |= splitLocation(LocNo, NewRegs, LIS);
11200b57cec5SDimitry Andric   }
11210b57cec5SDimitry Andric   return DidChange;
11220b57cec5SDimitry Andric }
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
11250b57cec5SDimitry Andric   bool DidChange = false;
11260b57cec5SDimitry Andric   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
11270b57cec5SDimitry Andric     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric   if (!DidChange)
11300b57cec5SDimitry Andric     return;
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric   // Map all of the new virtual registers.
11330b57cec5SDimitry Andric   UserValue *UV = lookupVirtReg(OldReg);
11340b57cec5SDimitry Andric   for (unsigned i = 0; i != NewRegs.size(); ++i)
11350b57cec5SDimitry Andric     mapVirtReg(NewRegs[i], UV);
11360b57cec5SDimitry Andric }
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric void LiveDebugVariables::
11390b57cec5SDimitry Andric splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
11400b57cec5SDimitry Andric   if (pImpl)
11410b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
11420b57cec5SDimitry Andric }
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
11450b57cec5SDimitry Andric                                  const TargetInstrInfo &TII,
11460b57cec5SDimitry Andric                                  const TargetRegisterInfo &TRI,
11470b57cec5SDimitry Andric                                  SpillOffsetMap &SpillOffsets) {
11480b57cec5SDimitry Andric   // Build a set of new locations with new numbers so we can coalesce our
11490b57cec5SDimitry Andric   // IntervalMap if two vreg intervals collapse to the same physical location.
11500b57cec5SDimitry Andric   // Use MapVector instead of SetVector because MapVector::insert returns the
11510b57cec5SDimitry Andric   // position of the previously or newly inserted element. The boolean value
11520b57cec5SDimitry Andric   // tracks if the location was produced by a spill.
11530b57cec5SDimitry Andric   // FIXME: This will be problematic if we ever support direct and indirect
11540b57cec5SDimitry Andric   // frame index locations, i.e. expressing both variables in memory and
11550b57cec5SDimitry Andric   // 'int x, *px = &x'. The "spilled" bit must become part of the location.
11560b57cec5SDimitry Andric   MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
11570b57cec5SDimitry Andric   SmallVector<unsigned, 4> LocNoMap(locations.size());
11580b57cec5SDimitry Andric   for (unsigned I = 0, E = locations.size(); I != E; ++I) {
11590b57cec5SDimitry Andric     bool Spilled = false;
11600b57cec5SDimitry Andric     unsigned SpillOffset = 0;
11610b57cec5SDimitry Andric     MachineOperand Loc = locations[I];
11620b57cec5SDimitry Andric     // Only virtual registers are rewritten.
11630b57cec5SDimitry Andric     if (Loc.isReg() && Loc.getReg() &&
11640b57cec5SDimitry Andric         TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
11650b57cec5SDimitry Andric       unsigned VirtReg = Loc.getReg();
11660b57cec5SDimitry Andric       if (VRM.isAssignedReg(VirtReg) &&
11670b57cec5SDimitry Andric           TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
11680b57cec5SDimitry Andric         // This can create a %noreg operand in rare cases when the sub-register
11690b57cec5SDimitry Andric         // index is no longer available. That means the user value is in a
11700b57cec5SDimitry Andric         // non-existent sub-register, and %noreg is exactly what we want.
11710b57cec5SDimitry Andric         Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
11720b57cec5SDimitry Andric       } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
11730b57cec5SDimitry Andric         // Retrieve the stack slot offset.
11740b57cec5SDimitry Andric         unsigned SpillSize;
11750b57cec5SDimitry Andric         const MachineRegisterInfo &MRI = MF.getRegInfo();
11760b57cec5SDimitry Andric         const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
11770b57cec5SDimitry Andric         bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
11780b57cec5SDimitry Andric                                              SpillOffset, MF);
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric         // FIXME: Invalidate the location if the offset couldn't be calculated.
11810b57cec5SDimitry Andric         (void)Success;
11820b57cec5SDimitry Andric 
11830b57cec5SDimitry Andric         Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
11840b57cec5SDimitry Andric         Spilled = true;
11850b57cec5SDimitry Andric       } else {
11860b57cec5SDimitry Andric         Loc.setReg(0);
11870b57cec5SDimitry Andric         Loc.setSubReg(0);
11880b57cec5SDimitry Andric       }
11890b57cec5SDimitry Andric     }
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric     // Insert this location if it doesn't already exist and record a mapping
11920b57cec5SDimitry Andric     // from the old number to the new number.
11930b57cec5SDimitry Andric     auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
11940b57cec5SDimitry Andric     unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
11950b57cec5SDimitry Andric     LocNoMap[I] = NewLocNo;
11960b57cec5SDimitry Andric   }
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric   // Rewrite the locations and record the stack slot offsets for spills.
11990b57cec5SDimitry Andric   locations.clear();
12000b57cec5SDimitry Andric   SpillOffsets.clear();
12010b57cec5SDimitry Andric   for (auto &Pair : NewLocations) {
12020b57cec5SDimitry Andric     bool Spilled;
12030b57cec5SDimitry Andric     unsigned SpillOffset;
12040b57cec5SDimitry Andric     std::tie(Spilled, SpillOffset) = Pair.second;
12050b57cec5SDimitry Andric     locations.push_back(Pair.first);
12060b57cec5SDimitry Andric     if (Spilled) {
12070b57cec5SDimitry Andric       unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
12080b57cec5SDimitry Andric       SpillOffsets[NewLocNo] = SpillOffset;
12090b57cec5SDimitry Andric     }
12100b57cec5SDimitry Andric   }
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric   // Update the interval map, but only coalesce left, since intervals to the
12130b57cec5SDimitry Andric   // right use the old location numbers. This should merge two contiguous
12140b57cec5SDimitry Andric   // DBG_VALUE intervals with different vregs that were allocated to the same
12150b57cec5SDimitry Andric   // physical register.
12160b57cec5SDimitry Andric   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
12170b57cec5SDimitry Andric     DbgValueLocation Loc = I.value();
12180b57cec5SDimitry Andric     // Undef values don't exist in locations (and thus not in LocNoMap either)
12190b57cec5SDimitry Andric     // so skip over them. See getLocationNo().
12200b57cec5SDimitry Andric     if (Loc.isUndef())
12210b57cec5SDimitry Andric       continue;
12220b57cec5SDimitry Andric     unsigned NewLocNo = LocNoMap[Loc.locNo()];
12230b57cec5SDimitry Andric     I.setValueUnchecked(Loc.changeLocNo(NewLocNo));
12240b57cec5SDimitry Andric     I.setStart(I.start());
12250b57cec5SDimitry Andric   }
12260b57cec5SDimitry Andric }
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric /// Find an iterator for inserting a DBG_VALUE instruction.
12290b57cec5SDimitry Andric static MachineBasicBlock::iterator
12300b57cec5SDimitry Andric findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
12310b57cec5SDimitry Andric                    LiveIntervals &LIS) {
12320b57cec5SDimitry Andric   SlotIndex Start = LIS.getMBBStartIdx(MBB);
12330b57cec5SDimitry Andric   Idx = Idx.getBaseIndex();
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric   // Try to find an insert location by going backwards from Idx.
12360b57cec5SDimitry Andric   MachineInstr *MI;
12370b57cec5SDimitry Andric   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
12380b57cec5SDimitry Andric     // We've reached the beginning of MBB.
12390b57cec5SDimitry Andric     if (Idx == Start) {
12400b57cec5SDimitry Andric       MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
12410b57cec5SDimitry Andric       return I;
12420b57cec5SDimitry Andric     }
12430b57cec5SDimitry Andric     Idx = Idx.getPrevIndex();
12440b57cec5SDimitry Andric   }
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric   // Don't insert anything after the first terminator, though.
12470b57cec5SDimitry Andric   return MI->isTerminator() ? MBB->getFirstTerminator() :
12480b57cec5SDimitry Andric                               std::next(MachineBasicBlock::iterator(MI));
12490b57cec5SDimitry Andric }
12500b57cec5SDimitry Andric 
12510b57cec5SDimitry Andric /// Find an iterator for inserting the next DBG_VALUE instruction
12520b57cec5SDimitry Andric /// (or end if no more insert locations found).
12530b57cec5SDimitry Andric static MachineBasicBlock::iterator
12540b57cec5SDimitry Andric findNextInsertLocation(MachineBasicBlock *MBB,
12550b57cec5SDimitry Andric                        MachineBasicBlock::iterator I,
12560b57cec5SDimitry Andric                        SlotIndex StopIdx, MachineOperand &LocMO,
12570b57cec5SDimitry Andric                        LiveIntervals &LIS,
12580b57cec5SDimitry Andric                        const TargetRegisterInfo &TRI) {
12590b57cec5SDimitry Andric   if (!LocMO.isReg())
12600b57cec5SDimitry Andric     return MBB->instr_end();
12610b57cec5SDimitry Andric   unsigned Reg = LocMO.getReg();
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric   // Find the next instruction in the MBB that define the register Reg.
12640b57cec5SDimitry Andric   while (I != MBB->end() && !I->isTerminator()) {
12650b57cec5SDimitry Andric     if (!LIS.isNotInMIMap(*I) &&
12660b57cec5SDimitry Andric         SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
12670b57cec5SDimitry Andric       break;
12680b57cec5SDimitry Andric     if (I->definesRegister(Reg, &TRI))
12690b57cec5SDimitry Andric       // The insert location is directly after the instruction/bundle.
12700b57cec5SDimitry Andric       return std::next(I);
12710b57cec5SDimitry Andric     ++I;
12720b57cec5SDimitry Andric   }
12730b57cec5SDimitry Andric   return MBB->end();
12740b57cec5SDimitry Andric }
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
12770b57cec5SDimitry Andric                                  SlotIndex StopIdx, DbgValueLocation Loc,
12780b57cec5SDimitry Andric                                  bool Spilled, unsigned SpillOffset,
12790b57cec5SDimitry Andric                                  LiveIntervals &LIS, const TargetInstrInfo &TII,
12800b57cec5SDimitry Andric                                  const TargetRegisterInfo &TRI) {
12810b57cec5SDimitry Andric   SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
12820b57cec5SDimitry Andric   // Only search within the current MBB.
12830b57cec5SDimitry Andric   StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
12840b57cec5SDimitry Andric   MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS);
12850b57cec5SDimitry Andric   // Undef values don't exist in locations so create new "noreg" register MOs
12860b57cec5SDimitry Andric   // for them. See getLocationNo().
12870b57cec5SDimitry Andric   MachineOperand MO = !Loc.isUndef() ?
12880b57cec5SDimitry Andric     locations[Loc.locNo()] :
12890b57cec5SDimitry Andric     MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false,
12900b57cec5SDimitry Andric                               /* isKill */ false, /* isDead */ false,
12910b57cec5SDimitry Andric                               /* isUndef */ false, /* isEarlyClobber */ false,
12920b57cec5SDimitry Andric                               /* SubReg */ 0, /* isDebug */ true);
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric   ++NumInsertedDebugValues;
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric   assert(cast<DILocalVariable>(Variable)
12970b57cec5SDimitry Andric              ->isValidLocationForIntrinsic(getDebugLoc()) &&
12980b57cec5SDimitry Andric          "Expected inlined-at fields to agree");
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric   // If the location was spilled, the new DBG_VALUE will be indirect. If the
13010b57cec5SDimitry Andric   // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
13020b57cec5SDimitry Andric   // that the original virtual register was a pointer. Also, add the stack slot
13030b57cec5SDimitry Andric   // offset for the spilled register to the expression.
13040b57cec5SDimitry Andric   const DIExpression *Expr = Expression;
13050b57cec5SDimitry Andric   uint8_t DIExprFlags = DIExpression::ApplyOffset;
13060b57cec5SDimitry Andric   bool IsIndirect = Loc.wasIndirect();
13070b57cec5SDimitry Andric   if (Spilled) {
13080b57cec5SDimitry Andric     if (IsIndirect)
13090b57cec5SDimitry Andric       DIExprFlags |= DIExpression::DerefAfter;
13100b57cec5SDimitry Andric     Expr =
13110b57cec5SDimitry Andric         DIExpression::prepend(Expr, DIExprFlags, SpillOffset);
13120b57cec5SDimitry Andric     IsIndirect = true;
13130b57cec5SDimitry Andric   }
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric   assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric   do {
13180b57cec5SDimitry Andric     BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
13190b57cec5SDimitry Andric             IsIndirect, MO, Variable, Expr);
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric     // Continue and insert DBG_VALUES after every redefinition of register
13220b57cec5SDimitry Andric     // associated with the debug value within the range
13230b57cec5SDimitry Andric     I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
13240b57cec5SDimitry Andric   } while (I != MBB->end());
13250b57cec5SDimitry Andric }
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
13280b57cec5SDimitry Andric                                  LiveIntervals &LIS,
13290b57cec5SDimitry Andric                                  const TargetInstrInfo &TII) {
13300b57cec5SDimitry Andric   MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
13310b57cec5SDimitry Andric   ++NumInsertedDebugLabels;
13320b57cec5SDimitry Andric   BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
13330b57cec5SDimitry Andric       .addMetadata(Label);
13340b57cec5SDimitry Andric }
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
13370b57cec5SDimitry Andric                                 const TargetInstrInfo &TII,
13380b57cec5SDimitry Andric                                 const TargetRegisterInfo &TRI,
13390b57cec5SDimitry Andric                                 const SpillOffsetMap &SpillOffsets) {
13400b57cec5SDimitry Andric   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
13430b57cec5SDimitry Andric     SlotIndex Start = I.start();
13440b57cec5SDimitry Andric     SlotIndex Stop = I.stop();
13450b57cec5SDimitry Andric     DbgValueLocation Loc = I.value();
13460b57cec5SDimitry Andric     auto SpillIt =
13470b57cec5SDimitry Andric         !Loc.isUndef() ? SpillOffsets.find(Loc.locNo()) : SpillOffsets.end();
13480b57cec5SDimitry Andric     bool Spilled = SpillIt != SpillOffsets.end();
13490b57cec5SDimitry Andric     unsigned SpillOffset = Spilled ? SpillIt->second : 0;
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << Loc.locNo());
13520b57cec5SDimitry Andric     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
13530b57cec5SDimitry Andric     SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
13540b57cec5SDimitry Andric 
13550b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
13560b57cec5SDimitry Andric     insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII,
13570b57cec5SDimitry Andric                      TRI);
13580b57cec5SDimitry Andric     // This interval may span multiple basic blocks.
13590b57cec5SDimitry Andric     // Insert a DBG_VALUE into each one.
13600b57cec5SDimitry Andric     while (Stop > MBBEnd) {
13610b57cec5SDimitry Andric       // Move to the next block.
13620b57cec5SDimitry Andric       Start = MBBEnd;
13630b57cec5SDimitry Andric       if (++MBB == MFEnd)
13640b57cec5SDimitry Andric         break;
13650b57cec5SDimitry Andric       MBBEnd = LIS.getMBBEndIdx(&*MBB);
13660b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
13670b57cec5SDimitry Andric       insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII,
13680b57cec5SDimitry Andric                        TRI);
13690b57cec5SDimitry Andric     }
13700b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << '\n');
13710b57cec5SDimitry Andric     if (MBB == MFEnd)
13720b57cec5SDimitry Andric       break;
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric     ++I;
13750b57cec5SDimitry Andric   }
13760b57cec5SDimitry Andric }
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII) {
13790b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\t" << loc);
13800b57cec5SDimitry Andric   MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
13830b57cec5SDimitry Andric   insertDebugLabel(&*MBB, loc, LIS, TII);
13840b57cec5SDimitry Andric 
13850b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << '\n');
13860b57cec5SDimitry Andric }
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
13890b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
13900b57cec5SDimitry Andric   if (!MF)
13910b57cec5SDimitry Andric     return;
13920b57cec5SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
13930b57cec5SDimitry Andric   SpillOffsetMap SpillOffsets;
13940b57cec5SDimitry Andric   for (auto &userValue : userValues) {
13950b57cec5SDimitry Andric     LLVM_DEBUG(userValue->print(dbgs(), TRI));
13960b57cec5SDimitry Andric     userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
13970b57cec5SDimitry Andric     userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets);
13980b57cec5SDimitry Andric   }
13990b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
14000b57cec5SDimitry Andric   for (auto &userLabel : userLabels) {
14010b57cec5SDimitry Andric     LLVM_DEBUG(userLabel->print(dbgs(), TRI));
14020b57cec5SDimitry Andric     userLabel->emitDebugLabel(*LIS, *TII);
14030b57cec5SDimitry Andric   }
14040b57cec5SDimitry Andric   EmitDone = true;
14050b57cec5SDimitry Andric }
14060b57cec5SDimitry Andric 
14070b57cec5SDimitry Andric void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
14080b57cec5SDimitry Andric   if (pImpl)
14090b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
14100b57cec5SDimitry Andric }
14110b57cec5SDimitry Andric 
14120b57cec5SDimitry Andric bool LiveDebugVariables::doInitialization(Module &M) {
14130b57cec5SDimitry Andric   return Pass::doInitialization(M);
14140b57cec5SDimitry Andric }
14150b57cec5SDimitry Andric 
14160b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
14170b57cec5SDimitry Andric LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
14180b57cec5SDimitry Andric   if (pImpl)
14190b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->print(dbgs());
14200b57cec5SDimitry Andric }
14210b57cec5SDimitry Andric #endif
1422