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