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 EnableLDV("live-debug-variables", cl::init(true), 70 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 INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE, 77 "Debug Variable Analysis", false, false) 78 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 79 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 80 INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE, 81 "Debug Variable Analysis", false, false) 82 83 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const { 84 AU.addRequired<MachineDominatorTree>(); 85 AU.addRequiredTransitive<LiveIntervals>(); 86 AU.setPreservesAll(); 87 MachineFunctionPass::getAnalysisUsage(AU); 88 } 89 90 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) { 91 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry()); 92 } 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 class UserValue { 111 const DILocalVariable *Variable; ///< The debug info variable we are part of. 112 const DIExpression *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 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo. 130 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, 131 unsigned LocNo, bool Spilled, LiveIntervals &LIS, 132 const TargetInstrInfo &TII); 133 134 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs 135 /// is live. Returns true if any changes were made. 136 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 137 LiveIntervals &LIS); 138 139 public: 140 /// UserValue - Create a new UserValue. 141 UserValue(const DILocalVariable *var, const DIExpression *expr, bool i, 142 DebugLoc L, LocMap::Allocator &alloc) 143 : Variable(var), Expression(expr), IsIndirect(i), dl(std::move(L)), 144 leader(this), locInts(alloc) {} 145 146 /// getLeader - Get the leader of this value's equivalence class. 147 UserValue *getLeader() { 148 UserValue *l = leader; 149 while (l != l->leader) 150 l = l->leader; 151 return leader = l; 152 } 153 154 /// getNext - Return the next UserValue in the equivalence class. 155 UserValue *getNext() const { return next; } 156 157 /// match - Does this UserValue match the parameters? 158 bool match(const DILocalVariable *Var, const DIExpression *Expr, 159 const DILocation *IA, bool indirect) const { 160 return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA && 161 indirect == IsIndirect; 162 } 163 164 enum : unsigned { UndefLocNo = ~0U }; 165 166 /// merge - Merge equivalence classes. 167 static UserValue *merge(UserValue *L1, UserValue *L2) { 168 L2 = L2->getLeader(); 169 if (!L1) 170 return L2; 171 L1 = L1->getLeader(); 172 if (L1 == L2) 173 return L1; 174 // Splice L2 before L1's members. 175 UserValue *End = L2; 176 while (End->next) { 177 End->leader = L1; 178 End = End->next; 179 } 180 End->leader = L1; 181 End->next = L1->next; 182 L1->next = L2; 183 return L1; 184 } 185 186 /// getLocationNo - Return the location number that matches Loc. 187 unsigned getLocationNo(const MachineOperand &LocMO) { 188 if (LocMO.isReg()) { 189 if (LocMO.getReg() == 0) 190 return UndefLocNo; 191 // For register locations we dont care about use/def and other flags. 192 for (unsigned i = 0, e = locations.size(); i != e; ++i) 193 if (locations[i].isReg() && 194 locations[i].getReg() == LocMO.getReg() && 195 locations[i].getSubReg() == LocMO.getSubReg()) 196 return i; 197 } else 198 for (unsigned i = 0, e = locations.size(); i != e; ++i) 199 if (LocMO.isIdenticalTo(locations[i])) 200 return i; 201 locations.push_back(LocMO); 202 // We are storing a MachineOperand outside a MachineInstr. 203 locations.back().clearParent(); 204 // Don't store def operands. 205 if (locations.back().isReg()) 206 locations.back().setIsUse(); 207 return locations.size() - 1; 208 } 209 210 /// mapVirtRegs - Ensure that all virtual register locations are mapped. 211 void mapVirtRegs(LDVImpl *LDV); 212 213 /// addDef - Add a definition point to this value. 214 void addDef(SlotIndex Idx, const MachineOperand &LocMO) { 215 // Add a singular (Idx,Idx) -> Loc mapping. 216 LocMap::iterator I = locInts.find(Idx); 217 if (!I.valid() || I.start() != Idx) 218 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO)); 219 else 220 // A later DBG_VALUE at the same SlotIndex overrides the old location. 221 I.setValue(getLocationNo(LocMO)); 222 } 223 224 /// extendDef - Extend the current definition as far as possible down. 225 /// Stop when meeting an existing def or when leaving the live 226 /// range of VNI. 227 /// End points where VNI is no longer live are added to Kills. 228 /// @param Idx Starting point for the definition. 229 /// @param LocNo Location number to propagate. 230 /// @param LR Restrict liveness to where LR has the value VNI. May be null. 231 /// @param VNI When LR is not null, this is the value to restrict to. 232 /// @param Kills Append end points of VNI's live range to Kills. 233 /// @param LIS Live intervals analysis. 234 void extendDef(SlotIndex Idx, unsigned LocNo, 235 LiveRange *LR, const VNInfo *VNI, 236 SmallVectorImpl<SlotIndex> *Kills, 237 LiveIntervals &LIS); 238 239 /// addDefsFromCopies - The value in LI/LocNo may be copies to other 240 /// registers. Determine if any of the copies are available at the kill 241 /// points, and add defs if possible. 242 /// @param LI Scan for copies of the value in LI->reg. 243 /// @param LocNo Location number of LI->reg. 244 /// @param Kills Points where the range of LocNo could be extended. 245 /// @param NewDefs Append (Idx, LocNo) of inserted defs here. 246 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo, 247 const SmallVectorImpl<SlotIndex> &Kills, 248 SmallVectorImpl<std::pair<SlotIndex, unsigned>> &NewDefs, 249 MachineRegisterInfo &MRI, 250 LiveIntervals &LIS); 251 252 /// computeIntervals - Compute the live intervals of all locations after 253 /// collecting all their def points. 254 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, 255 LiveIntervals &LIS, LexicalScopes &LS); 256 257 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is 258 /// live. Returns true if any changes were made. 259 bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 260 LiveIntervals &LIS); 261 262 /// rewriteLocations - Rewrite virtual register locations according to the 263 /// provided virtual register map. Record which locations were spilled. 264 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI, 265 BitVector &SpilledLocations); 266 267 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures. 268 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 269 const TargetInstrInfo &TRI, 270 const BitVector &SpilledLocations); 271 272 /// getDebugLoc - Return DebugLoc of this UserValue. 273 DebugLoc getDebugLoc() { return dl;} 274 275 void print(raw_ostream &, const TargetRegisterInfo *); 276 }; 277 278 /// LDVImpl - Implementation of the LiveDebugVariables pass. 279 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 DILocalVariable *, UserValue *>; 301 UVMap userVarMap; 302 303 /// getUserValue - Find or create a UserValue. 304 UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *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 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {} 328 329 bool runOnMachineFunction(MachineFunction &mf); 330 331 /// clear - Release all memory. 332 void clear() { 333 MF = nullptr; 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<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 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 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() == UndefLocNo) 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 void UserValue::mapVirtRegs(LDVImpl *LDV) { 423 for (unsigned i = 0, e = locations.size(); i != e; ++i) 424 if (locations[i].isReg() && 425 TargetRegisterInfo::isVirtualRegister(locations[i].getReg())) 426 LDV->mapVirtReg(locations[i].getReg(), this); 427 } 428 429 UserValue *LDVImpl::getUserValue(const DILocalVariable *Var, 430 const DIExpression *Expr, bool IsIndirect, 431 const DebugLoc &DL) { 432 UserValue *&Leader = userVarMap[Var]; 433 if (Leader) { 434 UserValue *UV = Leader->getLeader(); 435 Leader = UV; 436 for (; UV; UV = UV->getNext()) 437 if (UV->match(Var, Expr, DL->getInlinedAt(), IsIndirect)) 438 return UV; 439 } 440 441 userValues.push_back( 442 llvm::make_unique<UserValue>(Var, Expr, IsIndirect, DL, allocator)); 443 UserValue *UV = userValues.back().get(); 444 Leader = UserValue::merge(Leader, UV); 445 return UV; 446 } 447 448 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) { 449 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs"); 450 UserValue *&Leader = virtRegToEqClass[VirtReg]; 451 Leader = UserValue::merge(Leader, EC); 452 } 453 454 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) { 455 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg)) 456 return UV->getLeader(); 457 return nullptr; 458 } 459 460 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) { 461 // DBG_VALUE loc, offset, variable 462 if (MI.getNumOperands() != 4 || 463 !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) || 464 !MI.getOperand(2).isMetadata()) { 465 DEBUG(dbgs() << "Can't handle " << MI); 466 return false; 467 } 468 469 // Get or create the UserValue for (variable,offset). 470 bool IsIndirect = MI.getOperand(1).isImm(); 471 if (IsIndirect) 472 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset"); 473 const DILocalVariable *Var = MI.getDebugVariable(); 474 const DIExpression *Expr = MI.getDebugExpression(); 475 //here. 476 UserValue *UV = getUserValue(Var, Expr, IsIndirect, MI.getDebugLoc()); 477 UV->addDef(Idx, MI.getOperand(0)); 478 return true; 479 } 480 481 bool LDVImpl::collectDebugValues(MachineFunction &mf) { 482 bool Changed = false; 483 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE; 484 ++MFI) { 485 MachineBasicBlock *MBB = &*MFI; 486 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end(); 487 MBBI != MBBE;) { 488 if (!MBBI->isDebugValue()) { 489 ++MBBI; 490 continue; 491 } 492 // DBG_VALUE has no slot index, use the previous instruction instead. 493 SlotIndex Idx = 494 MBBI == MBB->begin() 495 ? LIS->getMBBStartIdx(MBB) 496 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot(); 497 // Handle consecutive DBG_VALUE instructions with the same slot index. 498 do { 499 if (handleDebugValue(*MBBI, Idx)) { 500 MBBI = MBB->erase(MBBI); 501 Changed = true; 502 } else 503 ++MBBI; 504 } while (MBBI != MBBE && MBBI->isDebugValue()); 505 } 506 } 507 return Changed; 508 } 509 510 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a 511 /// data-flow analysis to propagate them beyond basic block boundaries. 512 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo, LiveRange *LR, 513 const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills, 514 LiveIntervals &LIS) { 515 SlotIndex Start = Idx; 516 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start); 517 SlotIndex Stop = LIS.getMBBEndIdx(MBB); 518 LocMap::iterator I = locInts.find(Start); 519 520 // Limit to VNI's live range. 521 bool ToEnd = true; 522 if (LR && VNI) { 523 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start); 524 if (!Segment || Segment->valno != VNI) { 525 if (Kills) 526 Kills->push_back(Start); 527 return; 528 } 529 if (Segment->end < Stop) { 530 Stop = Segment->end; 531 ToEnd = false; 532 } 533 } 534 535 // There could already be a short def at Start. 536 if (I.valid() && I.start() <= Start) { 537 // Stop when meeting a different location or an already extended interval. 538 Start = Start.getNextSlot(); 539 if (I.value() != LocNo || I.stop() != Start) 540 return; 541 // This is a one-slot placeholder. Just skip it. 542 ++I; 543 } 544 545 // Limited by the next def. 546 if (I.valid() && I.start() < Stop) { 547 Stop = I.start(); 548 ToEnd = false; 549 } 550 // Limited by VNI's live range. 551 else if (!ToEnd && Kills) 552 Kills->push_back(Stop); 553 554 if (Start < Stop) 555 I.insert(Start, Stop, LocNo); 556 } 557 558 void 559 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo, 560 const SmallVectorImpl<SlotIndex> &Kills, 561 SmallVectorImpl<std::pair<SlotIndex, unsigned>> &NewDefs, 562 MachineRegisterInfo &MRI, LiveIntervals &LIS) { 563 if (Kills.empty()) 564 return; 565 // Don't track copies from physregs, there are too many uses. 566 if (!TargetRegisterInfo::isVirtualRegister(LI->reg)) 567 return; 568 569 // Collect all the (vreg, valno) pairs that are copies of LI. 570 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues; 571 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) { 572 MachineInstr *MI = MO.getParent(); 573 // Copies of the full value. 574 if (MO.getSubReg() || !MI->isCopy()) 575 continue; 576 unsigned DstReg = MI->getOperand(0).getReg(); 577 578 // Don't follow copies to physregs. These are usually setting up call 579 // arguments, and the argument registers are always call clobbered. We are 580 // better off in the source register which could be a callee-saved register, 581 // or it could be spilled. 582 if (!TargetRegisterInfo::isVirtualRegister(DstReg)) 583 continue; 584 585 // Is LocNo extended to reach this copy? If not, another def may be blocking 586 // it, or we are looking at a wrong value of LI. 587 SlotIndex Idx = LIS.getInstructionIndex(*MI); 588 LocMap::iterator I = locInts.find(Idx.getRegSlot(true)); 589 if (!I.valid() || I.value() != LocNo) 590 continue; 591 592 if (!LIS.hasInterval(DstReg)) 593 continue; 594 LiveInterval *DstLI = &LIS.getInterval(DstReg); 595 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot()); 596 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value"); 597 CopyValues.push_back(std::make_pair(DstLI, DstVNI)); 598 } 599 600 if (CopyValues.empty()) 601 return; 602 603 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n'); 604 605 // Try to add defs of the copied values for each kill point. 606 for (unsigned i = 0, e = Kills.size(); i != e; ++i) { 607 SlotIndex Idx = Kills[i]; 608 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) { 609 LiveInterval *DstLI = CopyValues[j].first; 610 const VNInfo *DstVNI = CopyValues[j].second; 611 if (DstLI->getVNInfoAt(Idx) != DstVNI) 612 continue; 613 // Check that there isn't already a def at Idx 614 LocMap::iterator I = locInts.find(Idx); 615 if (I.valid() && I.start() <= Idx) 616 continue; 617 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #" 618 << DstVNI->id << " in " << *DstLI << '\n'); 619 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def); 620 assert(CopyMI && CopyMI->isCopy() && "Bad copy value"); 621 unsigned LocNo = getLocationNo(CopyMI->getOperand(0)); 622 I.insert(Idx, Idx.getNextSlot(), LocNo); 623 NewDefs.push_back(std::make_pair(Idx, LocNo)); 624 break; 625 } 626 } 627 } 628 629 void UserValue::computeIntervals(MachineRegisterInfo &MRI, 630 const TargetRegisterInfo &TRI, 631 LiveIntervals &LIS, LexicalScopes &LS) { 632 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs; 633 634 // Collect all defs to be extended (Skipping undefs). 635 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) 636 if (I.value() != UndefLocNo) 637 Defs.push_back(std::make_pair(I.start(), I.value())); 638 639 // Extend all defs, and possibly add new ones along the way. 640 for (unsigned i = 0; i != Defs.size(); ++i) { 641 SlotIndex Idx = Defs[i].first; 642 unsigned LocNo = Defs[i].second; 643 const MachineOperand &Loc = locations[LocNo]; 644 645 if (!Loc.isReg()) { 646 extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS); 647 continue; 648 } 649 650 // Register locations are constrained to where the register value is live. 651 if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) { 652 LiveInterval *LI = nullptr; 653 const VNInfo *VNI = nullptr; 654 if (LIS.hasInterval(Loc.getReg())) { 655 LI = &LIS.getInterval(Loc.getReg()); 656 VNI = LI->getVNInfoAt(Idx); 657 } 658 SmallVector<SlotIndex, 16> Kills; 659 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS); 660 if (LI) 661 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS); 662 continue; 663 } 664 665 // For physregs, we only mark the start slot idx. DwarfDebug will see it 666 // as if the DBG_VALUE is valid up until the end of the basic block, or 667 // the next def of the physical register. So we do not need to extend the 668 // range. It might actually happen that the DBG_VALUE is the last use of 669 // the physical register (e.g. if this is an unused input argument to a 670 // function). 671 } 672 673 // Erase all the undefs. 674 for (LocMap::iterator I = locInts.begin(); I.valid();) 675 if (I.value() == UndefLocNo) 676 I.erase(); 677 else 678 ++I; 679 680 // The computed intervals may extend beyond the range of the debug 681 // location's lexical scope. In this case, splitting of an interval 682 // can result in an interval outside of the scope being created, 683 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent 684 // this, trim the intervals to the lexical scope. 685 686 LexicalScope *Scope = LS.findLexicalScope(dl); 687 if (!Scope) 688 return; 689 690 SlotIndex PrevEnd; 691 LocMap::iterator I = locInts.begin(); 692 693 // Iterate over the lexical scope ranges. Each time round the loop 694 // we check the intervals for overlap with the end of the previous 695 // range and the start of the next. The first range is handled as 696 // a special case where there is no PrevEnd. 697 for (const InsnRange &Range : Scope->getRanges()) { 698 SlotIndex RStart = LIS.getInstructionIndex(*Range.first); 699 SlotIndex REnd = LIS.getInstructionIndex(*Range.second); 700 701 // At the start of each iteration I has been advanced so that 702 // I.stop() >= PrevEnd. Check for overlap. 703 if (PrevEnd && I.start() < PrevEnd) { 704 SlotIndex IStop = I.stop(); 705 unsigned LocNo = I.value(); 706 707 // Stop overlaps previous end - trim the end of the interval to 708 // the scope range. 709 I.setStopUnchecked(PrevEnd); 710 ++I; 711 712 // If the interval also overlaps the start of the "next" (i.e. 713 // current) range create a new interval for the remainder (which 714 // may be further trimmed). 715 if (RStart < IStop) 716 I.insert(RStart, IStop, LocNo); 717 } 718 719 // Advance I so that I.stop() >= RStart, and check for overlap. 720 I.advanceTo(RStart); 721 if (!I.valid()) 722 return; 723 724 if (I.start() < RStart) { 725 // Interval start overlaps range - trim to the scope range. 726 I.setStartUnchecked(RStart); 727 // Remember that this interval was trimmed. 728 trimmedDefs.insert(RStart); 729 } 730 731 // The end of a lexical scope range is the last instruction in the 732 // range. To convert to an interval we need the index of the 733 // instruction after it. 734 REnd = REnd.getNextIndex(); 735 736 // Advance I to first interval outside current range. 737 I.advanceTo(REnd); 738 if (!I.valid()) 739 return; 740 741 PrevEnd = REnd; 742 } 743 744 // Check for overlap with end of final range. 745 if (PrevEnd && I.start() < PrevEnd) 746 I.setStopUnchecked(PrevEnd); 747 } 748 749 void LDVImpl::computeIntervals() { 750 LexicalScopes LS; 751 LS.initialize(*MF); 752 753 for (unsigned i = 0, e = userValues.size(); i != e; ++i) { 754 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS); 755 userValues[i]->mapVirtRegs(this); 756 } 757 } 758 759 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) { 760 clear(); 761 MF = &mf; 762 LIS = &pass.getAnalysis<LiveIntervals>(); 763 TRI = mf.getSubtarget().getRegisterInfo(); 764 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: " 765 << mf.getName() << " **********\n"); 766 767 bool Changed = collectDebugValues(mf); 768 computeIntervals(); 769 DEBUG(print(dbgs())); 770 ModifiedMF = Changed; 771 return Changed; 772 } 773 774 static void removeDebugValues(MachineFunction &mf) { 775 for (MachineBasicBlock &MBB : mf) { 776 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) { 777 if (!MBBI->isDebugValue()) { 778 ++MBBI; 779 continue; 780 } 781 MBBI = MBB.erase(MBBI); 782 } 783 } 784 } 785 786 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) { 787 if (!EnableLDV) 788 return false; 789 if (!mf.getFunction()->getSubprogram()) { 790 removeDebugValues(mf); 791 return false; 792 } 793 if (!pImpl) 794 pImpl = new LDVImpl(this); 795 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf); 796 } 797 798 void LiveDebugVariables::releaseMemory() { 799 if (pImpl) 800 static_cast<LDVImpl*>(pImpl)->clear(); 801 } 802 803 LiveDebugVariables::~LiveDebugVariables() { 804 if (pImpl) 805 delete static_cast<LDVImpl*>(pImpl); 806 } 807 808 //===----------------------------------------------------------------------===// 809 // Live Range Splitting 810 //===----------------------------------------------------------------------===// 811 812 bool 813 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 814 LiveIntervals& LIS) { 815 DEBUG({ 816 dbgs() << "Splitting Loc" << OldLocNo << '\t'; 817 print(dbgs(), nullptr); 818 }); 819 bool DidChange = false; 820 LocMap::iterator LocMapI; 821 LocMapI.setMap(locInts); 822 for (unsigned i = 0; i != NewRegs.size(); ++i) { 823 LiveInterval *LI = &LIS.getInterval(NewRegs[i]); 824 if (LI->empty()) 825 continue; 826 827 // Don't allocate the new LocNo until it is needed. 828 unsigned NewLocNo = UndefLocNo; 829 830 // Iterate over the overlaps between locInts and LI. 831 LocMapI.find(LI->beginIndex()); 832 if (!LocMapI.valid()) 833 continue; 834 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start()); 835 LiveInterval::iterator LIE = LI->end(); 836 while (LocMapI.valid() && LII != LIE) { 837 // At this point, we know that LocMapI.stop() > LII->start. 838 LII = LI->advanceTo(LII, LocMapI.start()); 839 if (LII == LIE) 840 break; 841 842 // Now LII->end > LocMapI.start(). Do we have an overlap? 843 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) { 844 // Overlapping correct location. Allocate NewLocNo now. 845 if (NewLocNo == UndefLocNo) { 846 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false); 847 MO.setSubReg(locations[OldLocNo].getSubReg()); 848 NewLocNo = getLocationNo(MO); 849 DidChange = true; 850 } 851 852 SlotIndex LStart = LocMapI.start(); 853 SlotIndex LStop = LocMapI.stop(); 854 855 // Trim LocMapI down to the LII overlap. 856 if (LStart < LII->start) 857 LocMapI.setStartUnchecked(LII->start); 858 if (LStop > LII->end) 859 LocMapI.setStopUnchecked(LII->end); 860 861 // Change the value in the overlap. This may trigger coalescing. 862 LocMapI.setValue(NewLocNo); 863 864 // Re-insert any removed OldLocNo ranges. 865 if (LStart < LocMapI.start()) { 866 LocMapI.insert(LStart, LocMapI.start(), OldLocNo); 867 ++LocMapI; 868 assert(LocMapI.valid() && "Unexpected coalescing"); 869 } 870 if (LStop > LocMapI.stop()) { 871 ++LocMapI; 872 LocMapI.insert(LII->end, LStop, OldLocNo); 873 --LocMapI; 874 } 875 } 876 877 // Advance to the next overlap. 878 if (LII->end < LocMapI.stop()) { 879 if (++LII == LIE) 880 break; 881 LocMapI.advanceTo(LII->start); 882 } else { 883 ++LocMapI; 884 if (!LocMapI.valid()) 885 break; 886 LII = LI->advanceTo(LII, LocMapI.start()); 887 } 888 } 889 } 890 891 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself. 892 locations.erase(locations.begin() + OldLocNo); 893 LocMapI.goToBegin(); 894 while (LocMapI.valid()) { 895 unsigned v = LocMapI.value(); 896 if (v == OldLocNo) { 897 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';' 898 << LocMapI.stop() << ")\n"); 899 LocMapI.erase(); 900 } else { 901 if (v > OldLocNo) 902 LocMapI.setValueUnchecked(v-1); 903 ++LocMapI; 904 } 905 } 906 907 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);}); 908 return DidChange; 909 } 910 911 bool 912 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, 913 LiveIntervals &LIS) { 914 bool DidChange = false; 915 // Split locations referring to OldReg. Iterate backwards so splitLocation can 916 // safely erase unused locations. 917 for (unsigned i = locations.size(); i ; --i) { 918 unsigned LocNo = i-1; 919 const MachineOperand *Loc = &locations[LocNo]; 920 if (!Loc->isReg() || Loc->getReg() != OldReg) 921 continue; 922 DidChange |= splitLocation(LocNo, NewRegs, LIS); 923 } 924 return DidChange; 925 } 926 927 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) { 928 bool DidChange = false; 929 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext()) 930 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS); 931 932 if (!DidChange) 933 return; 934 935 // Map all of the new virtual registers. 936 UserValue *UV = lookupVirtReg(OldReg); 937 for (unsigned i = 0; i != NewRegs.size(); ++i) 938 mapVirtReg(NewRegs[i], UV); 939 } 940 941 void LiveDebugVariables:: 942 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) { 943 if (pImpl) 944 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs); 945 } 946 947 void UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI, 948 BitVector &SpilledLocations) { 949 // Build a set of new locations with new numbers so we can coalesce our 950 // IntervalMap if two vreg intervals collapse to the same physical location. 951 // Use MapVector instead of SetVector because MapVector::insert returns the 952 // position of the previously or newly inserted element. The boolean value 953 // tracks if the location was produced by a spill. 954 // FIXME: This will be problematic if we ever support direct and indirect 955 // frame index locations, i.e. expressing both variables in memory and 956 // 'int x, *px = &x'. The "spilled" bit must become part of the location. 957 MapVector<MachineOperand, bool> NewLocations; 958 SmallVector<unsigned, 4> LocNoMap(locations.size()); 959 for (unsigned I = 0, E = locations.size(); I != E; ++I) { 960 bool Spilled = false; 961 MachineOperand Loc = locations[I]; 962 // Only virtual registers are rewritten. 963 if (Loc.isReg() && Loc.getReg() && 964 TargetRegisterInfo::isVirtualRegister(Loc.getReg())) { 965 unsigned VirtReg = Loc.getReg(); 966 if (VRM.isAssignedReg(VirtReg) && 967 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) { 968 // This can create a %noreg operand in rare cases when the sub-register 969 // index is no longer available. That means the user value is in a 970 // non-existent sub-register, and %noreg is exactly what we want. 971 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI); 972 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) { 973 // FIXME: Translate SubIdx to a stackslot offset. 974 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg)); 975 Spilled = true; 976 } else { 977 Loc.setReg(0); 978 Loc.setSubReg(0); 979 } 980 } 981 982 // Insert this location if it doesn't already exist and record a mapping 983 // from the old number to the new number. 984 auto InsertResult = NewLocations.insert({Loc, Spilled}); 985 unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first); 986 LocNoMap[I] = NewLocNo; 987 } 988 989 // Rewrite the locations and record which ones were spill slots. 990 locations.clear(); 991 SpilledLocations.clear(); 992 SpilledLocations.resize(NewLocations.size()); 993 for (auto &Pair : NewLocations) { 994 locations.push_back(Pair.first); 995 if (Pair.second) { 996 unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair); 997 SpilledLocations.set(NewLocNo); 998 } 999 } 1000 1001 // Update the interval map, but only coalesce left, since intervals to the 1002 // right use the old location numbers. This should merge two contiguous 1003 // DBG_VALUE intervals with different vregs that were allocated to the same 1004 // physical register. 1005 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) { 1006 unsigned NewLocNo = LocNoMap[I.value()]; 1007 I.setValueUnchecked(NewLocNo); 1008 I.setStart(I.start()); 1009 } 1010 } 1011 1012 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE 1013 /// instruction. 1014 static MachineBasicBlock::iterator 1015 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, 1016 LiveIntervals &LIS) { 1017 SlotIndex Start = LIS.getMBBStartIdx(MBB); 1018 Idx = Idx.getBaseIndex(); 1019 1020 // Try to find an insert location by going backwards from Idx. 1021 MachineInstr *MI; 1022 while (!(MI = LIS.getInstructionFromIndex(Idx))) { 1023 // We've reached the beginning of MBB. 1024 if (Idx == Start) { 1025 MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin()); 1026 return I; 1027 } 1028 Idx = Idx.getPrevIndex(); 1029 } 1030 1031 // Don't insert anything after the first terminator, though. 1032 return MI->isTerminator() ? MBB->getFirstTerminator() : 1033 std::next(MachineBasicBlock::iterator(MI)); 1034 } 1035 1036 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, 1037 unsigned LocNo, bool Spilled, 1038 LiveIntervals &LIS, 1039 const TargetInstrInfo &TII) { 1040 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS); 1041 MachineOperand &Loc = locations[LocNo]; 1042 ++NumInsertedDebugValues; 1043 1044 assert(cast<DILocalVariable>(Variable) 1045 ->isValidLocationForIntrinsic(getDebugLoc()) && 1046 "Expected inlined-at fields to agree"); 1047 1048 // If the location was spilled, the new DBG_VALUE will be indirect. If the 1049 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate 1050 // that the original virtual register was a pointer. 1051 bool NewIndirect = IsIndirect || Spilled; 1052 const DIExpression *Expr = Expression; 1053 if (Spilled && IsIndirect) 1054 Expr = DIExpression::prepend(Expr, DIExpression::WithDeref); 1055 1056 assert((!Spilled || Loc.isFI()) && 1057 "a spilled location must be a frame index"); 1058 1059 MachineInstrBuilder MIB = 1060 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE)) 1061 .add(Loc); 1062 if (NewIndirect) 1063 MIB.addImm(0U); 1064 else 1065 MIB.addReg(0U, RegState::Debug); 1066 MIB.addMetadata(Variable).addMetadata(Expr); 1067 } 1068 1069 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 1070 const TargetInstrInfo &TII, 1071 const BitVector &SpilledLocations) { 1072 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end(); 1073 1074 for (LocMap::const_iterator I = locInts.begin(); I.valid();) { 1075 SlotIndex Start = I.start(); 1076 SlotIndex Stop = I.stop(); 1077 unsigned LocNo = I.value(); 1078 bool Spilled = LocNo != UndefLocNo ? SpilledLocations.test(LocNo) : false; 1079 1080 // If the interval start was trimmed to the lexical scope insert the 1081 // DBG_VALUE at the previous index (otherwise it appears after the 1082 // first instruction in the range). 1083 if (trimmedDefs.count(Start)) 1084 Start = Start.getPrevIndex(); 1085 1086 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo); 1087 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); 1088 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB); 1089 1090 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd); 1091 insertDebugValue(&*MBB, Start, LocNo, Spilled, LIS, TII); 1092 // This interval may span multiple basic blocks. 1093 // Insert a DBG_VALUE into each one. 1094 while(Stop > MBBEnd) { 1095 // Move to the next block. 1096 Start = MBBEnd; 1097 if (++MBB == MFEnd) 1098 break; 1099 MBBEnd = LIS.getMBBEndIdx(&*MBB); 1100 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd); 1101 insertDebugValue(&*MBB, Start, LocNo, Spilled, LIS, TII); 1102 } 1103 DEBUG(dbgs() << '\n'); 1104 if (MBB == MFEnd) 1105 break; 1106 1107 ++I; 1108 } 1109 } 1110 1111 void LDVImpl::emitDebugValues(VirtRegMap *VRM) { 1112 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n"); 1113 if (!MF) 1114 return; 1115 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1116 BitVector SpilledLocations; 1117 for (unsigned i = 0, e = userValues.size(); i != e; ++i) { 1118 DEBUG(userValues[i]->print(dbgs(), TRI)); 1119 userValues[i]->rewriteLocations(*VRM, *TRI, SpilledLocations); 1120 userValues[i]->emitDebugValues(VRM, *LIS, *TII, SpilledLocations); 1121 } 1122 EmitDone = true; 1123 } 1124 1125 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) { 1126 if (pImpl) 1127 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM); 1128 } 1129 1130 bool LiveDebugVariables::doInitialization(Module &M) { 1131 return Pass::doInitialization(M); 1132 } 1133 1134 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1135 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const { 1136 if (pImpl) 1137 static_cast<LDVImpl*>(pImpl)->print(dbgs()); 1138 } 1139 #endif 1140