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