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