Home | History | Annotate | Download | only in CodeGen
      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 #define DEBUG_TYPE "livedebug"
     23 #include "LiveDebugVariables.h"
     24 #include "llvm/ADT/IntervalMap.h"
     25 #include "llvm/ADT/Statistic.h"
     26 #include "llvm/CodeGen/LexicalScopes.h"
     27 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
     28 #include "llvm/CodeGen/MachineDominators.h"
     29 #include "llvm/CodeGen/MachineFunction.h"
     30 #include "llvm/CodeGen/MachineInstrBuilder.h"
     31 #include "llvm/CodeGen/MachineRegisterInfo.h"
     32 #include "llvm/CodeGen/Passes.h"
     33 #include "llvm/CodeGen/VirtRegMap.h"
     34 #include "llvm/DebugInfo.h"
     35 #include "llvm/IR/Constants.h"
     36 #include "llvm/IR/Metadata.h"
     37 #include "llvm/IR/Value.h"
     38 #include "llvm/Support/CommandLine.h"
     39 #include "llvm/Support/Debug.h"
     40 #include "llvm/Target/TargetInstrInfo.h"
     41 #include "llvm/Target/TargetMachine.h"
     42 #include "llvm/Target/TargetRegisterInfo.h"
     43 
     44 using namespace llvm;
     45 
     46 static cl::opt<bool>
     47 EnableLDV("live-debug-variables", cl::init(true),
     48           cl::desc("Enable the live debug variables pass"), cl::Hidden);
     49 
     50 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
     51 char LiveDebugVariables::ID = 0;
     52 
     53 INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
     54                 "Debug Variable Analysis", false, false)
     55 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
     56 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
     57 INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
     58                 "Debug Variable Analysis", false, false)
     59 
     60 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
     61   AU.addRequired<MachineDominatorTree>();
     62   AU.addRequiredTransitive<LiveIntervals>();
     63   AU.setPreservesAll();
     64   MachineFunctionPass::getAnalysisUsage(AU);
     65 }
     66 
     67 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(0) {
     68   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
     69 }
     70 
     71 /// LocMap - Map of where a user value is live, and its location.
     72 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
     73 
     74 namespace {
     75 /// UserValueScopes - Keeps track of lexical scopes associated with an
     76 /// user value's source location.
     77 class UserValueScopes {
     78   DebugLoc DL;
     79   LexicalScopes &LS;
     80   SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
     81 
     82 public:
     83   UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(D), LS(L) {}
     84 
     85   /// dominates - Return true if current scope dominates at least one machine
     86   /// instruction in a given machine basic block.
     87   bool dominates(MachineBasicBlock *MBB) {
     88     if (LBlocks.empty())
     89       LS.getMachineBasicBlocks(DL, LBlocks);
     90     if (LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB))
     91       return true;
     92     return false;
     93   }
     94 };
     95 } // end anonymous namespace
     96 
     97 /// UserValue - A user value is a part of a debug info user variable.
     98 ///
     99 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
    100 /// holds part of a user variable. The part is identified by a byte offset.
    101 ///
    102 /// UserValues are grouped into equivalence classes for easier searching. Two
    103 /// user values are related if they refer to the same variable, or if they are
    104 /// held by the same virtual register. The equivalence class is the transitive
    105 /// closure of that relation.
    106 namespace {
    107 class LDVImpl;
    108 class UserValue {
    109   const MDNode *variable; ///< The debug info variable we are part of.
    110   unsigned offset;        ///< Byte offset into variable.
    111   bool IsIndirect;        ///< true if this is a register-indirect+offset value.
    112   DebugLoc dl;            ///< The debug location for the variable. This is
    113                           ///< used by dwarf writer to find lexical scope.
    114   UserValue *leader;      ///< Equivalence class leader.
    115   UserValue *next;        ///< Next value in equivalence class, or null.
    116 
    117   /// Numbered locations referenced by locmap.
    118   SmallVector<MachineOperand, 4> locations;
    119 
    120   /// Map of slot indices where this value is live.
    121   LocMap locInts;
    122 
    123   /// coalesceLocation - After LocNo was changed, check if it has become
    124   /// identical to another location, and coalesce them. This may cause LocNo or
    125   /// a later location to be erased, but no earlier location will be erased.
    126   void coalesceLocation(unsigned LocNo);
    127 
    128   /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
    129   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
    130                         LiveIntervals &LIS, const TargetInstrInfo &TII);
    131 
    132   /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
    133   /// is live. Returns true if any changes were made.
    134   bool splitLocation(unsigned OldLocNo, ArrayRef<LiveInterval*> NewRegs);
    135 
    136 public:
    137   /// UserValue - Create a new UserValue.
    138   UserValue(const MDNode *var, unsigned o, bool i, DebugLoc L,
    139             LocMap::Allocator &alloc)
    140     : variable(var), offset(o), IsIndirect(i), dl(L), leader(this),
    141       next(0), locInts(alloc)
    142   {}
    143 
    144   /// getLeader - Get the leader of this value's equivalence class.
    145   UserValue *getLeader() {
    146     UserValue *l = leader;
    147     while (l != l->leader)
    148       l = l->leader;
    149     return leader = l;
    150   }
    151 
    152   /// getNext - Return the next UserValue in the equivalence class.
    153   UserValue *getNext() const { return next; }
    154 
    155   /// match - Does this UserValue match the parameters?
    156   bool match(const MDNode *Var, unsigned Offset) const {
    157     return Var == variable && Offset == offset;
    158   }
    159 
    160   /// merge - Merge equivalence classes.
    161   static UserValue *merge(UserValue *L1, UserValue *L2) {
    162     L2 = L2->getLeader();
    163     if (!L1)
    164       return L2;
    165     L1 = L1->getLeader();
    166     if (L1 == L2)
    167       return L1;
    168     // Splice L2 before L1's members.
    169     UserValue *End = L2;
    170     while (End->next)
    171       End->leader = L1, End = End->next;
    172     End->leader = L1;
    173     End->next = L1->next;
    174     L1->next = L2;
    175     return L1;
    176   }
    177 
    178   /// getLocationNo - Return the location number that matches Loc.
    179   unsigned getLocationNo(const MachineOperand &LocMO) {
    180     if (LocMO.isReg()) {
    181       if (LocMO.getReg() == 0)
    182         return ~0u;
    183       // For register locations we dont care about use/def and other flags.
    184       for (unsigned i = 0, e = locations.size(); i != e; ++i)
    185         if (locations[i].isReg() &&
    186             locations[i].getReg() == LocMO.getReg() &&
    187             locations[i].getSubReg() == LocMO.getSubReg())
    188           return i;
    189     } else
    190       for (unsigned i = 0, e = locations.size(); i != e; ++i)
    191         if (LocMO.isIdenticalTo(locations[i]))
    192           return i;
    193     locations.push_back(LocMO);
    194     // We are storing a MachineOperand outside a MachineInstr.
    195     locations.back().clearParent();
    196     // Don't store def operands.
    197     if (locations.back().isReg())
    198       locations.back().setIsUse();
    199     return locations.size() - 1;
    200   }
    201 
    202   /// mapVirtRegs - Ensure that all virtual register locations are mapped.
    203   void mapVirtRegs(LDVImpl *LDV);
    204 
    205   /// addDef - Add a definition point to this value.
    206   void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
    207     // Add a singular (Idx,Idx) -> Loc mapping.
    208     LocMap::iterator I = locInts.find(Idx);
    209     if (!I.valid() || I.start() != Idx)
    210       I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
    211     else
    212       // A later DBG_VALUE at the same SlotIndex overrides the old location.
    213       I.setValue(getLocationNo(LocMO));
    214   }
    215 
    216   /// extendDef - Extend the current definition as far as possible down the
    217   /// dominator tree. Stop when meeting an existing def or when leaving the live
    218   /// range of VNI.
    219   /// End points where VNI is no longer live are added to Kills.
    220   /// @param Idx   Starting point for the definition.
    221   /// @param LocNo Location number to propagate.
    222   /// @param LI    Restrict liveness to where LI has the value VNI. May be null.
    223   /// @param VNI   When LI is not null, this is the value to restrict to.
    224   /// @param Kills Append end points of VNI's live range to Kills.
    225   /// @param LIS   Live intervals analysis.
    226   /// @param MDT   Dominator tree.
    227   void extendDef(SlotIndex Idx, unsigned LocNo,
    228                  LiveInterval *LI, const VNInfo *VNI,
    229                  SmallVectorImpl<SlotIndex> *Kills,
    230                  LiveIntervals &LIS, MachineDominatorTree &MDT,
    231                  UserValueScopes &UVS);
    232 
    233   /// addDefsFromCopies - The value in LI/LocNo may be copies to other
    234   /// registers. Determine if any of the copies are available at the kill
    235   /// points, and add defs if possible.
    236   /// @param LI      Scan for copies of the value in LI->reg.
    237   /// @param LocNo   Location number of LI->reg.
    238   /// @param Kills   Points where the range of LocNo could be extended.
    239   /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
    240   void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
    241                       const SmallVectorImpl<SlotIndex> &Kills,
    242                       SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
    243                       MachineRegisterInfo &MRI,
    244                       LiveIntervals &LIS);
    245 
    246   /// computeIntervals - Compute the live intervals of all locations after
    247   /// collecting all their def points.
    248   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
    249                         LiveIntervals &LIS, MachineDominatorTree &MDT,
    250                         UserValueScopes &UVS);
    251 
    252   /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
    253   /// live. Returns true if any changes were made.
    254   bool splitRegister(unsigned OldLocNo, ArrayRef<LiveInterval*> NewRegs);
    255 
    256   /// rewriteLocations - Rewrite virtual register locations according to the
    257   /// provided virtual register map.
    258   void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
    259 
    260   /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
    261   void emitDebugValues(VirtRegMap *VRM,
    262                        LiveIntervals &LIS, const TargetInstrInfo &TRI);
    263 
    264   /// findDebugLoc - Return DebugLoc used for this DBG_VALUE instruction. A
    265   /// variable may have more than one corresponding DBG_VALUE instructions.
    266   /// Only first one needs DebugLoc to identify variable's lexical scope
    267   /// in source file.
    268   DebugLoc findDebugLoc();
    269 
    270   /// getDebugLoc - Return DebugLoc of this UserValue.
    271   DebugLoc getDebugLoc() { return dl;}
    272   void print(raw_ostream&, const TargetMachine*);
    273 };
    274 } // namespace
    275 
    276 /// LDVImpl - Implementation of the LiveDebugVariables pass.
    277 namespace {
    278 class LDVImpl {
    279   LiveDebugVariables &pass;
    280   LocMap::Allocator allocator;
    281   MachineFunction *MF;
    282   LiveIntervals *LIS;
    283   LexicalScopes LS;
    284   MachineDominatorTree *MDT;
    285   const TargetRegisterInfo *TRI;
    286 
    287   /// Whether emitDebugValues is called.
    288   bool EmitDone;
    289   /// Whether the machine function is modified during the pass.
    290   bool ModifiedMF;
    291 
    292   /// userValues - All allocated UserValue instances.
    293   SmallVector<UserValue*, 8> userValues;
    294 
    295   /// Map virtual register to eq class leader.
    296   typedef DenseMap<unsigned, UserValue*> VRMap;
    297   VRMap virtRegToEqClass;
    298 
    299   /// Map user variable to eq class leader.
    300   typedef DenseMap<const MDNode *, UserValue*> UVMap;
    301   UVMap userVarMap;
    302 
    303   /// getUserValue - Find or create a UserValue.
    304   UserValue *getUserValue(const MDNode *Var, unsigned Offset,
    305                           bool IsIndirect, 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   LDVImpl(LiveDebugVariables *ps) : pass(*ps), EmitDone(false),
    328                                     ModifiedMF(false) {}
    329   bool runOnMachineFunction(MachineFunction &mf);
    330 
    331   /// clear - Release all memory.
    332   void clear() {
    333     DeleteContainerPointers(userValues);
    334     userValues.clear();
    335     virtRegToEqClass.clear();
    336     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     EmitDone = false;
    341     ModifiedMF = false;
    342   }
    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<LiveInterval*> NewRegs);
    349 
    350   /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
    351   void emitDebugValues(VirtRegMap *VRM);
    352 
    353   void print(raw_ostream&);
    354 };
    355 } // namespace
    356 
    357 void UserValue::print(raw_ostream &OS, const TargetMachine *TM) {
    358   DIVariable DV(variable);
    359   OS << "!\"";
    360   DV.printExtendedName(OS);
    361   OS << "\"\t";
    362   if (offset)
    363     OS << '+' << offset;
    364   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
    365     OS << " [" << I.start() << ';' << I.stop() << "):";
    366     if (I.value() == ~0u)
    367       OS << "undef";
    368     else
    369       OS << I.value();
    370   }
    371   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
    372     OS << " Loc" << i << '=';
    373     locations[i].print(OS, TM);
    374   }
    375   OS << '\n';
    376 }
    377 
    378 void LDVImpl::print(raw_ostream &OS) {
    379   OS << "********** DEBUG VARIABLES **********\n";
    380   for (unsigned i = 0, e = userValues.size(); i != e; ++i)
    381     userValues[i]->print(OS, &MF->getTarget());
    382 }
    383 
    384 void UserValue::coalesceLocation(unsigned LocNo) {
    385   unsigned KeepLoc = 0;
    386   for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
    387     if (KeepLoc == LocNo)
    388       continue;
    389     if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
    390       break;
    391   }
    392   // No matches.
    393   if (KeepLoc == locations.size())
    394     return;
    395 
    396   // Keep the smaller location, erase the larger one.
    397   unsigned EraseLoc = LocNo;
    398   if (KeepLoc > EraseLoc)
    399     std::swap(KeepLoc, EraseLoc);
    400   locations.erase(locations.begin() + EraseLoc);
    401 
    402   // Rewrite values.
    403   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
    404     unsigned v = I.value();
    405     if (v == EraseLoc)
    406       I.setValue(KeepLoc);      // Coalesce when possible.
    407     else if (v > EraseLoc)
    408       I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
    409   }
    410 }
    411 
    412 void UserValue::mapVirtRegs(LDVImpl *LDV) {
    413   for (unsigned i = 0, e = locations.size(); i != e; ++i)
    414     if (locations[i].isReg() &&
    415         TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
    416       LDV->mapVirtReg(locations[i].getReg(), this);
    417 }
    418 
    419 UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset,
    420                                  bool IsIndirect, DebugLoc DL) {
    421   UserValue *&Leader = userVarMap[Var];
    422   if (Leader) {
    423     UserValue *UV = Leader->getLeader();
    424     Leader = UV;
    425     for (; UV; UV = UV->getNext())
    426       if (UV->match(Var, Offset))
    427         return UV;
    428   }
    429 
    430   UserValue *UV = new UserValue(Var, Offset, IsIndirect, DL, allocator);
    431   userValues.push_back(UV);
    432   Leader = UserValue::merge(Leader, UV);
    433   return UV;
    434 }
    435 
    436 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
    437   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
    438   UserValue *&Leader = virtRegToEqClass[VirtReg];
    439   Leader = UserValue::merge(Leader, EC);
    440 }
    441 
    442 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
    443   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
    444     return UV->getLeader();
    445   return 0;
    446 }
    447 
    448 bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
    449   // DBG_VALUE loc, offset, variable
    450   if (MI->getNumOperands() != 3 ||
    451       !(MI->getOperand(1).isReg() || MI->getOperand(1).isImm()) ||
    452       !MI->getOperand(2).isMetadata()) {
    453     DEBUG(dbgs() << "Can't handle " << *MI);
    454     return false;
    455   }
    456 
    457   // Get or create the UserValue for (variable,offset).
    458   bool IsIndirect = MI->getOperand(1).isImm();
    459   unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
    460   const MDNode *Var = MI->getOperand(2).getMetadata();
    461   UserValue *UV = getUserValue(Var, Offset, IsIndirect, MI->getDebugLoc());
    462   UV->addDef(Idx, MI->getOperand(0));
    463   return true;
    464 }
    465 
    466 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
    467   bool Changed = false;
    468   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
    469        ++MFI) {
    470     MachineBasicBlock *MBB = MFI;
    471     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
    472          MBBI != MBBE;) {
    473       if (!MBBI->isDebugValue()) {
    474         ++MBBI;
    475         continue;
    476       }
    477       // DBG_VALUE has no slot index, use the previous instruction instead.
    478       SlotIndex Idx = MBBI == MBB->begin() ?
    479         LIS->getMBBStartIdx(MBB) :
    480         LIS->getInstructionIndex(llvm::prior(MBBI)).getRegSlot();
    481       // Handle consecutive DBG_VALUE instructions with the same slot index.
    482       do {
    483         if (handleDebugValue(MBBI, Idx)) {
    484           MBBI = MBB->erase(MBBI);
    485           Changed = true;
    486         } else
    487           ++MBBI;
    488       } while (MBBI != MBBE && MBBI->isDebugValue());
    489     }
    490   }
    491   return Changed;
    492 }
    493 
    494 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
    495                           LiveInterval *LI, const VNInfo *VNI,
    496                           SmallVectorImpl<SlotIndex> *Kills,
    497                           LiveIntervals &LIS, MachineDominatorTree &MDT,
    498                           UserValueScopes &UVS) {
    499   SmallVector<SlotIndex, 16> Todo;
    500   Todo.push_back(Idx);
    501   do {
    502     SlotIndex Start = Todo.pop_back_val();
    503     MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
    504     SlotIndex Stop = LIS.getMBBEndIdx(MBB);
    505     LocMap::iterator I = locInts.find(Start);
    506 
    507     // Limit to VNI's live range.
    508     bool ToEnd = true;
    509     if (LI && VNI) {
    510       LiveRange *Range = LI->getLiveRangeContaining(Start);
    511       if (!Range || Range->valno != VNI) {
    512         if (Kills)
    513           Kills->push_back(Start);
    514         continue;
    515       }
    516       if (Range->end < Stop)
    517         Stop = Range->end, ToEnd = false;
    518     }
    519 
    520     // There could already be a short def at Start.
    521     if (I.valid() && I.start() <= Start) {
    522       // Stop when meeting a different location or an already extended interval.
    523       Start = Start.getNextSlot();
    524       if (I.value() != LocNo || I.stop() != Start)
    525         continue;
    526       // This is a one-slot placeholder. Just skip it.
    527       ++I;
    528     }
    529 
    530     // Limited by the next def.
    531     if (I.valid() && I.start() < Stop)
    532       Stop = I.start(), ToEnd = false;
    533     // Limited by VNI's live range.
    534     else if (!ToEnd && Kills)
    535       Kills->push_back(Stop);
    536 
    537     if (Start >= Stop)
    538       continue;
    539 
    540     I.insert(Start, Stop, LocNo);
    541 
    542     // If we extended to the MBB end, propagate down the dominator tree.
    543     if (!ToEnd)
    544       continue;
    545     const std::vector<MachineDomTreeNode*> &Children =
    546       MDT.getNode(MBB)->getChildren();
    547     for (unsigned i = 0, e = Children.size(); i != e; ++i) {
    548       MachineBasicBlock *MBB = Children[i]->getBlock();
    549       if (UVS.dominates(MBB))
    550         Todo.push_back(LIS.getMBBStartIdx(MBB));
    551     }
    552   } while (!Todo.empty());
    553 }
    554 
    555 void
    556 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
    557                       const SmallVectorImpl<SlotIndex> &Kills,
    558                       SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
    559                       MachineRegisterInfo &MRI, LiveIntervals &LIS) {
    560   if (Kills.empty())
    561     return;
    562   // Don't track copies from physregs, there are too many uses.
    563   if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
    564     return;
    565 
    566   // Collect all the (vreg, valno) pairs that are copies of LI.
    567   SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
    568   for (MachineRegisterInfo::use_nodbg_iterator
    569          UI = MRI.use_nodbg_begin(LI->reg),
    570          UE = MRI.use_nodbg_end(); UI != UE; ++UI) {
    571     // Copies of the full value.
    572     if (UI.getOperand().getSubReg() || !UI->isCopy())
    573       continue;
    574     MachineInstr *MI = &*UI;
    575     unsigned DstReg = MI->getOperand(0).getReg();
    576 
    577     // Don't follow copies to physregs. These are usually setting up call
    578     // arguments, and the argument registers are always call clobbered. We are
    579     // better off in the source register which could be a callee-saved register,
    580     // or it could be spilled.
    581     if (!TargetRegisterInfo::isVirtualRegister(DstReg))
    582       continue;
    583 
    584     // Is LocNo extended to reach this copy? If not, another def may be blocking
    585     // it, or we are looking at a wrong value of LI.
    586     SlotIndex Idx = LIS.getInstructionIndex(MI);
    587     LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
    588     if (!I.valid() || I.value() != LocNo)
    589       continue;
    590 
    591     if (!LIS.hasInterval(DstReg))
    592       continue;
    593     LiveInterval *DstLI = &LIS.getInterval(DstReg);
    594     const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
    595     assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
    596     CopyValues.push_back(std::make_pair(DstLI, DstVNI));
    597   }
    598 
    599   if (CopyValues.empty())
    600     return;
    601 
    602   DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
    603 
    604   // Try to add defs of the copied values for each kill point.
    605   for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
    606     SlotIndex Idx = Kills[i];
    607     for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
    608       LiveInterval *DstLI = CopyValues[j].first;
    609       const VNInfo *DstVNI = CopyValues[j].second;
    610       if (DstLI->getVNInfoAt(Idx) != DstVNI)
    611         continue;
    612       // Check that there isn't already a def at Idx
    613       LocMap::iterator I = locInts.find(Idx);
    614       if (I.valid() && I.start() <= Idx)
    615         continue;
    616       DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
    617                    << DstVNI->id << " in " << *DstLI << '\n');
    618       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
    619       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
    620       unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
    621       I.insert(Idx, Idx.getNextSlot(), LocNo);
    622       NewDefs.push_back(std::make_pair(Idx, LocNo));
    623       break;
    624     }
    625   }
    626 }
    627 
    628 void
    629 UserValue::computeIntervals(MachineRegisterInfo &MRI,
    630                             const TargetRegisterInfo &TRI,
    631                             LiveIntervals &LIS,
    632                             MachineDominatorTree &MDT,
    633                             UserValueScopes &UVS) {
    634   SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
    635 
    636   // Collect all defs to be extended (Skipping undefs).
    637   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
    638     if (I.value() != ~0u)
    639       Defs.push_back(std::make_pair(I.start(), I.value()));
    640 
    641   // Extend all defs, and possibly add new ones along the way.
    642   for (unsigned i = 0; i != Defs.size(); ++i) {
    643     SlotIndex Idx = Defs[i].first;
    644     unsigned LocNo = Defs[i].second;
    645     const MachineOperand &Loc = locations[LocNo];
    646 
    647     if (!Loc.isReg()) {
    648       extendDef(Idx, LocNo, 0, 0, 0, LIS, MDT, UVS);
    649       continue;
    650     }
    651 
    652     // Register locations are constrained to where the register value is live.
    653     if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
    654       LiveInterval *LI = 0;
    655       const VNInfo *VNI = 0;
    656       if (LIS.hasInterval(Loc.getReg())) {
    657         LI = &LIS.getInterval(Loc.getReg());
    658         VNI = LI->getVNInfoAt(Idx);
    659       }
    660       SmallVector<SlotIndex, 16> Kills;
    661       extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, UVS);
    662       if (LI)
    663         addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
    664       continue;
    665     }
    666 
    667     // For physregs, use the live range of the first regunit as a guide.
    668     unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
    669     LiveInterval *LI = &LIS.getRegUnit(Unit);
    670     const VNInfo *VNI = LI->getVNInfoAt(Idx);
    671     // Don't track copies from physregs, it is too expensive.
    672     extendDef(Idx, LocNo, LI, VNI, 0, LIS, MDT, UVS);
    673   }
    674 
    675   // Finally, erase all the undefs.
    676   for (LocMap::iterator I = locInts.begin(); I.valid();)
    677     if (I.value() == ~0u)
    678       I.erase();
    679     else
    680       ++I;
    681 }
    682 
    683 void LDVImpl::computeIntervals() {
    684   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
    685     UserValueScopes UVS(userValues[i]->getDebugLoc(), LS);
    686     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, *MDT, UVS);
    687     userValues[i]->mapVirtRegs(this);
    688   }
    689 }
    690 
    691 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
    692   MF = &mf;
    693   LIS = &pass.getAnalysis<LiveIntervals>();
    694   MDT = &pass.getAnalysis<MachineDominatorTree>();
    695   TRI = mf.getTarget().getRegisterInfo();
    696   clear();
    697   LS.initialize(mf);
    698   DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
    699                << mf.getName() << " **********\n");
    700 
    701   bool Changed = collectDebugValues(mf);
    702   computeIntervals();
    703   DEBUG(print(dbgs()));
    704   LS.releaseMemory();
    705   ModifiedMF = Changed;
    706   return Changed;
    707 }
    708 
    709 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
    710   if (!EnableLDV)
    711     return false;
    712   if (!pImpl)
    713     pImpl = new LDVImpl(this);
    714   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
    715 }
    716 
    717 void LiveDebugVariables::releaseMemory() {
    718   if (pImpl)
    719     static_cast<LDVImpl*>(pImpl)->clear();
    720 }
    721 
    722 LiveDebugVariables::~LiveDebugVariables() {
    723   if (pImpl)
    724     delete static_cast<LDVImpl*>(pImpl);
    725 }
    726 
    727 //===----------------------------------------------------------------------===//
    728 //                           Live Range Splitting
    729 //===----------------------------------------------------------------------===//
    730 
    731 bool
    732 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<LiveInterval*> NewRegs) {
    733   DEBUG({
    734     dbgs() << "Splitting Loc" << OldLocNo << '\t';
    735     print(dbgs(), 0);
    736   });
    737   bool DidChange = false;
    738   LocMap::iterator LocMapI;
    739   LocMapI.setMap(locInts);
    740   for (unsigned i = 0; i != NewRegs.size(); ++i) {
    741     LiveInterval *LI = NewRegs[i];
    742     if (LI->empty())
    743       continue;
    744 
    745     // Don't allocate the new LocNo until it is needed.
    746     unsigned NewLocNo = ~0u;
    747 
    748     // Iterate over the overlaps between locInts and LI.
    749     LocMapI.find(LI->beginIndex());
    750     if (!LocMapI.valid())
    751       continue;
    752     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
    753     LiveInterval::iterator LIE = LI->end();
    754     while (LocMapI.valid() && LII != LIE) {
    755       // At this point, we know that LocMapI.stop() > LII->start.
    756       LII = LI->advanceTo(LII, LocMapI.start());
    757       if (LII == LIE)
    758         break;
    759 
    760       // Now LII->end > LocMapI.start(). Do we have an overlap?
    761       if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
    762         // Overlapping correct location. Allocate NewLocNo now.
    763         if (NewLocNo == ~0u) {
    764           MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
    765           MO.setSubReg(locations[OldLocNo].getSubReg());
    766           NewLocNo = getLocationNo(MO);
    767           DidChange = true;
    768         }
    769 
    770         SlotIndex LStart = LocMapI.start();
    771         SlotIndex LStop  = LocMapI.stop();
    772 
    773         // Trim LocMapI down to the LII overlap.
    774         if (LStart < LII->start)
    775           LocMapI.setStartUnchecked(LII->start);
    776         if (LStop > LII->end)
    777           LocMapI.setStopUnchecked(LII->end);
    778 
    779         // Change the value in the overlap. This may trigger coalescing.
    780         LocMapI.setValue(NewLocNo);
    781 
    782         // Re-insert any removed OldLocNo ranges.
    783         if (LStart < LocMapI.start()) {
    784           LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
    785           ++LocMapI;
    786           assert(LocMapI.valid() && "Unexpected coalescing");
    787         }
    788         if (LStop > LocMapI.stop()) {
    789           ++LocMapI;
    790           LocMapI.insert(LII->end, LStop, OldLocNo);
    791           --LocMapI;
    792         }
    793       }
    794 
    795       // Advance to the next overlap.
    796       if (LII->end < LocMapI.stop()) {
    797         if (++LII == LIE)
    798           break;
    799         LocMapI.advanceTo(LII->start);
    800       } else {
    801         ++LocMapI;
    802         if (!LocMapI.valid())
    803           break;
    804         LII = LI->advanceTo(LII, LocMapI.start());
    805       }
    806     }
    807   }
    808 
    809   // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
    810   locations.erase(locations.begin() + OldLocNo);
    811   LocMapI.goToBegin();
    812   while (LocMapI.valid()) {
    813     unsigned v = LocMapI.value();
    814     if (v == OldLocNo) {
    815       DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
    816                    << LocMapI.stop() << ")\n");
    817       LocMapI.erase();
    818     } else {
    819       if (v > OldLocNo)
    820         LocMapI.setValueUnchecked(v-1);
    821       ++LocMapI;
    822     }
    823   }
    824 
    825   DEBUG({dbgs() << "Split result: \t"; print(dbgs(), 0);});
    826   return DidChange;
    827 }
    828 
    829 bool
    830 UserValue::splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs) {
    831   bool DidChange = false;
    832   // Split locations referring to OldReg. Iterate backwards so splitLocation can
    833   // safely erase unused locations.
    834   for (unsigned i = locations.size(); i ; --i) {
    835     unsigned LocNo = i-1;
    836     const MachineOperand *Loc = &locations[LocNo];
    837     if (!Loc->isReg() || Loc->getReg() != OldReg)
    838       continue;
    839     DidChange |= splitLocation(LocNo, NewRegs);
    840   }
    841   return DidChange;
    842 }
    843 
    844 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs) {
    845   bool DidChange = false;
    846   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
    847     DidChange |= UV->splitRegister(OldReg, NewRegs);
    848 
    849   if (!DidChange)
    850     return;
    851 
    852   // Map all of the new virtual registers.
    853   UserValue *UV = lookupVirtReg(OldReg);
    854   for (unsigned i = 0; i != NewRegs.size(); ++i)
    855     mapVirtReg(NewRegs[i]->reg, UV);
    856 }
    857 
    858 void LiveDebugVariables::
    859 splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs) {
    860   if (pImpl)
    861     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
    862 }
    863 
    864 void
    865 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
    866   // Iterate over locations in reverse makes it easier to handle coalescing.
    867   for (unsigned i = locations.size(); i ; --i) {
    868     unsigned LocNo = i-1;
    869     MachineOperand &Loc = locations[LocNo];
    870     // Only virtual registers are rewritten.
    871     if (!Loc.isReg() || !Loc.getReg() ||
    872         !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
    873       continue;
    874     unsigned VirtReg = Loc.getReg();
    875     if (VRM.isAssignedReg(VirtReg) &&
    876         TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
    877       // This can create a %noreg operand in rare cases when the sub-register
    878       // index is no longer available. That means the user value is in a
    879       // non-existent sub-register, and %noreg is exactly what we want.
    880       Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
    881     } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
    882       // FIXME: Translate SubIdx to a stackslot offset.
    883       Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
    884     } else {
    885       Loc.setReg(0);
    886       Loc.setSubReg(0);
    887     }
    888     coalesceLocation(LocNo);
    889   }
    890 }
    891 
    892 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
    893 /// instruction.
    894 static MachineBasicBlock::iterator
    895 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
    896                    LiveIntervals &LIS) {
    897   SlotIndex Start = LIS.getMBBStartIdx(MBB);
    898   Idx = Idx.getBaseIndex();
    899 
    900   // Try to find an insert location by going backwards from Idx.
    901   MachineInstr *MI;
    902   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
    903     // We've reached the beginning of MBB.
    904     if (Idx == Start) {
    905       MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
    906       return I;
    907     }
    908     Idx = Idx.getPrevIndex();
    909   }
    910 
    911   // Don't insert anything after the first terminator, though.
    912   return MI->isTerminator() ? MBB->getFirstTerminator() :
    913                               llvm::next(MachineBasicBlock::iterator(MI));
    914 }
    915 
    916 DebugLoc UserValue::findDebugLoc() {
    917   DebugLoc D = dl;
    918   dl = DebugLoc();
    919   return D;
    920 }
    921 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
    922                                  unsigned LocNo,
    923                                  LiveIntervals &LIS,
    924                                  const TargetInstrInfo &TII) {
    925   MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
    926   MachineOperand &Loc = locations[LocNo];
    927   ++NumInsertedDebugValues;
    928 
    929   if (Loc.isReg())
    930     BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
    931             IsIndirect, Loc.getReg(), offset, variable);
    932   else
    933     BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
    934       .addOperand(Loc).addImm(offset).addMetadata(variable);
    935 }
    936 
    937 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
    938                                 const TargetInstrInfo &TII) {
    939   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
    940 
    941   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
    942     SlotIndex Start = I.start();
    943     SlotIndex Stop = I.stop();
    944     unsigned LocNo = I.value();
    945     DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
    946     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
    947     SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
    948 
    949     DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
    950     insertDebugValue(MBB, Start, LocNo, LIS, TII);
    951     // This interval may span multiple basic blocks.
    952     // Insert a DBG_VALUE into each one.
    953     while(Stop > MBBEnd) {
    954       // Move to the next block.
    955       Start = MBBEnd;
    956       if (++MBB == MFEnd)
    957         break;
    958       MBBEnd = LIS.getMBBEndIdx(MBB);
    959       DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
    960       insertDebugValue(MBB, Start, LocNo, LIS, TII);
    961     }
    962     DEBUG(dbgs() << '\n');
    963     if (MBB == MFEnd)
    964       break;
    965 
    966     ++I;
    967   }
    968 }
    969 
    970 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
    971   DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
    972   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
    973   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
    974     DEBUG(userValues[i]->print(dbgs(), &MF->getTarget()));
    975     userValues[i]->rewriteLocations(*VRM, *TRI);
    976     userValues[i]->emitDebugValues(VRM, *LIS, *TII);
    977   }
    978   EmitDone = true;
    979 }
    980 
    981 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
    982   if (pImpl)
    983     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
    984 }
    985 
    986 
    987 #ifndef NDEBUG
    988 void LiveDebugVariables::dump() {
    989   if (pImpl)
    990     static_cast<LDVImpl*>(pImpl)->print(dbgs());
    991 }
    992 #endif
    993