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