LCOV - code coverage report
Current view: top level - lib/CodeGen - LiveDebugVariables.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 393 397 99.0 %
Date: 2018-06-17 00:07:59 Functions: 43 43 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13