LCOV - code coverage report
Current view: top level - lib/CodeGen - LiveDebugVariables.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 429 432 99.3 %
Date: 2017-09-14 15:23:50 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/LiveIntervalAnalysis.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/VirtRegMap.h"
      43             : #include "llvm/IR/DebugInfoMetadata.h"
      44             : #include "llvm/IR/DebugLoc.h"
      45             : #include "llvm/IR/Function.h"
      46             : #include "llvm/IR/Metadata.h"
      47             : #include "llvm/MC/MCRegisterInfo.h"
      48             : #include "llvm/Pass.h"
      49             : #include "llvm/Support/Casting.h"
      50             : #include "llvm/Support/CommandLine.h"
      51             : #include "llvm/Support/Compiler.h"
      52             : #include "llvm/Support/Debug.h"
      53             : #include "llvm/Support/raw_ostream.h"
      54             : #include "llvm/Target/TargetInstrInfo.h"
      55             : #include "llvm/Target/TargetOpcodes.h"
      56             : #include "llvm/Target/TargetRegisterInfo.h"
      57             : #include "llvm/Target/TargetSubtargetInfo.h"
      58             : #include <algorithm>
      59             : #include <cassert>
      60             : #include <iterator>
      61             : #include <memory>
      62             : #include <utility>
      63             : 
      64             : using namespace llvm;
      65             : 
      66             : #define DEBUG_TYPE "livedebugvars"
      67             : 
      68             : static cl::opt<bool>
      69      289224 : EnableLDV("live-debug-variables", cl::init(true),
      70      289224 :           cl::desc("Enable the live debug variables pass"), cl::Hidden);
      71             : 
      72             : STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
      73             : 
      74             : char LiveDebugVariables::ID = 0;
      75             : 
      76       20212 : INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
      77             :                 "Debug Variable Analysis", false, false)
      78       20212 : INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
      79       20212 : INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
      80      379178 : INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
      81             :                 "Debug Variable Analysis", false, false)
      82             : 
      83       15357 : void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
      84       15357 :   AU.addRequired<MachineDominatorTree>();
      85       15357 :   AU.addRequiredTransitive<LiveIntervals>();
      86       15357 :   AU.setPreservesAll();
      87       15357 :   MachineFunctionPass::getAnalysisUsage(AU);
      88       15357 : }
      89             : 
      90       15357 : LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
      91       15357 :   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
      92       15357 : }
      93             : 
      94             : /// LocMap - Map of where a user value is live, and its location.
      95             : using LocMap = IntervalMap<SlotIndex, unsigned, 4>;
      96             : 
      97             : namespace {
      98             : 
      99             : class LDVImpl;
     100             : 
     101             : /// UserValue - A user value is a part of a debug info user variable.
     102             : ///
     103             : /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
     104             : /// holds part of a user variable. The part is identified by a byte offset.
     105             : ///
     106             : /// UserValues are grouped into equivalence classes for easier searching. Two
     107             : /// user values are related if they refer to the same variable, or if they are
     108             : /// held by the same virtual register. The equivalence class is the transitive
     109             : /// closure of that relation.
     110       53952 : class UserValue {
     111             :   const MDNode *Variable;   ///< The debug info variable we are part of.
     112             :   const MDNode *Expression; ///< Any complex address expression.
     113             :   bool IsIndirect;        ///< true if this is a register-indirect+offset value.
     114             :   DebugLoc dl;            ///< The debug location for the variable. This is
     115             :                           ///< used by dwarf writer to find lexical scope.
     116             :   UserValue *leader;      ///< Equivalence class leader.
     117             :   UserValue *next = nullptr; ///< Next value in equivalence class, or null.
     118             : 
     119             :   /// Numbered locations referenced by locmap.
     120             :   SmallVector<MachineOperand, 4> locations;
     121             : 
     122             :   /// Map of slot indices where this value is live.
     123             :   LocMap locInts;
     124             : 
     125             :   /// Set of interval start indexes that have been trimmed to the
     126             :   /// lexical scope.
     127             :   SmallSet<SlotIndex, 2> trimmedDefs;
     128             : 
     129             :   /// coalesceLocation - After LocNo was changed, check if it has become
     130             :   /// identical to another location, and coalesce them. This may cause LocNo or
     131             :   /// a later location to be erased, but no earlier location will be erased.
     132             :   void coalesceLocation(unsigned LocNo);
     133             : 
     134             :   /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
     135             :   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
     136             :                         LiveIntervals &LIS, const TargetInstrInfo &TII);
     137             : 
     138             :   /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
     139             :   /// is live. Returns true if any changes were made.
     140             :   bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
     141             :                      LiveIntervals &LIS);
     142             : 
     143             : public:
     144             :   /// UserValue - Create a new UserValue.
     145       13488 :   UserValue(const MDNode *var, const MDNode *expr, bool i, DebugLoc L,
     146             :             LocMap::Allocator &alloc)
     147       26976 :       : Variable(var), Expression(expr), IsIndirect(i), dl(std::move(L)),
     148       67440 :         leader(this), locInts(alloc) {}
     149             : 
     150             :   /// getLeader - Get the leader of this value's equivalence class.
     151             :   UserValue *getLeader() {
     152       45280 :     UserValue *l = leader;
     153       45280 :     while (l != l->leader)
     154             :       l = l->leader;
     155       45280 :     return leader = l;
     156             :   }
     157             : 
     158             :   /// getNext - Return the next UserValue in the equivalence class.
     159             :   UserValue *getNext() const { return next; }
     160             : 
     161             :   /// match - Does this UserValue match the parameters?
     162       30834 :   bool match(const MDNode *Var, const MDNode *Expr, const DILocation *IA,
     163             :              bool indirect) const {
     164       92683 :     return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA &&
     165       35219 :            indirect == IsIndirect;
     166             :   }
     167             : 
     168             :   /// merge - Merge equivalence classes.
     169       23499 :   static UserValue *merge(UserValue *L1, UserValue *L2) {
     170       46998 :     L2 = L2->getLeader();
     171       23499 :     if (!L1)
     172             :       return L2;
     173       22362 :     L1 = L1->getLeader();
     174       11181 :     if (L1 == L2)
     175             :       return L1;
     176             :     // Splice L2 before L1's members.
     177             :     UserValue *End = L2;
     178       17125 :     while (End->next) {
     179        4080 :       End->leader = L1;
     180        4080 :       End = End->next;
     181             :     }
     182        8965 :     End->leader = L1;
     183        8965 :     End->next = L1->next;
     184        8965 :     L1->next = L2;
     185        8965 :     return L1;
     186             :   }
     187             : 
     188             :   /// getLocationNo - Return the location number that matches Loc.
     189       18877 :   unsigned getLocationNo(const MachineOperand &LocMO) {
     190       18877 :     if (LocMO.isReg()) {
     191       16800 :       if (LocMO.getReg() == 0)
     192             :         return ~0u;
     193             :       // For register locations we dont care about use/def and other flags.
     194       28511 :       for (unsigned i = 0, e = locations.size(); i != e; ++i)
     195       18981 :         if (locations[i].isReg() &&
     196       10422 :             locations[i].getReg() == LocMO.getReg() &&
     197        4924 :             locations[i].getSubReg() == LocMO.getSubReg())
     198             :           return i;
     199             :     } else
     200        4257 :       for (unsigned i = 0, e = locations.size(); i != e; ++i)
     201         744 :         if (LocMO.isIdenticalTo(locations[i]))
     202             :           return i;
     203       13012 :     locations.push_back(LocMO);
     204             :     // We are storing a MachineOperand outside a MachineInstr.
     205       13012 :     locations.back().clearParent();
     206             :     // Don't store def operands.
     207       39036 :     if (locations.back().isReg())
     208       22408 :       locations.back().setIsUse();
     209       26024 :     return locations.size() - 1;
     210             :   }
     211             : 
     212             :   /// mapVirtRegs - Ensure that all virtual register locations are mapped.
     213             :   void mapVirtRegs(LDVImpl *LDV);
     214             : 
     215             :   /// addDef - Add a definition point to this value.
     216       17873 :   void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
     217             :     // Add a singular (Idx,Idx) -> Loc mapping.
     218       53619 :     LocMap::iterator I = locInts.find(Idx);
     219        2955 :     if (!I.valid() || I.start() != Idx)
     220       33776 :       I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
     221             :     else
     222             :       // A later DBG_VALUE at the same SlotIndex overrides the old location.
     223         985 :       I.setValue(getLocationNo(LocMO));
     224       17873 :   }
     225             : 
     226             :   /// extendDef - Extend the current definition as far as possible down.
     227             :   /// Stop when meeting an existing def or when leaving the live
     228             :   /// range of VNI.
     229             :   /// End points where VNI is no longer live are added to Kills.
     230             :   /// @param Idx   Starting point for the definition.
     231             :   /// @param LocNo Location number to propagate.
     232             :   /// @param LR    Restrict liveness to where LR has the value VNI. May be null.
     233             :   /// @param VNI   When LR is not null, this is the value to restrict to.
     234             :   /// @param Kills Append end points of VNI's live range to Kills.
     235             :   /// @param LIS   Live intervals analysis.
     236             :   void extendDef(SlotIndex Idx, unsigned LocNo,
     237             :                  LiveRange *LR, const VNInfo *VNI,
     238             :                  SmallVectorImpl<SlotIndex> *Kills,
     239             :                  LiveIntervals &LIS);
     240             : 
     241             :   /// addDefsFromCopies - The value in LI/LocNo may be copies to other
     242             :   /// registers. Determine if any of the copies are available at the kill
     243             :   /// points, and add defs if possible.
     244             :   /// @param LI      Scan for copies of the value in LI->reg.
     245             :   /// @param LocNo   Location number of LI->reg.
     246             :   /// @param Kills   Points where the range of LocNo could be extended.
     247             :   /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
     248             :   void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
     249             :                        const SmallVectorImpl<SlotIndex> &Kills,
     250             :                        SmallVectorImpl<std::pair<SlotIndex, unsigned>> &NewDefs,
     251             :                        MachineRegisterInfo &MRI,
     252             :                        LiveIntervals &LIS);
     253             : 
     254             :   /// computeIntervals - Compute the live intervals of all locations after
     255             :   /// collecting all their def points.
     256             :   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
     257             :                         LiveIntervals &LIS, LexicalScopes &LS);
     258             : 
     259             :   /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
     260             :   /// live. Returns true if any changes were made.
     261             :   bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
     262             :                      LiveIntervals &LIS);
     263             : 
     264             :   /// rewriteLocations - Rewrite virtual register locations according to the
     265             :   /// provided virtual register map.
     266             :   void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
     267             : 
     268             :   /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
     269             :   void emitDebugValues(VirtRegMap *VRM,
     270             :                        LiveIntervals &LIS, const TargetInstrInfo &TRI);
     271             : 
     272             :   /// getDebugLoc - Return DebugLoc of this UserValue.
     273       25412 :   DebugLoc getDebugLoc() { return dl;}
     274             : 
     275             :   void print(raw_ostream &, const TargetRegisterInfo *);
     276             : };
     277             : 
     278             : /// LDVImpl - Implementation of the LiveDebugVariables pass.
     279        2035 : class LDVImpl {
     280             :   LiveDebugVariables &pass;
     281             :   LocMap::Allocator allocator;
     282             :   MachineFunction *MF = nullptr;
     283             :   LiveIntervals *LIS;
     284             :   const TargetRegisterInfo *TRI;
     285             : 
     286             :   /// Whether emitDebugValues is called.
     287             :   bool EmitDone = false;
     288             : 
     289             :   /// Whether the machine function is modified during the pass.
     290             :   bool ModifiedMF = false;
     291             : 
     292             :   /// userValues - All allocated UserValue instances.
     293             :   SmallVector<std::unique_ptr<UserValue>, 8> userValues;
     294             : 
     295             :   /// Map virtual register to eq class leader.
     296             :   using VRMap = DenseMap<unsigned, UserValue *>;
     297             :   VRMap virtRegToEqClass;
     298             : 
     299             :   /// Map user variable to eq class leader.
     300             :   using UVMap = DenseMap<const MDNode *, UserValue *>;
     301             :   UVMap userVarMap;
     302             : 
     303             :   /// getUserValue - Find or create a UserValue.
     304             :   UserValue *getUserValue(const MDNode *Var, const MDNode *Expr,
     305             :                           bool IsIndirect, const DebugLoc &DL);
     306             : 
     307             :   /// lookupVirtReg - Find the EC leader for VirtReg or null.
     308             :   UserValue *lookupVirtReg(unsigned VirtReg);
     309             : 
     310             :   /// handleDebugValue - Add DBG_VALUE instruction to our maps.
     311             :   /// @param MI  DBG_VALUE instruction
     312             :   /// @param Idx Last valid SLotIndex before instruction.
     313             :   /// @return    True if the DBG_VALUE instruction should be deleted.
     314             :   bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
     315             : 
     316             :   /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
     317             :   /// a UserValue def for each instruction.
     318             :   /// @param mf MachineFunction to be scanned.
     319             :   /// @return True if any debug values were found.
     320             :   bool collectDebugValues(MachineFunction &mf);
     321             : 
     322             :   /// computeIntervals - Compute the live intervals of all user values after
     323             :   /// collecting all their def points.
     324             :   void computeIntervals();
     325             : 
     326             : public:
     327        2035 :   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
     328             : 
     329             :   bool runOnMachineFunction(MachineFunction &mf);
     330             : 
     331             :   /// clear - Release all memory.
     332       11949 :   void clear() {
     333       11949 :     MF = nullptr;
     334       23898 :     userValues.clear();
     335       11949 :     virtRegToEqClass.clear();
     336       11949 :     userVarMap.clear();
     337             :     // Make sure we call emitDebugValues if the machine function was modified.
     338             :     assert((!ModifiedMF || EmitDone) &&
     339             :            "Dbg values are not emitted in LDV");
     340       11949 :     EmitDone = false;
     341       11949 :     ModifiedMF = false;
     342       11949 :   }
     343             : 
     344             :   /// mapVirtReg - Map virtual register to an equivalence class.
     345             :   void mapVirtReg(unsigned VirtReg, UserValue *EC);
     346             : 
     347             :   /// splitRegister -  Replace all references to OldReg with NewRegs.
     348             :   void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
     349             : 
     350             :   /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
     351             :   void emitDebugValues(VirtRegMap *VRM);
     352             : 
     353             :   void print(raw_ostream&);
     354             : };
     355             : 
     356             : } // end anonymous namespace
     357             : 
     358             : #ifndef NDEBUG
     359             : static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
     360             :                           const LLVMContext &Ctx) {
     361             :   if (!DL)
     362             :     return;
     363             : 
     364             :   auto *Scope = cast<DIScope>(DL.getScope());
     365             :   // Omit the directory, because it's likely to be long and uninteresting.
     366             :   CommentOS << Scope->getFilename();
     367             :   CommentOS << ':' << DL.getLine();
     368             :   if (DL.getCol() != 0)
     369             :     CommentOS << ':' << DL.getCol();
     370             : 
     371             :   DebugLoc InlinedAtDL = DL.getInlinedAt();
     372             :   if (!InlinedAtDL)
     373             :     return;
     374             : 
     375             :   CommentOS << " @[ ";
     376             :   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
     377             :   CommentOS << " ]";
     378             : }
     379             : 
     380             : static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
     381             :                               const DILocation *DL) {
     382             :   const LLVMContext &Ctx = V->getContext();
     383             :   StringRef Res = V->getName();
     384             :   if (!Res.empty())
     385             :     OS << Res << "," << V->getLine();
     386             :   if (auto *InlinedAt = DL->getInlinedAt()) {
     387             :     if (DebugLoc InlinedAtDL = InlinedAt) {
     388             :       OS << " @[";
     389             :       printDebugLoc(InlinedAtDL, OS, Ctx);
     390             :       OS << "]";
     391             :     }
     392             :   }
     393             : }
     394             : 
     395             : void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
     396             :   auto *DV = cast<DILocalVariable>(Variable);
     397             :   OS << "!\"";
     398             :   printExtendedName(OS, DV, dl);
     399             : 
     400             :   OS << "\"\t";
     401             :   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
     402             :     OS << " [" << I.start() << ';' << I.stop() << "):";
     403             :     if (I.value() == ~0u)
     404             :       OS << "undef";
     405             :     else
     406             :       OS << I.value();
     407             :   }
     408             :   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
     409             :     OS << " Loc" << i << '=';
     410             :     locations[i].print(OS, TRI);
     411             :   }
     412             :   OS << '\n';
     413             : }
     414             : 
     415             : void LDVImpl::print(raw_ostream &OS) {
     416             :   OS << "********** DEBUG VARIABLES **********\n";
     417             :   for (unsigned i = 0, e = userValues.size(); i != e; ++i)
     418             :     userValues[i]->print(OS, TRI);
     419             : }
     420             : #endif
     421             : 
     422        9323 : void UserValue::coalesceLocation(unsigned LocNo) {
     423        9323 :   unsigned KeepLoc = 0;
     424       29701 :   for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
     425       11406 :     if (KeepLoc == LocNo)
     426        9028 :       continue;
     427        7134 :     if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
     428             :       break;
     429             :   }
     430             :   // No matches.
     431       18646 :   if (KeepLoc == locations.size())
     432             :     return;
     433             : 
     434             :   // Keep the smaller location, erase the larger one.
     435         351 :   unsigned EraseLoc = LocNo;
     436         351 :   if (KeepLoc > EraseLoc)
     437             :     std::swap(KeepLoc, EraseLoc);
     438         702 :   locations.erase(locations.begin() + EraseLoc);
     439             : 
     440             :   // Rewrite values.
     441        1571 :   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
     442         869 :     unsigned v = I.value();
     443         869 :     if (v == EraseLoc)
     444         372 :       I.setValue(KeepLoc);      // Coalesce when possible.
     445         497 :     else if (v > EraseLoc)
     446          26 :       I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
     447             :   }
     448             : }
     449             : 
     450       13488 : void UserValue::mapVirtRegs(LDVImpl *LDV) {
     451       39017 :   for (unsigned i = 0, e = locations.size(); i != e; ++i)
     452       46356 :     if (locations[i].isReg() &&
     453       30699 :         TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
     454       18480 :       LDV->mapVirtReg(locations[i].getReg(), this);
     455       13488 : }
     456             : 
     457       17873 : UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr,
     458             :                                  bool IsIndirect, const DebugLoc &DL) {
     459       35746 :   UserValue *&Leader = userVarMap[Var];
     460       17873 :   if (Leader) {
     461       20100 :     UserValue *UV = Leader->getLeader();
     462       10050 :     Leader = UV;
     463       62948 :     for (; UV; UV = UV->getNext())
     464       92502 :       if (UV->match(Var, Expr, DL->getInlinedAt(), IsIndirect))
     465             :         return UV;
     466             :   }
     467             : 
     468       26976 :   userValues.push_back(
     469       26976 :       llvm::make_unique<UserValue>(Var, Expr, IsIndirect, DL, allocator));
     470       40464 :   UserValue *UV = userValues.back().get();
     471       13488 :   Leader = UserValue::merge(Leader, UV);
     472       13488 :   return UV;
     473             : }
     474             : 
     475       10011 : void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
     476             :   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
     477       20022 :   UserValue *&Leader = virtRegToEqClass[VirtReg];
     478       10011 :   Leader = UserValue::merge(Leader, EC);
     479       10011 : }
     480             : 
     481       19582 : UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
     482       39164 :   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
     483         550 :     return UV->getLeader();
     484             :   return nullptr;
     485             : }
     486             : 
     487       17873 : bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
     488             :   // DBG_VALUE loc, offset, variable
     489       35746 :   if (MI.getNumOperands() != 4 ||
     490       54263 :       !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
     491       35746 :       !MI.getOperand(2).isMetadata()) {
     492             :     DEBUG(dbgs() << "Can't handle " << MI);
     493             :     return false;
     494             :   }
     495             : 
     496             :   // Get or create the UserValue for (variable,offset).
     497       17873 :   bool IsIndirect = MI.isIndirectDebugValue();
     498             :   if (IsIndirect)
     499             :     assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
     500       17873 :   const MDNode *Var = MI.getDebugVariable();
     501       17873 :   const MDNode *Expr = MI.getDebugExpression();
     502             :   //here.
     503       17873 :   UserValue *UV = getUserValue(Var, Expr, IsIndirect, MI.getDebugLoc());
     504       17873 :   UV->addDef(Idx, MI.getOperand(0));
     505       17873 :   return true;
     506             : }
     507             : 
     508        5836 : bool LDVImpl::collectDebugValues(MachineFunction &mf) {
     509        5836 :   bool Changed = false;
     510       11672 :   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
     511             :        ++MFI) {
     512      120790 :     MachineBasicBlock *MBB = &*MFI;
     513      241580 :     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
     514     1788748 :          MBBI != MBBE;) {
     515     4996331 :       if (!MBBI->isDebugValue()) {
     516     1660415 :         ++MBBI;
     517     1660415 :         continue;
     518             :       }
     519             :       // DBG_VALUE has no slot index, use the previous instruction instead.
     520             :       SlotIndex Idx =
     521       15086 :           MBBI == MBB->begin()
     522        2041 :               ? LIS->getMBBStartIdx(MBB)
     523       33633 :               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
     524             :       // Handle consecutive DBG_VALUE instructions with the same slot index.
     525             :       do {
     526       17873 :         if (handleDebugValue(*MBBI, Idx)) {
     527       17873 :           MBBI = MBB->erase(MBBI);
     528       17873 :           Changed = true;
     529             :         } else
     530             :           ++MBBI;
     531       53437 :       } while (MBBI != MBBE && MBBI->isDebugValue());
     532             :     }
     533             :   }
     534        5836 :   return Changed;
     535             : }
     536             : 
     537             : /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
     538             : /// data-flow analysis to propagate them beyond basic block boundaries.
     539       12759 : void UserValue::extendDef(SlotIndex Idx, unsigned LocNo, LiveRange *LR,
     540             :                           const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
     541             :                           LiveIntervals &LIS) {
     542       12759 :   SlotIndex Start = Idx;
     543       25518 :   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
     544       25518 :   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
     545       38277 :   LocMap::iterator I = locInts.find(Start);
     546             : 
     547             :   // Limit to VNI's live range.
     548       12759 :   bool ToEnd = true;
     549       12759 :   if (LR && VNI) {
     550       10506 :     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
     551       10506 :     if (!Segment || Segment->valno != VNI) {
     552           0 :       if (Kills)
     553           0 :         Kills->push_back(Start);
     554           0 :       return;
     555             :     }
     556       21012 :     if (Segment->end < Stop) {
     557        3352 :       Stop = Segment->end;
     558        3352 :       ToEnd = false;
     559             :     }
     560             :   }
     561             : 
     562             :   // There could already be a short def at Start.
     563       38277 :   if (I.valid() && I.start() <= Start) {
     564             :     // Stop when meeting a different location or an already extended interval.
     565       12759 :     Start = Start.getNextSlot();
     566       38277 :     if (I.value() != LocNo || I.stop() != Start)
     567             :       return;
     568             :     // This is a one-slot placeholder. Just skip it.
     569             :     ++I;
     570             :   }
     571             : 
     572             :   // Limited by the next def.
     573        6531 :   if (I.valid() && I.start() < Stop) {
     574         232 :     Stop = I.start();
     575         232 :     ToEnd = false;
     576             :   }
     577             :   // Limited by VNI's live range.
     578       12527 :   else if (!ToEnd && Kills)
     579        2479 :     Kills->push_back(Stop);
     580             : 
     581       12759 :   if (Start < Stop)
     582       12738 :     I.insert(Start, Stop, LocNo);
     583             : }
     584             : 
     585             : void
     586        9774 : UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
     587             :                        const SmallVectorImpl<SlotIndex> &Kills,
     588             :                        SmallVectorImpl<std::pair<SlotIndex, unsigned>> &NewDefs,
     589             :                        MachineRegisterInfo &MRI, LiveIntervals &LIS) {
     590        9774 :   if (Kills.empty())
     591        9516 :     return;
     592             :   // Don't track copies from physregs, there are too many uses.
     593        4958 :   if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
     594             :     return;
     595             : 
     596             :   // Collect all the (vreg, valno) pairs that are copies of LI.
     597        2737 :   SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
     598       16104 :   for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
     599        8667 :     MachineInstr *MI = MO.getParent();
     600             :     // Copies of the full value.
     601       17118 :     if (MO.getSubReg() || !MI->isCopy())
     602        8379 :       continue;
     603        1601 :     unsigned DstReg = MI->getOperand(0).getReg();
     604             : 
     605             :     // Don't follow copies to physregs. These are usually setting up call
     606             :     // arguments, and the argument registers are always call clobbered. We are
     607             :     // better off in the source register which could be a callee-saved register,
     608             :     // or it could be spilled.
     609        1601 :     if (!TargetRegisterInfo::isVirtualRegister(DstReg))
     610             :       continue;
     611             : 
     612             :     // Is LocNo extended to reach this copy? If not, another def may be blocking
     613             :     // it, or we are looking at a wrong value of LI.
     614         702 :     SlotIndex Idx = LIS.getInstructionIndex(*MI);
     615        1341 :     LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
     616         671 :     if (!I.valid() || I.value() != LocNo)
     617             :       continue;
     618             : 
     619         288 :     if (!LIS.hasInterval(DstReg))
     620             :       continue;
     621         288 :     LiveInterval *DstLI = &LIS.getInterval(DstReg);
     622         864 :     const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
     623             :     assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
     624         576 :     CopyValues.push_back(std::make_pair(DstLI, DstVNI));
     625             :   }
     626             : 
     627        2479 :   if (CopyValues.empty())
     628             :     return;
     629             : 
     630             :   DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
     631             : 
     632             :   // Try to add defs of the copied values for each kill point.
     633         774 :   for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
     634         516 :     SlotIndex Idx = Kills[i];
     635         771 :     for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
     636         576 :       LiveInterval *DstLI = CopyValues[j].first;
     637         576 :       const VNInfo *DstVNI = CopyValues[j].second;
     638         576 :       if (DstLI->getVNInfoAt(Idx) != DstVNI)
     639         255 :         continue;
     640             :       // Check that there isn't already a def at Idx
     641          66 :       LocMap::iterator I = locInts.find(Idx);
     642          24 :       if (I.valid() && I.start() <= Idx)
     643             :         continue;
     644             :       DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
     645             :                    << DstVNI->id << " in " << *DstLI << '\n');
     646          66 :       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
     647             :       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
     648          33 :       unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
     649          66 :       I.insert(Idx, Idx.getNextSlot(), LocNo);
     650          66 :       NewDefs.push_back(std::make_pair(Idx, LocNo));
     651          33 :       break;
     652             :     }
     653             :   }
     654             : }
     655             : 
     656       13488 : void UserValue::computeIntervals(MachineRegisterInfo &MRI,
     657             :                                  const TargetRegisterInfo &TRI,
     658             :                                  LiveIntervals &LIS, LexicalScopes &LS) {
     659       15687 :   SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
     660             : 
     661             :   // Collect all defs to be extended (Skipping undefs).
     662      101216 :   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
     663       16888 :     if (I.value() != ~0u)
     664       38178 :       Defs.push_back(std::make_pair(I.start(), I.value()));
     665             : 
     666             :   // Extend all defs, and possibly add new ones along the way.
     667       52494 :   for (unsigned i = 0; i != Defs.size(); ++i) {
     668       25518 :     SlotIndex Idx = Defs[i].first;
     669       25518 :     unsigned LocNo = Defs[i].second;
     670       25518 :     const MachineOperand &Loc = locations[LocNo];
     671             : 
     672       14696 :     if (!Loc.isReg()) {
     673        1937 :       extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS);
     674       13674 :       continue;
     675             :     }
     676             : 
     677             :     // Register locations are constrained to where the register value is live.
     678       21644 :     if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
     679        9800 :       LiveInterval *LI = nullptr;
     680        9800 :       const VNInfo *VNI = nullptr;
     681       19574 :       if (LIS.hasInterval(Loc.getReg())) {
     682        9774 :         LI = &LIS.getInterval(Loc.getReg());
     683        9774 :         VNI = LI->getVNInfoAt(Idx);
     684             :       }
     685       19600 :       SmallVector<SlotIndex, 16> Kills;
     686        9800 :       extendDef(Idx, LocNo, LI, VNI, &Kills, LIS);
     687        9800 :       if (LI)
     688        9774 :         addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
     689             :       continue;
     690             :     }
     691             : 
     692             :     // For physregs, use the live range of the first regunit as a guide.
     693        3066 :     unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
     694        1022 :     LiveRange *LR = &LIS.getRegUnit(Unit);
     695        1022 :     const VNInfo *VNI = LR->getVNInfoAt(Idx);
     696             :     // Don't track copies from physregs, it is too expensive.
     697        1022 :     extendDef(Idx, LocNo, LR, VNI, nullptr, LIS);
     698             :   }
     699             : 
     700             :   // Erase all the undefs.
     701       43659 :   for (LocMap::iterator I = locInts.begin(); I.valid();)
     702       16683 :     if (I.value() == ~0u)
     703        4162 :       I.erase();
     704             :     else
     705             :       ++I;
     706             : 
     707             :   // The computed intervals may extend beyond the range of the debug
     708             :   // location's lexical scope. In this case, splitting of an interval
     709             :   // can result in an interval outside of the scope being created,
     710             :   // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
     711             :   // this, trim the intervals to the lexical scope.
     712             : 
     713       26976 :   LexicalScope *Scope = LS.findLexicalScope(dl);
     714       13488 :   if (!Scope)
     715       11289 :     return;
     716             : 
     717       12344 :   SlotIndex PrevEnd;
     718       26887 :   LocMap::iterator I = locInts.begin();
     719             : 
     720             :   // Iterate over the lexical scope ranges. Each time round the loop
     721             :   // we check the intervals for overlap with the end of the previous
     722             :   // range and the start of the next. The first range is handled as
     723             :   // a special case where there is no PrevEnd.
     724       39989 :   for (const InsnRange &Range : Scope->getRanges()) {
     725       26204 :     SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
     726       26204 :     SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
     727             : 
     728             :     // At the start of each iteration I has been advanced so that
     729             :     // I.stop() >= PrevEnd. Check for overlap.
     730       14618 :     if (PrevEnd && I.start() < PrevEnd) {
     731         277 :       SlotIndex IStop = I.stop();
     732         277 :       unsigned LocNo = I.value();
     733             : 
     734             :       // Stop overlaps previous end - trim the end of the interval to
     735             :       // the scope range.
     736         277 :       I.setStopUnchecked(PrevEnd);
     737         277 :       ++I;
     738             : 
     739             :       // If the interval also overlaps the start of the "next" (i.e.
     740             :       // current) range create a new interval for the remainder (which
     741             :       // may be further trimmed).
     742         277 :       if (RStart < IStop)
     743         160 :         I.insert(RStart, IStop, LocNo);
     744             :     }
     745             : 
     746             :     // Advance I so that I.stop() >= RStart, and check for overlap.
     747       13102 :     I.advanceTo(RStart);
     748        7918 :     if (!I.valid())
     749       10145 :       return;
     750             : 
     751       15836 :     if (I.start() < RStart) {
     752             :       // Interval start overlaps range - trim to the scope range.
     753        5384 :       I.setStartUnchecked(RStart);
     754             :       // Remember that this interval was trimmed.
     755        5384 :       trimmedDefs.insert(RStart);
     756             :     }
     757             : 
     758             :     // The end of a lexical scope range is the last instruction in the
     759             :     // range. To convert to an interval we need the index of the
     760             :     // instruction after it.
     761        7918 :     REnd = REnd.getNextIndex();
     762             : 
     763             :     // Advance I to first interval outside current range.
     764        7918 :     I.advanceTo(REnd);
     765        2957 :     if (!I.valid())
     766             :       return;
     767             : 
     768        2957 :     PrevEnd = REnd;
     769             :   }
     770             : 
     771             :   // Check for overlap with end of final range.
     772        6597 :   if (PrevEnd && I.start() < PrevEnd)
     773        1801 :     I.setStopUnchecked(PrevEnd);
     774             : }
     775             : 
     776        5836 : void LDVImpl::computeIntervals() {
     777       11672 :   LexicalScopes LS;
     778        5836 :   LS.initialize(*MF);
     779             : 
     780       25160 :   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
     781       40464 :     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
     782       40464 :     userValues[i]->mapVirtRegs(this);
     783             :   }
     784        5836 : }
     785             : 
     786        5836 : bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
     787        5836 :   clear();
     788        5836 :   MF = &mf;
     789        5836 :   LIS = &pass.getAnalysis<LiveIntervals>();
     790        5836 :   TRI = mf.getSubtarget().getRegisterInfo();
     791             :   DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
     792             :                << mf.getName() << " **********\n");
     793             : 
     794        5836 :   bool Changed = collectDebugValues(mf);
     795        5836 :   computeIntervals();
     796             :   DEBUG(print(dbgs()));
     797        5836 :   ModifiedMF = Changed;
     798        5836 :   return Changed;
     799             : }
     800             : 
     801      128999 : static void removeDebugValues(MachineFunction &mf) {
     802      549246 :   for (MachineBasicBlock &MBB : mf) {
     803     2356402 :     for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
     804     5608938 :       if (!MBBI->isDebugValue()) {
     805     1869628 :         ++MBBI;
     806     1869628 :         continue;
     807             :       }
     808          27 :       MBBI = MBB.erase(MBBI);
     809             :     }
     810             :   }
     811      128999 : }
     812             : 
     813      134835 : bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
     814      134835 :   if (!EnableLDV)
     815             :     return false;
     816      134835 :   if (!mf.getFunction()->getSubprogram()) {
     817      128999 :     removeDebugValues(mf);
     818      128999 :     return false;
     819             :   }
     820        5836 :   if (!pImpl)
     821         407 :     pImpl = new LDVImpl(this);
     822        5836 :   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
     823             : }
     824             : 
     825      134856 : void LiveDebugVariables::releaseMemory() {
     826      134856 :   if (pImpl)
     827        6113 :     static_cast<LDVImpl*>(pImpl)->clear();
     828      134856 : }
     829             : 
     830       45798 : LiveDebugVariables::~LiveDebugVariables() {
     831       15266 :   if (pImpl)
     832         407 :     delete static_cast<LDVImpl*>(pImpl);
     833       30532 : }
     834             : 
     835             : //===----------------------------------------------------------------------===//
     836             : //                           Live Range Splitting
     837             : //===----------------------------------------------------------------------===//
     838             : 
     839             : bool
     840         888 : UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
     841             :                          LiveIntervals& LIS) {
     842             :   DEBUG({
     843             :     dbgs() << "Splitting Loc" << OldLocNo << '\t';
     844             :     print(dbgs(), nullptr);
     845             :   });
     846         888 :   bool DidChange = false;
     847        1776 :   LocMap::iterator LocMapI;
     848        1776 :   LocMapI.setMap(locInts);
     849        3391 :   for (unsigned i = 0; i != NewRegs.size(); ++i) {
     850        5006 :     LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
     851        5006 :     if (LI->empty())
     852          29 :       continue;
     853             : 
     854             :     // Don't allocate the new LocNo until it is needed.
     855        2474 :     unsigned NewLocNo = ~0u;
     856             : 
     857             :     // Iterate over the overlaps between locInts and LI.
     858        4948 :     LocMapI.find(LI->beginIndex());
     859        2474 :     if (!LocMapI.valid())
     860        1105 :       continue;
     861        4107 :     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
     862        2738 :     LiveInterval::iterator LIE = LI->end();
     863        1683 :     while (LocMapI.valid() && LII != LIE) {
     864             :       // At this point, we know that LocMapI.stop() > LII->start.
     865        2696 :       LII = LI->advanceTo(LII, LocMapI.start());
     866        1348 :       if (LII == LIE)
     867             :         break;
     868             : 
     869             :       // Now LII->end > LocMapI.start(). Do we have an overlap?
     870        3496 :       if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
     871             :         // Overlapping correct location. Allocate NewLocNo now.
     872        1036 :         if (NewLocNo == ~0u) {
     873        1942 :           MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
     874        3884 :           MO.setSubReg(locations[OldLocNo].getSubReg());
     875         971 :           NewLocNo = getLocationNo(MO);
     876         971 :           DidChange = true;
     877             :         }
     878             : 
     879        1036 :         SlotIndex LStart = LocMapI.start();
     880        1036 :         SlotIndex LStop  = LocMapI.stop();
     881             : 
     882             :         // Trim LocMapI down to the LII overlap.
     883        1036 :         if (LStart < LII->start)
     884             :           LocMapI.setStartUnchecked(LII->start);
     885        1036 :         if (LStop > LII->end)
     886          29 :           LocMapI.setStopUnchecked(LII->end);
     887             : 
     888             :         // Change the value in the overlap. This may trigger coalescing.
     889        1036 :         LocMapI.setValue(NewLocNo);
     890             : 
     891             :         // Re-insert any removed OldLocNo ranges.
     892        2072 :         if (LStart < LocMapI.start()) {
     893          70 :           LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
     894             :           ++LocMapI;
     895             :           assert(LocMapI.valid() && "Unexpected coalescing");
     896             :         }
     897        2072 :         if (LStop > LocMapI.stop()) {
     898          29 :           ++LocMapI;
     899          29 :           LocMapI.insert(LII->end, LStop, OldLocNo);
     900             :           --LocMapI;
     901             :         }
     902             :       }
     903             : 
     904             :       // Advance to the next overlap.
     905        2696 :       if (LII->end < LocMapI.stop()) {
     906          91 :         if (++LII == LIE)
     907             :           break;
     908          15 :         LocMapI.advanceTo(LII->start);
     909             :       } else {
     910        1257 :         ++LocMapI;
     911         305 :         if (!LocMapI.valid())
     912             :           break;
     913         610 :         LII = LI->advanceTo(LII, LocMapI.start());
     914             :       }
     915             :     }
     916             :   }
     917             : 
     918             :   // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
     919        2664 :   locations.erase(locations.begin() + OldLocNo);
     920         888 :   LocMapI.goToBegin();
     921        1292 :   while (LocMapI.valid()) {
     922        1292 :     unsigned v = LocMapI.value();
     923        1292 :     if (v == OldLocNo) {
     924             :       DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
     925             :                    << LocMapI.stop() << ")\n");
     926          14 :       LocMapI.erase();
     927             :     } else {
     928        1278 :       if (v > OldLocNo)
     929        1110 :         LocMapI.setValueUnchecked(v-1);
     930             :       ++LocMapI;
     931             :     }
     932             :   }
     933             : 
     934             :   DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
     935        1776 :   return DidChange;
     936             : }
     937             : 
     938             : bool
     939        3254 : UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
     940             :                          LiveIntervals &LIS) {
     941        3254 :   bool DidChange = false;
     942             :   // Split locations referring to OldReg. Iterate backwards so splitLocation can
     943             :   // safely erase unused locations.
     944        6508 :   for (unsigned i = locations.size(); i ; --i) {
     945        3457 :     unsigned LocNo = i-1;
     946        6914 :     const MachineOperand *Loc = &locations[LocNo];
     947        3457 :     if (!Loc->isReg() || Loc->getReg() != OldReg)
     948        2569 :       continue;
     949         888 :     DidChange |= splitLocation(LocNo, NewRegs, LIS);
     950             :   }
     951        3254 :   return DidChange;
     952             : }
     953             : 
     954       19309 : void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
     955       19309 :   bool DidChange = false;
     956       22563 :   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
     957        3254 :     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
     958             : 
     959       19309 :   if (!DidChange)
     960             :     return;
     961             : 
     962             :   // Map all of the new virtual registers.
     963         273 :   UserValue *UV = lookupVirtReg(OldReg);
     964        1044 :   for (unsigned i = 0; i != NewRegs.size(); ++i)
     965        1542 :     mapVirtReg(NewRegs[i], UV);
     966             : }
     967             : 
     968       26760 : void LiveDebugVariables::
     969             : splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
     970       26760 :   if (pImpl)
     971       19309 :     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
     972       26760 : }
     973             : 
     974             : void
     975       13488 : UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
     976             :   // Iterate over locations in reverse makes it easier to handle coalescing.
     977       26976 :   for (unsigned i = locations.size(); i ; --i) {
     978       12124 :     unsigned LocNo = i-1;
     979       24248 :     MachineOperand &Loc = locations[LocNo];
     980             :     // Only virtual registers are rewritten.
     981       22440 :     if (!Loc.isReg() || !Loc.getReg() ||
     982       20632 :         !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
     983        2801 :       continue;
     984        9323 :     unsigned VirtReg = Loc.getReg();
     985        9125 :     if (VRM.isAssignedReg(VirtReg) &&
     986       18250 :         TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
     987             :       // This can create a %noreg operand in rare cases when the sub-register
     988             :       // index is no longer available. That means the user value is in a
     989             :       // non-existent sub-register, and %noreg is exactly what we want.
     990        9049 :       Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
     991         274 :     } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
     992             :       // FIXME: Translate SubIdx to a stackslot offset.
     993         396 :       Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
     994             :     } else {
     995          76 :       Loc.setReg(0);
     996             :       Loc.setSubReg(0);
     997             :     }
     998        9323 :     coalesceLocation(LocNo);
     999             :   }
    1000       13488 : }
    1001             : 
    1002             : /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
    1003             : /// instruction.
    1004             : static MachineBasicBlock::iterator
    1005       12706 : findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
    1006             :                    LiveIntervals &LIS) {
    1007       25412 :   SlotIndex Start = LIS.getMBBStartIdx(MBB);
    1008       12706 :   Idx = Idx.getBaseIndex();
    1009             : 
    1010             :   // Try to find an insert location by going backwards from Idx.
    1011             :   MachineInstr *MI;
    1012       32117 :   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
    1013             :     // We've reached the beginning of MBB.
    1014        4761 :     if (Idx == Start) {
    1015        2526 :       MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
    1016        2526 :       return I;
    1017             :     }
    1018        2235 :     Idx = Idx.getPrevIndex();
    1019             :   }
    1020             : 
    1021             :   // Don't insert anything after the first terminator, though.
    1022       10180 :   return MI->isTerminator() ? MBB->getFirstTerminator() :
    1023       20356 :                               std::next(MachineBasicBlock::iterator(MI));
    1024             : }
    1025             : 
    1026       12706 : void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
    1027             :                                  unsigned LocNo,
    1028             :                                  LiveIntervals &LIS,
    1029             :                                  const TargetInstrInfo &TII) {
    1030       12706 :   MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
    1031       25412 :   MachineOperand &Loc = locations[LocNo];
    1032       12706 :   ++NumInsertedDebugValues;
    1033             : 
    1034             :   assert(cast<DILocalVariable>(Variable)
    1035             :              ->isValidLocationForIntrinsic(getDebugLoc()) &&
    1036             :          "Expected inlined-at fields to agree");
    1037       12706 :   if (Loc.isReg())
    1038       21174 :     BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
    1039       21174 :             IsIndirect, Loc.getReg(), Variable, Expression);
    1040             :   else
    1041       10595 :     BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
    1042        2119 :         .add(Loc)
    1043        2119 :         .addImm(0U)
    1044        4238 :         .addMetadata(Variable)
    1045        4238 :         .addMetadata(Expression);
    1046       12706 : }
    1047             : 
    1048       13488 : void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
    1049             :                                 const TargetInstrInfo &TII) {
    1050       26976 :   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
    1051             : 
    1052       92804 :   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
    1053       12682 :     SlotIndex Start = I.start();
    1054       12682 :     SlotIndex Stop = I.stop();
    1055       12682 :     unsigned LocNo = I.value();
    1056             : 
    1057             :     // If the interval start was trimmed to the lexical scope insert the
    1058             :     // DBG_VALUE at the previous index (otherwise it appears after the
    1059             :     // first instruction in the range).
    1060       12682 :     if (trimmedDefs.count(Start))
    1061        5384 :       Start = Start.getPrevIndex();
    1062             : 
    1063             :     DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
    1064       38046 :     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
    1065       25364 :     SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
    1066             : 
    1067             :     DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
    1068       12682 :     insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
    1069             :     // This interval may span multiple basic blocks.
    1070             :     // Insert a DBG_VALUE into each one.
    1071       12730 :     while(Stop > MBBEnd) {
    1072             :       // Move to the next block.
    1073          24 :       Start = MBBEnd;
    1074          24 :       if (++MBB == MFEnd)
    1075             :         break;
    1076          48 :       MBBEnd = LIS.getMBBEndIdx(&*MBB);
    1077             :       DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
    1078          24 :       insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
    1079             :     }
    1080             :     DEBUG(dbgs() << '\n');
    1081       12682 :     if (MBB == MFEnd)
    1082             :       break;
    1083             : 
    1084       12682 :     ++I;
    1085             :   }
    1086       13488 : }
    1087             : 
    1088        6113 : void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
    1089             :   DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
    1090        6113 :   if (!MF)
    1091             :     return;
    1092        5836 :   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
    1093       25160 :   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
    1094             :     DEBUG(userValues[i]->print(dbgs(), TRI));
    1095       40464 :     userValues[i]->rewriteLocations(*VRM, *TRI);
    1096       40464 :     userValues[i]->emitDebugValues(VRM, *LIS, *TII);
    1097             :   }
    1098        5836 :   EmitDone = true;
    1099             : }
    1100             : 
    1101      134820 : void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
    1102      134820 :   if (pImpl)
    1103        6113 :     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
    1104      134820 : }
    1105             : 
    1106       15361 : bool LiveDebugVariables::doInitialization(Module &M) {
    1107       15361 :   return Pass::doInitialization(M);
    1108      216918 : }
    1109             : 
    1110             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
    1111             : LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
    1112             :   if (pImpl)
    1113             :     static_cast<LDVImpl*>(pImpl)->print(dbgs());
    1114             : }
    1115             : #endif

Generated by: LCOV version 1.13