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