LLVM API Documentation
00001 //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the LiveDebugVariables analysis. 00011 // 00012 // Remove all DBG_VALUE instructions referencing virtual registers and replace 00013 // them with a data structure tracking where live user variables are kept - in a 00014 // virtual register or in a stack slot. 00015 // 00016 // Allow the data structure to be updated during register allocation when values 00017 // are moved between registers and stack slots. Finally emit new DBG_VALUE 00018 // instructions after register allocation is complete. 00019 // 00020 //===----------------------------------------------------------------------===// 00021 00022 #include "LiveDebugVariables.h" 00023 #include "llvm/ADT/IntervalMap.h" 00024 #include "llvm/ADT/Statistic.h" 00025 #include "llvm/CodeGen/LexicalScopes.h" 00026 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 00027 #include "llvm/CodeGen/MachineDominators.h" 00028 #include "llvm/CodeGen/MachineFunction.h" 00029 #include "llvm/CodeGen/MachineInstrBuilder.h" 00030 #include "llvm/CodeGen/MachineRegisterInfo.h" 00031 #include "llvm/CodeGen/Passes.h" 00032 #include "llvm/CodeGen/VirtRegMap.h" 00033 #include "llvm/IR/Constants.h" 00034 #include "llvm/IR/DebugInfo.h" 00035 #include "llvm/IR/Metadata.h" 00036 #include "llvm/IR/Value.h" 00037 #include "llvm/Support/CommandLine.h" 00038 #include "llvm/Support/Debug.h" 00039 #include "llvm/Target/TargetInstrInfo.h" 00040 #include "llvm/Target/TargetMachine.h" 00041 #include "llvm/Target/TargetRegisterInfo.h" 00042 #include "llvm/Target/TargetSubtargetInfo.h" 00043 00044 #include <memory> 00045 00046 using namespace llvm; 00047 00048 #define DEBUG_TYPE "livedebug" 00049 00050 static cl::opt<bool> 00051 EnableLDV("live-debug-variables", cl::init(true), 00052 cl::desc("Enable the live debug variables pass"), cl::Hidden); 00053 00054 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted"); 00055 char LiveDebugVariables::ID = 0; 00056 00057 INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars", 00058 "Debug Variable Analysis", false, false) 00059 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 00060 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 00061 INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars", 00062 "Debug Variable Analysis", false, false) 00063 00064 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const { 00065 AU.addRequired<MachineDominatorTree>(); 00066 AU.addRequiredTransitive<LiveIntervals>(); 00067 AU.setPreservesAll(); 00068 MachineFunctionPass::getAnalysisUsage(AU); 00069 } 00070 00071 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(nullptr) { 00072 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry()); 00073 } 00074 00075 /// LocMap - Map of where a user value is live, and its location. 00076 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap; 00077 00078 namespace { 00079 /// UserValueScopes - Keeps track of lexical scopes associated with a 00080 /// user value's source location. 00081 class UserValueScopes { 00082 DebugLoc DL; 00083 LexicalScopes &LS; 00084 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks; 00085 00086 public: 00087 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(D), LS(L) {} 00088 00089 /// dominates - Return true if current scope dominates at least one machine 00090 /// instruction in a given machine basic block. 00091 bool dominates(MachineBasicBlock *MBB) { 00092 if (LBlocks.empty()) 00093 LS.getMachineBasicBlocks(DL, LBlocks); 00094 if (LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB)) 00095 return true; 00096 return false; 00097 } 00098 }; 00099 } // end anonymous namespace 00100 00101 /// UserValue - A user value is a part of a debug info user variable. 00102 /// 00103 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register 00104 /// holds part of a user variable. The part is identified by a byte offset. 00105 /// 00106 /// UserValues are grouped into equivalence classes for easier searching. Two 00107 /// user values are related if they refer to the same variable, or if they are 00108 /// held by the same virtual register. The equivalence class is the transitive 00109 /// closure of that relation. 00110 namespace { 00111 class LDVImpl; 00112 class UserValue { 00113 const MDNode *variable; ///< The debug info variable we are part of. 00114 unsigned offset; ///< Byte offset into variable. 00115 bool IsIndirect; ///< true if this is a register-indirect+offset value. 00116 DebugLoc dl; ///< The debug location for the variable. This is 00117 ///< used by dwarf writer to find lexical scope. 00118 UserValue *leader; ///< Equivalence class leader. 00119 UserValue *next; ///< Next value in equivalence class, or null. 00120 00121 /// Numbered locations referenced by locmap. 00122 SmallVector<MachineOperand, 4> locations; 00123 00124 /// Map of slot indices where this value is live. 00125 LocMap locInts; 00126 00127 /// coalesceLocation - After LocNo was changed, check if it has become 00128 /// identical to another location, and coalesce them. This may cause LocNo or 00129 /// a later location to be erased, but no earlier location will be erased. 00130 void coalesceLocation(unsigned LocNo); 00131 00132 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo. 00133 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo, 00134 LiveIntervals &LIS, const TargetInstrInfo &TII); 00135 00136 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs 00137 /// is live. Returns true if any changes were made. 00138 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 00139 LiveIntervals &LIS); 00140 00141 public: 00142 /// UserValue - Create a new UserValue. 00143 UserValue(const MDNode *var, unsigned o, bool i, DebugLoc L, 00144 LocMap::Allocator &alloc) 00145 : variable(var), offset(o), IsIndirect(i), dl(L), leader(this), 00146 next(nullptr), locInts(alloc) 00147 {} 00148 00149 /// getLeader - Get the leader of this value's equivalence class. 00150 UserValue *getLeader() { 00151 UserValue *l = leader; 00152 while (l != l->leader) 00153 l = l->leader; 00154 return leader = l; 00155 } 00156 00157 /// getNext - Return the next UserValue in the equivalence class. 00158 UserValue *getNext() const { return next; } 00159 00160 /// match - Does this UserValue match the parameters? 00161 bool match(const MDNode *Var, unsigned Offset, bool indirect) const { 00162 return Var == variable && Offset == offset && indirect == IsIndirect; 00163 } 00164 00165 /// merge - Merge equivalence classes. 00166 static UserValue *merge(UserValue *L1, UserValue *L2) { 00167 L2 = L2->getLeader(); 00168 if (!L1) 00169 return L2; 00170 L1 = L1->getLeader(); 00171 if (L1 == L2) 00172 return L1; 00173 // Splice L2 before L1's members. 00174 UserValue *End = L2; 00175 while (End->next) 00176 End->leader = L1, End = End->next; 00177 End->leader = L1; 00178 End->next = L1->next; 00179 L1->next = L2; 00180 return L1; 00181 } 00182 00183 /// getLocationNo - Return the location number that matches Loc. 00184 unsigned getLocationNo(const MachineOperand &LocMO) { 00185 if (LocMO.isReg()) { 00186 if (LocMO.getReg() == 0) 00187 return ~0u; 00188 // For register locations we dont care about use/def and other flags. 00189 for (unsigned i = 0, e = locations.size(); i != e; ++i) 00190 if (locations[i].isReg() && 00191 locations[i].getReg() == LocMO.getReg() && 00192 locations[i].getSubReg() == LocMO.getSubReg()) 00193 return i; 00194 } else 00195 for (unsigned i = 0, e = locations.size(); i != e; ++i) 00196 if (LocMO.isIdenticalTo(locations[i])) 00197 return i; 00198 locations.push_back(LocMO); 00199 // We are storing a MachineOperand outside a MachineInstr. 00200 locations.back().clearParent(); 00201 // Don't store def operands. 00202 if (locations.back().isReg()) 00203 locations.back().setIsUse(); 00204 return locations.size() - 1; 00205 } 00206 00207 /// mapVirtRegs - Ensure that all virtual register locations are mapped. 00208 void mapVirtRegs(LDVImpl *LDV); 00209 00210 /// addDef - Add a definition point to this value. 00211 void addDef(SlotIndex Idx, const MachineOperand &LocMO) { 00212 // Add a singular (Idx,Idx) -> Loc mapping. 00213 LocMap::iterator I = locInts.find(Idx); 00214 if (!I.valid() || I.start() != Idx) 00215 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO)); 00216 else 00217 // A later DBG_VALUE at the same SlotIndex overrides the old location. 00218 I.setValue(getLocationNo(LocMO)); 00219 } 00220 00221 /// extendDef - Extend the current definition as far as possible down the 00222 /// dominator tree. Stop when meeting an existing def or when leaving the live 00223 /// range of VNI. 00224 /// End points where VNI is no longer live are added to Kills. 00225 /// @param Idx Starting point for the definition. 00226 /// @param LocNo Location number to propagate. 00227 /// @param LR Restrict liveness to where LR has the value VNI. May be null. 00228 /// @param VNI When LR is not null, this is the value to restrict to. 00229 /// @param Kills Append end points of VNI's live range to Kills. 00230 /// @param LIS Live intervals analysis. 00231 /// @param MDT Dominator tree. 00232 void extendDef(SlotIndex Idx, unsigned LocNo, 00233 LiveRange *LR, const VNInfo *VNI, 00234 SmallVectorImpl<SlotIndex> *Kills, 00235 LiveIntervals &LIS, MachineDominatorTree &MDT, 00236 UserValueScopes &UVS); 00237 00238 /// addDefsFromCopies - The value in LI/LocNo may be copies to other 00239 /// registers. Determine if any of the copies are available at the kill 00240 /// points, and add defs if possible. 00241 /// @param LI Scan for copies of the value in LI->reg. 00242 /// @param LocNo Location number of LI->reg. 00243 /// @param Kills Points where the range of LocNo could be extended. 00244 /// @param NewDefs Append (Idx, LocNo) of inserted defs here. 00245 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo, 00246 const SmallVectorImpl<SlotIndex> &Kills, 00247 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs, 00248 MachineRegisterInfo &MRI, 00249 LiveIntervals &LIS); 00250 00251 /// computeIntervals - Compute the live intervals of all locations after 00252 /// collecting all their def points. 00253 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, 00254 LiveIntervals &LIS, MachineDominatorTree &MDT, 00255 UserValueScopes &UVS); 00256 00257 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is 00258 /// live. Returns true if any changes were made. 00259 bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 00260 LiveIntervals &LIS); 00261 00262 /// rewriteLocations - Rewrite virtual register locations according to the 00263 /// provided virtual register map. 00264 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI); 00265 00266 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures. 00267 void emitDebugValues(VirtRegMap *VRM, 00268 LiveIntervals &LIS, const TargetInstrInfo &TRI); 00269 00270 /// findDebugLoc - Return DebugLoc used for this DBG_VALUE instruction. A 00271 /// variable may have more than one corresponding DBG_VALUE instructions. 00272 /// Only first one needs DebugLoc to identify variable's lexical scope 00273 /// in source file. 00274 DebugLoc findDebugLoc(); 00275 00276 /// getDebugLoc - Return DebugLoc of this UserValue. 00277 DebugLoc getDebugLoc() { return dl;} 00278 void print(raw_ostream&, const TargetMachine*); 00279 }; 00280 } // namespace 00281 00282 /// LDVImpl - Implementation of the LiveDebugVariables pass. 00283 namespace { 00284 class LDVImpl { 00285 LiveDebugVariables &pass; 00286 LocMap::Allocator allocator; 00287 MachineFunction *MF; 00288 LiveIntervals *LIS; 00289 LexicalScopes LS; 00290 MachineDominatorTree *MDT; 00291 const TargetRegisterInfo *TRI; 00292 00293 /// Whether emitDebugValues is called. 00294 bool EmitDone; 00295 /// Whether the machine function is modified during the pass. 00296 bool ModifiedMF; 00297 00298 /// userValues - All allocated UserValue instances. 00299 SmallVector<std::unique_ptr<UserValue>, 8> userValues; 00300 00301 /// Map virtual register to eq class leader. 00302 typedef DenseMap<unsigned, UserValue*> VRMap; 00303 VRMap virtRegToEqClass; 00304 00305 /// Map user variable to eq class leader. 00306 typedef DenseMap<const MDNode *, UserValue*> UVMap; 00307 UVMap userVarMap; 00308 00309 /// getUserValue - Find or create a UserValue. 00310 UserValue *getUserValue(const MDNode *Var, unsigned Offset, 00311 bool IsIndirect, DebugLoc DL); 00312 00313 /// lookupVirtReg - Find the EC leader for VirtReg or null. 00314 UserValue *lookupVirtReg(unsigned VirtReg); 00315 00316 /// handleDebugValue - Add DBG_VALUE instruction to our maps. 00317 /// @param MI DBG_VALUE instruction 00318 /// @param Idx Last valid SLotIndex before instruction. 00319 /// @return True if the DBG_VALUE instruction should be deleted. 00320 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx); 00321 00322 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding 00323 /// a UserValue def for each instruction. 00324 /// @param mf MachineFunction to be scanned. 00325 /// @return True if any debug values were found. 00326 bool collectDebugValues(MachineFunction &mf); 00327 00328 /// computeIntervals - Compute the live intervals of all user values after 00329 /// collecting all their def points. 00330 void computeIntervals(); 00331 00332 public: 00333 LDVImpl(LiveDebugVariables *ps) 00334 : pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {} 00335 bool runOnMachineFunction(MachineFunction &mf); 00336 00337 /// clear - Release all memory. 00338 void clear() { 00339 MF = nullptr; 00340 userValues.clear(); 00341 virtRegToEqClass.clear(); 00342 userVarMap.clear(); 00343 // Make sure we call emitDebugValues if the machine function was modified. 00344 assert((!ModifiedMF || EmitDone) && 00345 "Dbg values are not emitted in LDV"); 00346 EmitDone = false; 00347 ModifiedMF = false; 00348 } 00349 00350 /// mapVirtReg - Map virtual register to an equivalence class. 00351 void mapVirtReg(unsigned VirtReg, UserValue *EC); 00352 00353 /// splitRegister - Replace all references to OldReg with NewRegs. 00354 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs); 00355 00356 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures. 00357 void emitDebugValues(VirtRegMap *VRM); 00358 00359 void print(raw_ostream&); 00360 }; 00361 } // namespace 00362 00363 void UserValue::print(raw_ostream &OS, const TargetMachine *TM) { 00364 DIVariable DV(variable); 00365 OS << "!\""; 00366 DV.printExtendedName(OS); 00367 OS << "\"\t"; 00368 if (offset) 00369 OS << '+' << offset; 00370 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) { 00371 OS << " [" << I.start() << ';' << I.stop() << "):"; 00372 if (I.value() == ~0u) 00373 OS << "undef"; 00374 else 00375 OS << I.value(); 00376 } 00377 for (unsigned i = 0, e = locations.size(); i != e; ++i) { 00378 OS << " Loc" << i << '='; 00379 locations[i].print(OS, TM); 00380 } 00381 OS << '\n'; 00382 } 00383 00384 void LDVImpl::print(raw_ostream &OS) { 00385 OS << "********** DEBUG VARIABLES **********\n"; 00386 for (unsigned i = 0, e = userValues.size(); i != e; ++i) 00387 userValues[i]->print(OS, &MF->getTarget()); 00388 } 00389 00390 void UserValue::coalesceLocation(unsigned LocNo) { 00391 unsigned KeepLoc = 0; 00392 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) { 00393 if (KeepLoc == LocNo) 00394 continue; 00395 if (locations[KeepLoc].isIdenticalTo(locations[LocNo])) 00396 break; 00397 } 00398 // No matches. 00399 if (KeepLoc == locations.size()) 00400 return; 00401 00402 // Keep the smaller location, erase the larger one. 00403 unsigned EraseLoc = LocNo; 00404 if (KeepLoc > EraseLoc) 00405 std::swap(KeepLoc, EraseLoc); 00406 locations.erase(locations.begin() + EraseLoc); 00407 00408 // Rewrite values. 00409 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) { 00410 unsigned v = I.value(); 00411 if (v == EraseLoc) 00412 I.setValue(KeepLoc); // Coalesce when possible. 00413 else if (v > EraseLoc) 00414 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values. 00415 } 00416 } 00417 00418 void UserValue::mapVirtRegs(LDVImpl *LDV) { 00419 for (unsigned i = 0, e = locations.size(); i != e; ++i) 00420 if (locations[i].isReg() && 00421 TargetRegisterInfo::isVirtualRegister(locations[i].getReg())) 00422 LDV->mapVirtReg(locations[i].getReg(), this); 00423 } 00424 00425 UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset, 00426 bool IsIndirect, DebugLoc DL) { 00427 UserValue *&Leader = userVarMap[Var]; 00428 if (Leader) { 00429 UserValue *UV = Leader->getLeader(); 00430 Leader = UV; 00431 for (; UV; UV = UV->getNext()) 00432 if (UV->match(Var, Offset, IsIndirect)) 00433 return UV; 00434 } 00435 00436 userValues.push_back( 00437 make_unique<UserValue>(Var, Offset, IsIndirect, DL, allocator)); 00438 UserValue *UV = userValues.back().get(); 00439 Leader = UserValue::merge(Leader, UV); 00440 return UV; 00441 } 00442 00443 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) { 00444 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs"); 00445 UserValue *&Leader = virtRegToEqClass[VirtReg]; 00446 Leader = UserValue::merge(Leader, EC); 00447 } 00448 00449 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) { 00450 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg)) 00451 return UV->getLeader(); 00452 return nullptr; 00453 } 00454 00455 bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) { 00456 // DBG_VALUE loc, offset, variable 00457 if (MI->getNumOperands() != 3 || 00458 !(MI->getOperand(1).isReg() || MI->getOperand(1).isImm()) || 00459 !MI->getOperand(2).isMetadata()) { 00460 DEBUG(dbgs() << "Can't handle " << *MI); 00461 return false; 00462 } 00463 00464 // Get or create the UserValue for (variable,offset). 00465 bool IsIndirect = MI->isIndirectDebugValue(); 00466 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0; 00467 const MDNode *Var = MI->getOperand(2).getMetadata(); 00468 //here. 00469 UserValue *UV = getUserValue(Var, Offset, IsIndirect, MI->getDebugLoc()); 00470 UV->addDef(Idx, MI->getOperand(0)); 00471 return true; 00472 } 00473 00474 bool LDVImpl::collectDebugValues(MachineFunction &mf) { 00475 bool Changed = false; 00476 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE; 00477 ++MFI) { 00478 MachineBasicBlock *MBB = MFI; 00479 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end(); 00480 MBBI != MBBE;) { 00481 if (!MBBI->isDebugValue()) { 00482 ++MBBI; 00483 continue; 00484 } 00485 // DBG_VALUE has no slot index, use the previous instruction instead. 00486 SlotIndex Idx = MBBI == MBB->begin() ? 00487 LIS->getMBBStartIdx(MBB) : 00488 LIS->getInstructionIndex(std::prev(MBBI)).getRegSlot(); 00489 // Handle consecutive DBG_VALUE instructions with the same slot index. 00490 do { 00491 if (handleDebugValue(MBBI, Idx)) { 00492 MBBI = MBB->erase(MBBI); 00493 Changed = true; 00494 } else 00495 ++MBBI; 00496 } while (MBBI != MBBE && MBBI->isDebugValue()); 00497 } 00498 } 00499 return Changed; 00500 } 00501 00502 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo, 00503 LiveRange *LR, const VNInfo *VNI, 00504 SmallVectorImpl<SlotIndex> *Kills, 00505 LiveIntervals &LIS, MachineDominatorTree &MDT, 00506 UserValueScopes &UVS) { 00507 SmallVector<SlotIndex, 16> Todo; 00508 Todo.push_back(Idx); 00509 do { 00510 SlotIndex Start = Todo.pop_back_val(); 00511 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start); 00512 SlotIndex Stop = LIS.getMBBEndIdx(MBB); 00513 LocMap::iterator I = locInts.find(Start); 00514 00515 // Limit to VNI's live range. 00516 bool ToEnd = true; 00517 if (LR && VNI) { 00518 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start); 00519 if (!Segment || Segment->valno != VNI) { 00520 if (Kills) 00521 Kills->push_back(Start); 00522 continue; 00523 } 00524 if (Segment->end < Stop) 00525 Stop = Segment->end, ToEnd = false; 00526 } 00527 00528 // There could already be a short def at Start. 00529 if (I.valid() && I.start() <= Start) { 00530 // Stop when meeting a different location or an already extended interval. 00531 Start = Start.getNextSlot(); 00532 if (I.value() != LocNo || I.stop() != Start) 00533 continue; 00534 // This is a one-slot placeholder. Just skip it. 00535 ++I; 00536 } 00537 00538 // Limited by the next def. 00539 if (I.valid() && I.start() < Stop) 00540 Stop = I.start(), ToEnd = false; 00541 // Limited by VNI's live range. 00542 else if (!ToEnd && Kills) 00543 Kills->push_back(Stop); 00544 00545 if (Start >= Stop) 00546 continue; 00547 00548 I.insert(Start, Stop, LocNo); 00549 00550 // If we extended to the MBB end, propagate down the dominator tree. 00551 if (!ToEnd) 00552 continue; 00553 const std::vector<MachineDomTreeNode*> &Children = 00554 MDT.getNode(MBB)->getChildren(); 00555 for (unsigned i = 0, e = Children.size(); i != e; ++i) { 00556 MachineBasicBlock *MBB = Children[i]->getBlock(); 00557 if (UVS.dominates(MBB)) 00558 Todo.push_back(LIS.getMBBStartIdx(MBB)); 00559 } 00560 } while (!Todo.empty()); 00561 } 00562 00563 void 00564 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo, 00565 const SmallVectorImpl<SlotIndex> &Kills, 00566 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs, 00567 MachineRegisterInfo &MRI, LiveIntervals &LIS) { 00568 if (Kills.empty()) 00569 return; 00570 // Don't track copies from physregs, there are too many uses. 00571 if (!TargetRegisterInfo::isVirtualRegister(LI->reg)) 00572 return; 00573 00574 // Collect all the (vreg, valno) pairs that are copies of LI. 00575 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues; 00576 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) { 00577 MachineInstr *MI = MO.getParent(); 00578 // Copies of the full value. 00579 if (MO.getSubReg() || !MI->isCopy()) 00580 continue; 00581 unsigned DstReg = MI->getOperand(0).getReg(); 00582 00583 // Don't follow copies to physregs. These are usually setting up call 00584 // arguments, and the argument registers are always call clobbered. We are 00585 // better off in the source register which could be a callee-saved register, 00586 // or it could be spilled. 00587 if (!TargetRegisterInfo::isVirtualRegister(DstReg)) 00588 continue; 00589 00590 // Is LocNo extended to reach this copy? If not, another def may be blocking 00591 // it, or we are looking at a wrong value of LI. 00592 SlotIndex Idx = LIS.getInstructionIndex(MI); 00593 LocMap::iterator I = locInts.find(Idx.getRegSlot(true)); 00594 if (!I.valid() || I.value() != LocNo) 00595 continue; 00596 00597 if (!LIS.hasInterval(DstReg)) 00598 continue; 00599 LiveInterval *DstLI = &LIS.getInterval(DstReg); 00600 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot()); 00601 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value"); 00602 CopyValues.push_back(std::make_pair(DstLI, DstVNI)); 00603 } 00604 00605 if (CopyValues.empty()) 00606 return; 00607 00608 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n'); 00609 00610 // Try to add defs of the copied values for each kill point. 00611 for (unsigned i = 0, e = Kills.size(); i != e; ++i) { 00612 SlotIndex Idx = Kills[i]; 00613 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) { 00614 LiveInterval *DstLI = CopyValues[j].first; 00615 const VNInfo *DstVNI = CopyValues[j].second; 00616 if (DstLI->getVNInfoAt(Idx) != DstVNI) 00617 continue; 00618 // Check that there isn't already a def at Idx 00619 LocMap::iterator I = locInts.find(Idx); 00620 if (I.valid() && I.start() <= Idx) 00621 continue; 00622 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #" 00623 << DstVNI->id << " in " << *DstLI << '\n'); 00624 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def); 00625 assert(CopyMI && CopyMI->isCopy() && "Bad copy value"); 00626 unsigned LocNo = getLocationNo(CopyMI->getOperand(0)); 00627 I.insert(Idx, Idx.getNextSlot(), LocNo); 00628 NewDefs.push_back(std::make_pair(Idx, LocNo)); 00629 break; 00630 } 00631 } 00632 } 00633 00634 void 00635 UserValue::computeIntervals(MachineRegisterInfo &MRI, 00636 const TargetRegisterInfo &TRI, 00637 LiveIntervals &LIS, 00638 MachineDominatorTree &MDT, 00639 UserValueScopes &UVS) { 00640 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs; 00641 00642 // Collect all defs to be extended (Skipping undefs). 00643 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) 00644 if (I.value() != ~0u) 00645 Defs.push_back(std::make_pair(I.start(), I.value())); 00646 00647 // Extend all defs, and possibly add new ones along the way. 00648 for (unsigned i = 0; i != Defs.size(); ++i) { 00649 SlotIndex Idx = Defs[i].first; 00650 unsigned LocNo = Defs[i].second; 00651 const MachineOperand &Loc = locations[LocNo]; 00652 00653 if (!Loc.isReg()) { 00654 extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS, MDT, UVS); 00655 continue; 00656 } 00657 00658 // Register locations are constrained to where the register value is live. 00659 if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) { 00660 LiveInterval *LI = nullptr; 00661 const VNInfo *VNI = nullptr; 00662 if (LIS.hasInterval(Loc.getReg())) { 00663 LI = &LIS.getInterval(Loc.getReg()); 00664 VNI = LI->getVNInfoAt(Idx); 00665 } 00666 SmallVector<SlotIndex, 16> Kills; 00667 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, UVS); 00668 if (LI) 00669 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS); 00670 continue; 00671 } 00672 00673 // For physregs, use the live range of the first regunit as a guide. 00674 unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI); 00675 LiveRange *LR = &LIS.getRegUnit(Unit); 00676 const VNInfo *VNI = LR->getVNInfoAt(Idx); 00677 // Don't track copies from physregs, it is too expensive. 00678 extendDef(Idx, LocNo, LR, VNI, nullptr, LIS, MDT, UVS); 00679 } 00680 00681 // Finally, erase all the undefs. 00682 for (LocMap::iterator I = locInts.begin(); I.valid();) 00683 if (I.value() == ~0u) 00684 I.erase(); 00685 else 00686 ++I; 00687 } 00688 00689 void LDVImpl::computeIntervals() { 00690 for (unsigned i = 0, e = userValues.size(); i != e; ++i) { 00691 UserValueScopes UVS(userValues[i]->getDebugLoc(), LS); 00692 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, *MDT, UVS); 00693 userValues[i]->mapVirtRegs(this); 00694 } 00695 } 00696 00697 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) { 00698 clear(); 00699 MF = &mf; 00700 LIS = &pass.getAnalysis<LiveIntervals>(); 00701 MDT = &pass.getAnalysis<MachineDominatorTree>(); 00702 TRI = mf.getSubtarget().getRegisterInfo(); 00703 LS.initialize(mf); 00704 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: " 00705 << mf.getName() << " **********\n"); 00706 00707 bool Changed = collectDebugValues(mf); 00708 computeIntervals(); 00709 DEBUG(print(dbgs())); 00710 ModifiedMF = Changed; 00711 return Changed; 00712 } 00713 00714 static void removeDebugValues(MachineFunction &mf) { 00715 for (MachineBasicBlock &MBB : mf) { 00716 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) { 00717 if (!MBBI->isDebugValue()) { 00718 ++MBBI; 00719 continue; 00720 } 00721 MBBI = MBB.erase(MBBI); 00722 } 00723 } 00724 } 00725 00726 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) { 00727 if (!EnableLDV) 00728 return false; 00729 if (!FunctionDIs.count(mf.getFunction())) { 00730 removeDebugValues(mf); 00731 return false; 00732 } 00733 if (!pImpl) 00734 pImpl = new LDVImpl(this); 00735 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf); 00736 } 00737 00738 void LiveDebugVariables::releaseMemory() { 00739 if (pImpl) 00740 static_cast<LDVImpl*>(pImpl)->clear(); 00741 } 00742 00743 LiveDebugVariables::~LiveDebugVariables() { 00744 if (pImpl) 00745 delete static_cast<LDVImpl*>(pImpl); 00746 } 00747 00748 //===----------------------------------------------------------------------===// 00749 // Live Range Splitting 00750 //===----------------------------------------------------------------------===// 00751 00752 bool 00753 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 00754 LiveIntervals& LIS) { 00755 DEBUG({ 00756 dbgs() << "Splitting Loc" << OldLocNo << '\t'; 00757 print(dbgs(), nullptr); 00758 }); 00759 bool DidChange = false; 00760 LocMap::iterator LocMapI; 00761 LocMapI.setMap(locInts); 00762 for (unsigned i = 0; i != NewRegs.size(); ++i) { 00763 LiveInterval *LI = &LIS.getInterval(NewRegs[i]); 00764 if (LI->empty()) 00765 continue; 00766 00767 // Don't allocate the new LocNo until it is needed. 00768 unsigned NewLocNo = ~0u; 00769 00770 // Iterate over the overlaps between locInts and LI. 00771 LocMapI.find(LI->beginIndex()); 00772 if (!LocMapI.valid()) 00773 continue; 00774 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start()); 00775 LiveInterval::iterator LIE = LI->end(); 00776 while (LocMapI.valid() && LII != LIE) { 00777 // At this point, we know that LocMapI.stop() > LII->start. 00778 LII = LI->advanceTo(LII, LocMapI.start()); 00779 if (LII == LIE) 00780 break; 00781 00782 // Now LII->end > LocMapI.start(). Do we have an overlap? 00783 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) { 00784 // Overlapping correct location. Allocate NewLocNo now. 00785 if (NewLocNo == ~0u) { 00786 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false); 00787 MO.setSubReg(locations[OldLocNo].getSubReg()); 00788 NewLocNo = getLocationNo(MO); 00789 DidChange = true; 00790 } 00791 00792 SlotIndex LStart = LocMapI.start(); 00793 SlotIndex LStop = LocMapI.stop(); 00794 00795 // Trim LocMapI down to the LII overlap. 00796 if (LStart < LII->start) 00797 LocMapI.setStartUnchecked(LII->start); 00798 if (LStop > LII->end) 00799 LocMapI.setStopUnchecked(LII->end); 00800 00801 // Change the value in the overlap. This may trigger coalescing. 00802 LocMapI.setValue(NewLocNo); 00803 00804 // Re-insert any removed OldLocNo ranges. 00805 if (LStart < LocMapI.start()) { 00806 LocMapI.insert(LStart, LocMapI.start(), OldLocNo); 00807 ++LocMapI; 00808 assert(LocMapI.valid() && "Unexpected coalescing"); 00809 } 00810 if (LStop > LocMapI.stop()) { 00811 ++LocMapI; 00812 LocMapI.insert(LII->end, LStop, OldLocNo); 00813 --LocMapI; 00814 } 00815 } 00816 00817 // Advance to the next overlap. 00818 if (LII->end < LocMapI.stop()) { 00819 if (++LII == LIE) 00820 break; 00821 LocMapI.advanceTo(LII->start); 00822 } else { 00823 ++LocMapI; 00824 if (!LocMapI.valid()) 00825 break; 00826 LII = LI->advanceTo(LII, LocMapI.start()); 00827 } 00828 } 00829 } 00830 00831 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself. 00832 locations.erase(locations.begin() + OldLocNo); 00833 LocMapI.goToBegin(); 00834 while (LocMapI.valid()) { 00835 unsigned v = LocMapI.value(); 00836 if (v == OldLocNo) { 00837 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';' 00838 << LocMapI.stop() << ")\n"); 00839 LocMapI.erase(); 00840 } else { 00841 if (v > OldLocNo) 00842 LocMapI.setValueUnchecked(v-1); 00843 ++LocMapI; 00844 } 00845 } 00846 00847 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);}); 00848 return DidChange; 00849 } 00850 00851 bool 00852 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, 00853 LiveIntervals &LIS) { 00854 bool DidChange = false; 00855 // Split locations referring to OldReg. Iterate backwards so splitLocation can 00856 // safely erase unused locations. 00857 for (unsigned i = locations.size(); i ; --i) { 00858 unsigned LocNo = i-1; 00859 const MachineOperand *Loc = &locations[LocNo]; 00860 if (!Loc->isReg() || Loc->getReg() != OldReg) 00861 continue; 00862 DidChange |= splitLocation(LocNo, NewRegs, LIS); 00863 } 00864 return DidChange; 00865 } 00866 00867 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) { 00868 bool DidChange = false; 00869 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext()) 00870 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS); 00871 00872 if (!DidChange) 00873 return; 00874 00875 // Map all of the new virtual registers. 00876 UserValue *UV = lookupVirtReg(OldReg); 00877 for (unsigned i = 0; i != NewRegs.size(); ++i) 00878 mapVirtReg(NewRegs[i], UV); 00879 } 00880 00881 void LiveDebugVariables:: 00882 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) { 00883 if (pImpl) 00884 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs); 00885 } 00886 00887 void 00888 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) { 00889 // Iterate over locations in reverse makes it easier to handle coalescing. 00890 for (unsigned i = locations.size(); i ; --i) { 00891 unsigned LocNo = i-1; 00892 MachineOperand &Loc = locations[LocNo]; 00893 // Only virtual registers are rewritten. 00894 if (!Loc.isReg() || !Loc.getReg() || 00895 !TargetRegisterInfo::isVirtualRegister(Loc.getReg())) 00896 continue; 00897 unsigned VirtReg = Loc.getReg(); 00898 if (VRM.isAssignedReg(VirtReg) && 00899 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) { 00900 // This can create a %noreg operand in rare cases when the sub-register 00901 // index is no longer available. That means the user value is in a 00902 // non-existent sub-register, and %noreg is exactly what we want. 00903 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI); 00904 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) { 00905 // FIXME: Translate SubIdx to a stackslot offset. 00906 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg)); 00907 } else { 00908 Loc.setReg(0); 00909 Loc.setSubReg(0); 00910 } 00911 coalesceLocation(LocNo); 00912 } 00913 } 00914 00915 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE 00916 /// instruction. 00917 static MachineBasicBlock::iterator 00918 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, 00919 LiveIntervals &LIS) { 00920 SlotIndex Start = LIS.getMBBStartIdx(MBB); 00921 Idx = Idx.getBaseIndex(); 00922 00923 // Try to find an insert location by going backwards from Idx. 00924 MachineInstr *MI; 00925 while (!(MI = LIS.getInstructionFromIndex(Idx))) { 00926 // We've reached the beginning of MBB. 00927 if (Idx == Start) { 00928 MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin()); 00929 return I; 00930 } 00931 Idx = Idx.getPrevIndex(); 00932 } 00933 00934 // Don't insert anything after the first terminator, though. 00935 return MI->isTerminator() ? MBB->getFirstTerminator() : 00936 std::next(MachineBasicBlock::iterator(MI)); 00937 } 00938 00939 DebugLoc UserValue::findDebugLoc() { 00940 DebugLoc D = dl; 00941 dl = DebugLoc(); 00942 return D; 00943 } 00944 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, 00945 unsigned LocNo, 00946 LiveIntervals &LIS, 00947 const TargetInstrInfo &TII) { 00948 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS); 00949 MachineOperand &Loc = locations[LocNo]; 00950 ++NumInsertedDebugValues; 00951 00952 if (Loc.isReg()) 00953 BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE), 00954 IsIndirect, Loc.getReg(), offset, variable); 00955 else 00956 BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE)) 00957 .addOperand(Loc).addImm(offset).addMetadata(variable); 00958 } 00959 00960 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 00961 const TargetInstrInfo &TII) { 00962 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end(); 00963 00964 for (LocMap::const_iterator I = locInts.begin(); I.valid();) { 00965 SlotIndex Start = I.start(); 00966 SlotIndex Stop = I.stop(); 00967 unsigned LocNo = I.value(); 00968 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo); 00969 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start); 00970 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB); 00971 00972 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd); 00973 insertDebugValue(MBB, Start, LocNo, LIS, TII); 00974 // This interval may span multiple basic blocks. 00975 // Insert a DBG_VALUE into each one. 00976 while(Stop > MBBEnd) { 00977 // Move to the next block. 00978 Start = MBBEnd; 00979 if (++MBB == MFEnd) 00980 break; 00981 MBBEnd = LIS.getMBBEndIdx(MBB); 00982 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd); 00983 insertDebugValue(MBB, Start, LocNo, LIS, TII); 00984 } 00985 DEBUG(dbgs() << '\n'); 00986 if (MBB == MFEnd) 00987 break; 00988 00989 ++I; 00990 } 00991 } 00992 00993 void LDVImpl::emitDebugValues(VirtRegMap *VRM) { 00994 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n"); 00995 if (!MF) 00996 return; 00997 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 00998 for (unsigned i = 0, e = userValues.size(); i != e; ++i) { 00999 DEBUG(userValues[i]->print(dbgs(), &MF->getTarget())); 01000 userValues[i]->rewriteLocations(*VRM, *TRI); 01001 userValues[i]->emitDebugValues(VRM, *LIS, *TII); 01002 } 01003 EmitDone = true; 01004 } 01005 01006 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) { 01007 if (pImpl) 01008 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM); 01009 } 01010 01011 bool LiveDebugVariables::doInitialization(Module &M) { 01012 FunctionDIs = makeSubprogramMap(M); 01013 return Pass::doInitialization(M); 01014 } 01015 01016 #ifndef NDEBUG 01017 void LiveDebugVariables::dump() { 01018 if (pImpl) 01019 static_cast<LDVImpl*>(pImpl)->print(dbgs()); 01020 } 01021 #endif