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/BinaryFormat/Dwarf.h" 32 #include "llvm/CodeGen/LexicalScopes.h" 33 #include "llvm/CodeGen/LiveInterval.h" 34 #include "llvm/CodeGen/LiveIntervals.h" 35 #include "llvm/CodeGen/MachineBasicBlock.h" 36 #include "llvm/CodeGen/MachineDominators.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineInstr.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineOperand.h" 41 #include "llvm/CodeGen/MachineRegisterInfo.h" 42 #include "llvm/CodeGen/SlotIndexes.h" 43 #include "llvm/CodeGen/TargetInstrInfo.h" 44 #include "llvm/CodeGen/TargetOpcodes.h" 45 #include "llvm/CodeGen/TargetRegisterInfo.h" 46 #include "llvm/CodeGen/TargetSubtargetInfo.h" 47 #include "llvm/CodeGen/VirtRegMap.h" 48 #include "llvm/Config/llvm-config.h" 49 #include "llvm/IR/DebugInfoMetadata.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/Function.h" 52 #include "llvm/InitializePasses.h" 53 #include "llvm/Pass.h" 54 #include "llvm/Support/Casting.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include <algorithm> 59 #include <cassert> 60 #include <iterator> 61 #include <memory> 62 #include <optional> 63 #include <utility> 64 65 using namespace llvm; 66 67 #define DEBUG_TYPE "livedebugvars" 68 69 static cl::opt<bool> 70 EnableLDV("live-debug-variables", cl::init(true), 71 cl::desc("Enable the live debug variables pass"), cl::Hidden); 72 73 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted"); 74 STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted"); 75 76 char LiveDebugVariables::ID = 0; 77 78 INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE, 79 "Debug Variable Analysis", false, false) 80 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 81 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 82 INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE, 83 "Debug Variable Analysis", false, false) 84 85 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const { 86 AU.addRequired<MachineDominatorTree>(); 87 AU.addRequiredTransitive<LiveIntervals>(); 88 AU.setPreservesAll(); 89 MachineFunctionPass::getAnalysisUsage(AU); 90 } 91 92 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) { 93 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry()); 94 } 95 96 enum : unsigned { UndefLocNo = ~0U }; 97 98 namespace { 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(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList, 104 const DIExpression &Expr) 105 : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) { 106 assert(!(WasIndirect && WasList) && 107 "DBG_VALUE_LISTs should not be indirect."); 108 SmallVector<unsigned> LocNoVec; 109 for (unsigned LocNo : NewLocs) { 110 auto It = find(LocNoVec, LocNo); 111 if (It == LocNoVec.end()) 112 LocNoVec.push_back(LocNo); 113 else { 114 // Loc duplicates an element in LocNos; replace references to Op 115 // with references to the duplicating element. 116 unsigned OpIdx = LocNoVec.size(); 117 unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It); 118 Expression = 119 DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx); 120 } 121 } 122 // FIXME: Debug values referencing 64+ unique machine locations are rare and 123 // currently unsupported for performance reasons. If we can verify that 124 // performance is acceptable for such debug values, we can increase the 125 // bit-width of LocNoCount to 14 to enable up to 16384 unique machine 126 // locations. We will also need to verify that this does not cause issues 127 // with LiveDebugVariables' use of IntervalMap. 128 if (LocNoVec.size() < 64) { 129 LocNoCount = LocNoVec.size(); 130 if (LocNoCount > 0) { 131 LocNos = std::make_unique<unsigned[]>(LocNoCount); 132 std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin()); 133 } 134 } else { 135 LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine " 136 "locations, dropping...\n"); 137 LocNoCount = 1; 138 // Turn this into an undef debug value list; right now, the simplest form 139 // of this is an expression with one arg, and an undef debug operand. 140 Expression = 141 DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0, 142 dwarf::DW_OP_stack_value}); 143 if (auto FragmentInfoOpt = Expr.getFragmentInfo()) 144 Expression = *DIExpression::createFragmentExpression( 145 Expression, FragmentInfoOpt->OffsetInBits, 146 FragmentInfoOpt->SizeInBits); 147 LocNos = std::make_unique<unsigned[]>(LocNoCount); 148 LocNos[0] = UndefLocNo; 149 } 150 } 151 152 DbgVariableValue() : LocNoCount(0), WasIndirect(false), WasList(false) {} 153 DbgVariableValue(const DbgVariableValue &Other) 154 : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()), 155 WasList(Other.getWasList()), Expression(Other.getExpression()) { 156 if (Other.getLocNoCount()) { 157 LocNos.reset(new unsigned[Other.getLocNoCount()]); 158 std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin()); 159 } 160 } 161 162 DbgVariableValue &operator=(const DbgVariableValue &Other) { 163 if (this == &Other) 164 return *this; 165 if (Other.getLocNoCount()) { 166 LocNos.reset(new unsigned[Other.getLocNoCount()]); 167 std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin()); 168 } else { 169 LocNos.release(); 170 } 171 LocNoCount = Other.getLocNoCount(); 172 WasIndirect = Other.getWasIndirect(); 173 WasList = Other.getWasList(); 174 Expression = Other.getExpression(); 175 return *this; 176 } 177 178 const DIExpression *getExpression() const { return Expression; } 179 uint8_t getLocNoCount() const { return LocNoCount; } 180 bool containsLocNo(unsigned LocNo) const { 181 return is_contained(loc_nos(), LocNo); 182 } 183 bool getWasIndirect() const { return WasIndirect; } 184 bool getWasList() const { return WasList; } 185 bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); } 186 187 DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const { 188 SmallVector<unsigned, 4> NewLocNos; 189 for (unsigned LocNo : loc_nos()) 190 NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1 191 : LocNo); 192 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression); 193 } 194 195 DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const { 196 SmallVector<unsigned> NewLocNos; 197 for (unsigned LocNo : loc_nos()) 198 // Undef values don't exist in locations (and thus not in LocNoMap 199 // either) so skip over them. See getLocationNo(). 200 NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]); 201 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression); 202 } 203 204 DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const { 205 SmallVector<unsigned> NewLocNos; 206 NewLocNos.assign(loc_nos_begin(), loc_nos_end()); 207 auto OldLocIt = find(NewLocNos, OldLocNo); 208 assert(OldLocIt != NewLocNos.end() && "Old location must be present."); 209 *OldLocIt = NewLocNo; 210 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression); 211 } 212 213 bool hasLocNoGreaterThan(unsigned LocNo) const { 214 return any_of(loc_nos(), 215 [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; }); 216 } 217 218 void printLocNos(llvm::raw_ostream &OS) const { 219 for (const unsigned &Loc : loc_nos()) 220 OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc; 221 } 222 223 friend inline bool operator==(const DbgVariableValue &LHS, 224 const DbgVariableValue &RHS) { 225 if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList, 226 LHS.Expression) != 227 std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression)) 228 return false; 229 return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(), 230 RHS.loc_nos_begin()); 231 } 232 233 friend inline bool operator!=(const DbgVariableValue &LHS, 234 const DbgVariableValue &RHS) { 235 return !(LHS == RHS); 236 } 237 238 unsigned *loc_nos_begin() { return LocNos.get(); } 239 const unsigned *loc_nos_begin() const { return LocNos.get(); } 240 unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; } 241 const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; } 242 ArrayRef<unsigned> loc_nos() const { 243 return ArrayRef<unsigned>(LocNos.get(), LocNoCount); 244 } 245 246 private: 247 // IntervalMap requires the value object to be very small, to the extent 248 // that we do not have enough room for an std::vector. Using a C-style array 249 // (with a unique_ptr wrapper for convenience) allows us to optimize for this 250 // specific case by packing the array size into only 6 bits (it is highly 251 // unlikely that any debug value will need 64+ locations). 252 std::unique_ptr<unsigned[]> LocNos; 253 uint8_t LocNoCount : 6; 254 bool WasIndirect : 1; 255 bool WasList : 1; 256 const DIExpression *Expression = nullptr; 257 }; 258 } // namespace 259 260 /// Map of where a user value is live to that value. 261 using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>; 262 263 /// Map of stack slot offsets for spilled locations. 264 /// Non-spilled locations are not added to the map. 265 using SpillOffsetMap = DenseMap<unsigned, unsigned>; 266 267 /// Cache to save the location where it can be used as the starting 268 /// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug. 269 /// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from 270 /// repeatedly searching the same set of PHIs/Labels/Debug instructions 271 /// if it is called many times for the same block. 272 using BlockSkipInstsMap = 273 DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>; 274 275 namespace { 276 277 class LDVImpl; 278 279 /// A user value is a part of a debug info user variable. 280 /// 281 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register 282 /// holds part of a user variable. The part is identified by a byte offset. 283 /// 284 /// UserValues are grouped into equivalence classes for easier searching. Two 285 /// user values are related if they are held by the same virtual register. The 286 /// equivalence class is the transitive closure of that relation. 287 class UserValue { 288 const DILocalVariable *Variable; ///< The debug info variable we are part of. 289 /// The part of the variable we describe. 290 const std::optional<DIExpression::FragmentInfo> Fragment; 291 DebugLoc dl; ///< The debug location for the variable. This is 292 ///< used by dwarf writer to find lexical scope. 293 UserValue *leader; ///< Equivalence class leader. 294 UserValue *next = nullptr; ///< Next value in equivalence class, or null. 295 296 /// Numbered locations referenced by locmap. 297 SmallVector<MachineOperand, 4> locations; 298 299 /// Map of slot indices where this value is live. 300 LocMap locInts; 301 302 /// Set of interval start indexes that have been trimmed to the 303 /// lexical scope. 304 SmallSet<SlotIndex, 2> trimmedDefs; 305 306 /// Insert a DBG_VALUE into MBB at Idx for DbgValue. 307 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx, 308 SlotIndex StopIdx, DbgVariableValue DbgValue, 309 ArrayRef<bool> LocSpills, 310 ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS, 311 const TargetInstrInfo &TII, 312 const TargetRegisterInfo &TRI, 313 BlockSkipInstsMap &BBSkipInstsMap); 314 315 /// Replace OldLocNo ranges with NewRegs ranges where NewRegs 316 /// is live. Returns true if any changes were made. 317 bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs, 318 LiveIntervals &LIS); 319 320 public: 321 /// Create a new UserValue. 322 UserValue(const DILocalVariable *var, 323 std::optional<DIExpression::FragmentInfo> Fragment, DebugLoc L, 324 LocMap::Allocator &alloc) 325 : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this), 326 locInts(alloc) {} 327 328 /// Get the leader of this value's equivalence class. 329 UserValue *getLeader() { 330 UserValue *l = leader; 331 while (l != l->leader) 332 l = l->leader; 333 return leader = l; 334 } 335 336 /// Return the next UserValue in the equivalence class. 337 UserValue *getNext() const { return next; } 338 339 /// Merge equivalence classes. 340 static UserValue *merge(UserValue *L1, UserValue *L2) { 341 L2 = L2->getLeader(); 342 if (!L1) 343 return L2; 344 L1 = L1->getLeader(); 345 if (L1 == L2) 346 return L1; 347 // Splice L2 before L1's members. 348 UserValue *End = L2; 349 while (End->next) { 350 End->leader = L1; 351 End = End->next; 352 } 353 End->leader = L1; 354 End->next = L1->next; 355 L1->next = L2; 356 return L1; 357 } 358 359 /// Return the location number that matches Loc. 360 /// 361 /// For undef values we always return location number UndefLocNo without 362 /// inserting anything in locations. Since locations is a vector and the 363 /// location number is the position in the vector and UndefLocNo is ~0, 364 /// we would need a very big vector to put the value at the right position. 365 unsigned getLocationNo(const MachineOperand &LocMO) { 366 if (LocMO.isReg()) { 367 if (LocMO.getReg() == 0) 368 return UndefLocNo; 369 // For register locations we dont care about use/def and other flags. 370 for (unsigned i = 0, e = locations.size(); i != e; ++i) 371 if (locations[i].isReg() && 372 locations[i].getReg() == LocMO.getReg() && 373 locations[i].getSubReg() == LocMO.getSubReg()) 374 return i; 375 } else 376 for (unsigned i = 0, e = locations.size(); i != e; ++i) 377 if (LocMO.isIdenticalTo(locations[i])) 378 return i; 379 locations.push_back(LocMO); 380 // We are storing a MachineOperand outside a MachineInstr. 381 locations.back().clearParent(); 382 // Don't store def operands. 383 if (locations.back().isReg()) { 384 if (locations.back().isDef()) 385 locations.back().setIsDead(false); 386 locations.back().setIsUse(); 387 } 388 return locations.size() - 1; 389 } 390 391 /// Remove (recycle) a location number. If \p LocNo still is used by the 392 /// locInts nothing is done. 393 void removeLocationIfUnused(unsigned LocNo) { 394 // Bail out if LocNo still is used. 395 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) { 396 const DbgVariableValue &DbgValue = I.value(); 397 if (DbgValue.containsLocNo(LocNo)) 398 return; 399 } 400 // Remove the entry in the locations vector, and adjust all references to 401 // location numbers above the removed entry. 402 locations.erase(locations.begin() + LocNo); 403 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) { 404 const DbgVariableValue &DbgValue = I.value(); 405 if (DbgValue.hasLocNoGreaterThan(LocNo)) 406 I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo)); 407 } 408 } 409 410 /// Ensure that all virtual register locations are mapped. 411 void mapVirtRegs(LDVImpl *LDV); 412 413 /// Add a definition point to this user value. 414 void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect, 415 bool IsList, const DIExpression &Expr) { 416 SmallVector<unsigned> Locs; 417 for (const MachineOperand &Op : LocMOs) 418 Locs.push_back(getLocationNo(Op)); 419 DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr); 420 // Add a singular (Idx,Idx) -> value mapping. 421 LocMap::iterator I = locInts.find(Idx); 422 if (!I.valid() || I.start() != Idx) 423 I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue)); 424 else 425 // A later DBG_VALUE at the same SlotIndex overrides the old location. 426 I.setValue(std::move(DbgValue)); 427 } 428 429 /// Extend the current definition as far as possible down. 430 /// 431 /// Stop when meeting an existing def or when leaving the live 432 /// range of VNI. End points where VNI is no longer live are added to Kills. 433 /// 434 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a 435 /// data-flow analysis to propagate them beyond basic block boundaries. 436 /// 437 /// \param Idx Starting point for the definition. 438 /// \param DbgValue value to propagate. 439 /// \param LiveIntervalInfo For each location number key in this map, 440 /// restricts liveness to where the LiveRange has the value equal to the\ 441 /// VNInfo. 442 /// \param [out] Kills Append end points of VNI's live range to Kills. 443 /// \param LIS Live intervals analysis. 444 void 445 extendDef(SlotIndex Idx, DbgVariableValue DbgValue, 446 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> 447 &LiveIntervalInfo, 448 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills, 449 LiveIntervals &LIS); 450 451 /// The value in LI may be copies to other registers. Determine if 452 /// any of the copies are available at the kill points, and add defs if 453 /// possible. 454 /// 455 /// \param DbgValue Location number of LI->reg, and DIExpression. 456 /// \param LocIntervals Scan for copies of the value for each location in the 457 /// corresponding LiveInterval->reg. 458 /// \param KilledAt The point where the range of DbgValue could be extended. 459 /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here. 460 void addDefsFromCopies( 461 DbgVariableValue DbgValue, 462 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals, 463 SlotIndex KilledAt, 464 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs, 465 MachineRegisterInfo &MRI, LiveIntervals &LIS); 466 467 /// Compute the live intervals of all locations after collecting all their 468 /// def points. 469 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, 470 LiveIntervals &LIS, LexicalScopes &LS); 471 472 /// Replace OldReg ranges with NewRegs ranges where NewRegs is 473 /// live. Returns true if any changes were made. 474 bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs, 475 LiveIntervals &LIS); 476 477 /// Rewrite virtual register locations according to the provided virtual 478 /// register map. Record the stack slot offsets for the locations that 479 /// were spilled. 480 void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF, 481 const TargetInstrInfo &TII, 482 const TargetRegisterInfo &TRI, 483 SpillOffsetMap &SpillOffsets); 484 485 /// Recreate DBG_VALUE instruction from data structures. 486 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 487 const TargetInstrInfo &TII, 488 const TargetRegisterInfo &TRI, 489 const SpillOffsetMap &SpillOffsets, 490 BlockSkipInstsMap &BBSkipInstsMap); 491 492 /// Return DebugLoc of this UserValue. 493 const DebugLoc &getDebugLoc() { return dl; } 494 495 void print(raw_ostream &, const TargetRegisterInfo *); 496 }; 497 498 /// A user label is a part of a debug info user label. 499 class UserLabel { 500 const DILabel *Label; ///< The debug info label we are part of. 501 DebugLoc dl; ///< The debug location for the label. This is 502 ///< used by dwarf writer to find lexical scope. 503 SlotIndex loc; ///< Slot used by the debug label. 504 505 /// Insert a DBG_LABEL into MBB at Idx. 506 void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx, 507 LiveIntervals &LIS, const TargetInstrInfo &TII, 508 BlockSkipInstsMap &BBSkipInstsMap); 509 510 public: 511 /// Create a new UserLabel. 512 UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx) 513 : Label(label), dl(std::move(L)), loc(Idx) {} 514 515 /// Does this UserLabel match the parameters? 516 bool matches(const DILabel *L, const DILocation *IA, 517 const SlotIndex Index) const { 518 return Label == L && dl->getInlinedAt() == IA && loc == Index; 519 } 520 521 /// Recreate DBG_LABEL instruction from data structures. 522 void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII, 523 BlockSkipInstsMap &BBSkipInstsMap); 524 525 /// Return DebugLoc of this UserLabel. 526 const DebugLoc &getDebugLoc() { return dl; } 527 528 void print(raw_ostream &, const TargetRegisterInfo *); 529 }; 530 531 /// Implementation of the LiveDebugVariables pass. 532 class LDVImpl { 533 LiveDebugVariables &pass; 534 LocMap::Allocator allocator; 535 MachineFunction *MF = nullptr; 536 LiveIntervals *LIS; 537 const TargetRegisterInfo *TRI; 538 539 /// Position and VReg of a PHI instruction during register allocation. 540 struct PHIValPos { 541 SlotIndex SI; /// Slot where this PHI occurs. 542 Register Reg; /// VReg this PHI occurs in. 543 unsigned SubReg; /// Qualifiying subregister for Reg. 544 }; 545 546 /// Map from debug instruction number to PHI position during allocation. 547 std::map<unsigned, PHIValPos> PHIValToPos; 548 /// Index of, for each VReg, which debug instruction numbers and corresponding 549 /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs, 550 /// at different positions. 551 DenseMap<Register, std::vector<unsigned>> RegToPHIIdx; 552 553 /// Record for any debug instructions unlinked from their blocks during 554 /// regalloc. Stores the instr and it's location, so that they can be 555 /// re-inserted after regalloc is over. 556 struct InstrPos { 557 MachineInstr *MI; ///< Debug instruction, unlinked from it's block. 558 SlotIndex Idx; ///< Slot position where MI should be re-inserted. 559 MachineBasicBlock *MBB; ///< Block that MI was in. 560 }; 561 562 /// Collection of stored debug instructions, preserved until after regalloc. 563 SmallVector<InstrPos, 32> StashedDebugInstrs; 564 565 /// Whether emitDebugValues is called. 566 bool EmitDone = false; 567 568 /// Whether the machine function is modified during the pass. 569 bool ModifiedMF = false; 570 571 /// All allocated UserValue instances. 572 SmallVector<std::unique_ptr<UserValue>, 8> userValues; 573 574 /// All allocated UserLabel instances. 575 SmallVector<std::unique_ptr<UserLabel>, 2> userLabels; 576 577 /// Map virtual register to eq class leader. 578 using VRMap = DenseMap<unsigned, UserValue *>; 579 VRMap virtRegToEqClass; 580 581 /// Map to find existing UserValue instances. 582 using UVMap = DenseMap<DebugVariable, UserValue *>; 583 UVMap userVarMap; 584 585 /// Find or create a UserValue. 586 UserValue *getUserValue(const DILocalVariable *Var, 587 std::optional<DIExpression::FragmentInfo> Fragment, 588 const DebugLoc &DL); 589 590 /// Find the EC leader for VirtReg or null. 591 UserValue *lookupVirtReg(Register VirtReg); 592 593 /// Add DBG_VALUE instruction to our maps. 594 /// 595 /// \param MI DBG_VALUE instruction 596 /// \param Idx Last valid SLotIndex before instruction. 597 /// 598 /// \returns True if the DBG_VALUE instruction should be deleted. 599 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx); 600 601 /// Track variable location debug instructions while using the instruction 602 /// referencing implementation. Such debug instructions do not need to be 603 /// updated during regalloc because they identify instructions rather than 604 /// register locations. However, they needs to be removed from the 605 /// MachineFunction during regalloc, then re-inserted later, to avoid 606 /// disrupting the allocator. 607 /// 608 /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction 609 /// \param Idx Last valid SlotIndex before instruction 610 /// 611 /// \returns Iterator to continue processing from after unlinking. 612 MachineBasicBlock::iterator handleDebugInstr(MachineInstr &MI, SlotIndex Idx); 613 614 /// Add DBG_LABEL instruction to UserLabel. 615 /// 616 /// \param MI DBG_LABEL instruction 617 /// \param Idx Last valid SlotIndex before instruction. 618 /// 619 /// \returns True if the DBG_LABEL instruction should be deleted. 620 bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx); 621 622 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def 623 /// for each instruction. 624 /// 625 /// \param mf MachineFunction to be scanned. 626 /// \param InstrRef Whether to operate in instruction referencing mode. If 627 /// true, most of LiveDebugVariables doesn't run. 628 /// 629 /// \returns True if any debug values were found. 630 bool collectDebugValues(MachineFunction &mf, bool InstrRef); 631 632 /// Compute the live intervals of all user values after collecting all 633 /// their def points. 634 void computeIntervals(); 635 636 public: 637 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {} 638 639 bool runOnMachineFunction(MachineFunction &mf, bool InstrRef); 640 641 /// Release all memory. 642 void clear() { 643 MF = nullptr; 644 PHIValToPos.clear(); 645 RegToPHIIdx.clear(); 646 StashedDebugInstrs.clear(); 647 userValues.clear(); 648 userLabels.clear(); 649 virtRegToEqClass.clear(); 650 userVarMap.clear(); 651 // Make sure we call emitDebugValues if the machine function was modified. 652 assert((!ModifiedMF || EmitDone) && 653 "Dbg values are not emitted in LDV"); 654 EmitDone = false; 655 ModifiedMF = false; 656 } 657 658 /// Map virtual register to an equivalence class. 659 void mapVirtReg(Register VirtReg, UserValue *EC); 660 661 /// Replace any PHI referring to OldReg with its corresponding NewReg, if 662 /// present. 663 void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs); 664 665 /// Replace all references to OldReg with NewRegs. 666 void splitRegister(Register OldReg, ArrayRef<Register> NewRegs); 667 668 /// Recreate DBG_VALUE instruction from data structures. 669 void emitDebugValues(VirtRegMap *VRM); 670 671 void print(raw_ostream&); 672 }; 673 674 } // end anonymous namespace 675 676 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 677 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS, 678 const LLVMContext &Ctx) { 679 if (!DL) 680 return; 681 682 auto *Scope = cast<DIScope>(DL.getScope()); 683 // Omit the directory, because it's likely to be long and uninteresting. 684 CommentOS << Scope->getFilename(); 685 CommentOS << ':' << DL.getLine(); 686 if (DL.getCol() != 0) 687 CommentOS << ':' << DL.getCol(); 688 689 DebugLoc InlinedAtDL = DL.getInlinedAt(); 690 if (!InlinedAtDL) 691 return; 692 693 CommentOS << " @[ "; 694 printDebugLoc(InlinedAtDL, CommentOS, Ctx); 695 CommentOS << " ]"; 696 } 697 698 static void printExtendedName(raw_ostream &OS, const DINode *Node, 699 const DILocation *DL) { 700 const LLVMContext &Ctx = Node->getContext(); 701 StringRef Res; 702 unsigned Line = 0; 703 if (const auto *V = dyn_cast<const DILocalVariable>(Node)) { 704 Res = V->getName(); 705 Line = V->getLine(); 706 } else if (const auto *L = dyn_cast<const DILabel>(Node)) { 707 Res = L->getName(); 708 Line = L->getLine(); 709 } 710 711 if (!Res.empty()) 712 OS << Res << "," << Line; 713 auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr; 714 if (InlinedAt) { 715 if (DebugLoc InlinedAtDL = InlinedAt) { 716 OS << " @["; 717 printDebugLoc(InlinedAtDL, OS, Ctx); 718 OS << "]"; 719 } 720 } 721 } 722 723 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) { 724 OS << "!\""; 725 printExtendedName(OS, Variable, dl); 726 727 OS << "\"\t"; 728 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) { 729 OS << " [" << I.start() << ';' << I.stop() << "):"; 730 if (I.value().isUndef()) 731 OS << " undef"; 732 else { 733 I.value().printLocNos(OS); 734 if (I.value().getWasIndirect()) 735 OS << " ind"; 736 else if (I.value().getWasList()) 737 OS << " list"; 738 } 739 } 740 for (unsigned i = 0, e = locations.size(); i != e; ++i) { 741 OS << " Loc" << i << '='; 742 locations[i].print(OS, TRI); 743 } 744 OS << '\n'; 745 } 746 747 void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) { 748 OS << "!\""; 749 printExtendedName(OS, Label, dl); 750 751 OS << "\"\t"; 752 OS << loc; 753 OS << '\n'; 754 } 755 756 void LDVImpl::print(raw_ostream &OS) { 757 OS << "********** DEBUG VARIABLES **********\n"; 758 for (auto &userValue : userValues) 759 userValue->print(OS, TRI); 760 OS << "********** DEBUG LABELS **********\n"; 761 for (auto &userLabel : userLabels) 762 userLabel->print(OS, TRI); 763 } 764 #endif 765 766 void UserValue::mapVirtRegs(LDVImpl *LDV) { 767 for (unsigned i = 0, e = locations.size(); i != e; ++i) 768 if (locations[i].isReg() && 769 Register::isVirtualRegister(locations[i].getReg())) 770 LDV->mapVirtReg(locations[i].getReg(), this); 771 } 772 773 UserValue * 774 LDVImpl::getUserValue(const DILocalVariable *Var, 775 std::optional<DIExpression::FragmentInfo> Fragment, 776 const DebugLoc &DL) { 777 // FIXME: Handle partially overlapping fragments. See 778 // https://reviews.llvm.org/D70121#1849741. 779 DebugVariable ID(Var, Fragment, DL->getInlinedAt()); 780 UserValue *&UV = userVarMap[ID]; 781 if (!UV) { 782 userValues.push_back( 783 std::make_unique<UserValue>(Var, Fragment, DL, allocator)); 784 UV = userValues.back().get(); 785 } 786 return UV; 787 } 788 789 void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) { 790 assert(Register::isVirtualRegister(VirtReg) && "Only map VirtRegs"); 791 UserValue *&Leader = virtRegToEqClass[VirtReg]; 792 Leader = UserValue::merge(Leader, EC); 793 } 794 795 UserValue *LDVImpl::lookupVirtReg(Register VirtReg) { 796 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg)) 797 return UV->getLeader(); 798 return nullptr; 799 } 800 801 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) { 802 // DBG_VALUE loc, offset, variable, expr 803 // DBG_VALUE_LIST variable, expr, locs... 804 if (!MI.isDebugValue()) { 805 LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI); 806 return false; 807 } 808 if (!MI.getDebugVariableOp().isMetadata()) { 809 LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: " 810 << MI); 811 return false; 812 } 813 if (MI.isNonListDebugValue() && 814 (MI.getNumOperands() != 4 || 815 !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) { 816 LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI); 817 return false; 818 } 819 820 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual 821 // register that hasn't been defined yet. If we do not remove those here, then 822 // the re-insertion of the DBG_VALUE instruction after register allocation 823 // will be incorrect. 824 bool Discard = false; 825 for (const MachineOperand &Op : MI.debug_operands()) { 826 if (Op.isReg() && Register::isVirtualRegister(Op.getReg())) { 827 const Register Reg = Op.getReg(); 828 if (!LIS->hasInterval(Reg)) { 829 // The DBG_VALUE is described by a virtual register that does not have a 830 // live interval. Discard the DBG_VALUE. 831 Discard = true; 832 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx 833 << " " << MI); 834 } else { 835 // The DBG_VALUE is only valid if either Reg is live out from Idx, or 836 // Reg is defined dead at Idx (where Idx is the slot index for the 837 // instruction preceding the DBG_VALUE). 838 const LiveInterval &LI = LIS->getInterval(Reg); 839 LiveQueryResult LRQ = LI.Query(Idx); 840 if (!LRQ.valueOutOrDead()) { 841 // We have found a DBG_VALUE with the value in a virtual register that 842 // is not live. Discard the DBG_VALUE. 843 Discard = true; 844 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx 845 << " " << MI); 846 } 847 } 848 } 849 } 850 851 // Get or create the UserValue for (variable,offset) here. 852 bool IsIndirect = MI.isDebugOffsetImm(); 853 if (IsIndirect) 854 assert(MI.getDebugOffset().getImm() == 0 && 855 "DBG_VALUE with nonzero offset"); 856 bool IsList = MI.isDebugValueList(); 857 const DILocalVariable *Var = MI.getDebugVariable(); 858 const DIExpression *Expr = MI.getDebugExpression(); 859 UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc()); 860 if (!Discard) 861 UV->addDef(Idx, 862 ArrayRef<MachineOperand>(MI.debug_operands().begin(), 863 MI.debug_operands().end()), 864 IsIndirect, IsList, *Expr); 865 else { 866 MachineOperand MO = MachineOperand::CreateReg(0U, false); 867 MO.setIsDebug(); 868 // We should still pass a list the same size as MI.debug_operands() even if 869 // all MOs are undef, so that DbgVariableValue can correctly adjust the 870 // expression while removing the duplicated undefs. 871 SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO); 872 UV->addDef(Idx, UndefMOs, false, IsList, *Expr); 873 } 874 return true; 875 } 876 877 MachineBasicBlock::iterator LDVImpl::handleDebugInstr(MachineInstr &MI, 878 SlotIndex Idx) { 879 assert(MI.isDebugValueLike() || MI.isDebugPHI()); 880 881 // In instruction referencing mode, there should be no DBG_VALUE instructions 882 // that refer to virtual registers. They might still refer to constants. 883 if (MI.isDebugValueLike()) 884 assert(none_of(MI.debug_operands(), 885 [](const MachineOperand &MO) { 886 return MO.isReg() && MO.getReg().isVirtual(); 887 }) && 888 "MIs should not refer to Virtual Registers in InstrRef mode."); 889 890 // Unlink the instruction, store it in the debug instructions collection. 891 auto NextInst = std::next(MI.getIterator()); 892 auto *MBB = MI.getParent(); 893 MI.removeFromParent(); 894 StashedDebugInstrs.push_back({&MI, Idx, MBB}); 895 return NextInst; 896 } 897 898 bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) { 899 // DBG_LABEL label 900 if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) { 901 LLVM_DEBUG(dbgs() << "Can't handle " << MI); 902 return false; 903 } 904 905 // Get or create the UserLabel for label here. 906 const DILabel *Label = MI.getDebugLabel(); 907 const DebugLoc &DL = MI.getDebugLoc(); 908 bool Found = false; 909 for (auto const &L : userLabels) { 910 if (L->matches(Label, DL->getInlinedAt(), Idx)) { 911 Found = true; 912 break; 913 } 914 } 915 if (!Found) 916 userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx)); 917 918 return true; 919 } 920 921 bool LDVImpl::collectDebugValues(MachineFunction &mf, bool InstrRef) { 922 bool Changed = false; 923 for (MachineBasicBlock &MBB : mf) { 924 for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end(); 925 MBBI != MBBE;) { 926 // Use the first debug instruction in the sequence to get a SlotIndex 927 // for following consecutive debug instructions. 928 if (!MBBI->isDebugOrPseudoInstr()) { 929 ++MBBI; 930 continue; 931 } 932 // Debug instructions has no slot index. Use the previous 933 // non-debug instruction's SlotIndex as its SlotIndex. 934 SlotIndex Idx = 935 MBBI == MBB.begin() 936 ? LIS->getMBBStartIdx(&MBB) 937 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot(); 938 // Handle consecutive debug instructions with the same slot index. 939 do { 940 // In instruction referencing mode, pass each instr to handleDebugInstr 941 // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and 942 // need to go through the normal live interval splitting process. 943 if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() || 944 MBBI->isDebugRef())) { 945 MBBI = handleDebugInstr(*MBBI, Idx); 946 Changed = true; 947 // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler 948 // to track things through register allocation, and erase the instr. 949 } else if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) || 950 (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) { 951 MBBI = MBB.erase(MBBI); 952 Changed = true; 953 } else 954 ++MBBI; 955 } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr()); 956 } 957 } 958 return Changed; 959 } 960 961 void UserValue::extendDef( 962 SlotIndex Idx, DbgVariableValue DbgValue, 963 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> 964 &LiveIntervalInfo, 965 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills, 966 LiveIntervals &LIS) { 967 SlotIndex Start = Idx; 968 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start); 969 SlotIndex Stop = LIS.getMBBEndIdx(MBB); 970 LocMap::iterator I = locInts.find(Start); 971 972 // Limit to the intersection of the VNIs' live ranges. 973 for (auto &LII : LiveIntervalInfo) { 974 LiveRange *LR = LII.second.first; 975 assert(LR && LII.second.second && "Missing range info for Idx."); 976 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start); 977 assert(Segment && Segment->valno == LII.second.second && 978 "Invalid VNInfo for Idx given?"); 979 if (Segment->end < Stop) { 980 Stop = Segment->end; 981 Kills = {Stop, {LII.first}}; 982 } else if (Segment->end == Stop && Kills) { 983 // If multiple locations end at the same place, track all of them in 984 // Kills. 985 Kills->second.push_back(LII.first); 986 } 987 } 988 989 // There could already be a short def at Start. 990 if (I.valid() && I.start() <= Start) { 991 // Stop when meeting a different location or an already extended interval. 992 Start = Start.getNextSlot(); 993 if (I.value() != DbgValue || I.stop() != Start) { 994 // Clear `Kills`, as we have a new def available. 995 Kills = std::nullopt; 996 return; 997 } 998 // This is a one-slot placeholder. Just skip it. 999 ++I; 1000 } 1001 1002 // Limited by the next def. 1003 if (I.valid() && I.start() < Stop) { 1004 Stop = I.start(); 1005 // Clear `Kills`, as we have a new def available. 1006 Kills = std::nullopt; 1007 } 1008 1009 if (Start < Stop) { 1010 DbgVariableValue ExtDbgValue(DbgValue); 1011 I.insert(Start, Stop, std::move(ExtDbgValue)); 1012 } 1013 } 1014 1015 void UserValue::addDefsFromCopies( 1016 DbgVariableValue DbgValue, 1017 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals, 1018 SlotIndex KilledAt, 1019 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs, 1020 MachineRegisterInfo &MRI, LiveIntervals &LIS) { 1021 // Don't track copies from physregs, there are too many uses. 1022 if (any_of(LocIntervals, [](auto LocI) { 1023 return !Register::isVirtualRegister(LocI.second->reg()); 1024 })) 1025 return; 1026 1027 // Collect all the (vreg, valno) pairs that are copies of LI. 1028 SmallDenseMap<unsigned, 1029 SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>> 1030 CopyValues; 1031 for (auto &LocInterval : LocIntervals) { 1032 unsigned LocNo = LocInterval.first; 1033 LiveInterval *LI = LocInterval.second; 1034 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) { 1035 MachineInstr *MI = MO.getParent(); 1036 // Copies of the full value. 1037 if (MO.getSubReg() || !MI->isCopy()) 1038 continue; 1039 Register DstReg = MI->getOperand(0).getReg(); 1040 1041 // Don't follow copies to physregs. These are usually setting up call 1042 // arguments, and the argument registers are always call clobbered. We are 1043 // better off in the source register which could be a callee-saved 1044 // register, or it could be spilled. 1045 if (!Register::isVirtualRegister(DstReg)) 1046 continue; 1047 1048 // Is the value extended to reach this copy? If not, another def may be 1049 // blocking it, or we are looking at a wrong value of LI. 1050 SlotIndex Idx = LIS.getInstructionIndex(*MI); 1051 LocMap::iterator I = locInts.find(Idx.getRegSlot(true)); 1052 if (!I.valid() || I.value() != DbgValue) 1053 continue; 1054 1055 if (!LIS.hasInterval(DstReg)) 1056 continue; 1057 LiveInterval *DstLI = &LIS.getInterval(DstReg); 1058 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot()); 1059 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value"); 1060 CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI)); 1061 } 1062 } 1063 1064 if (CopyValues.empty()) 1065 return; 1066 1067 #if !defined(NDEBUG) 1068 for (auto &LocInterval : LocIntervals) 1069 LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size() 1070 << " copies of " << *LocInterval.second << '\n'); 1071 #endif 1072 1073 // Try to add defs of the copied values for the kill point. Check that there 1074 // isn't already a def at Idx. 1075 LocMap::iterator I = locInts.find(KilledAt); 1076 if (I.valid() && I.start() <= KilledAt) 1077 return; 1078 DbgVariableValue NewValue(DbgValue); 1079 for (auto &LocInterval : LocIntervals) { 1080 unsigned LocNo = LocInterval.first; 1081 bool FoundCopy = false; 1082 for (auto &LIAndVNI : CopyValues[LocNo]) { 1083 LiveInterval *DstLI = LIAndVNI.first; 1084 const VNInfo *DstVNI = LIAndVNI.second; 1085 if (DstLI->getVNInfoAt(KilledAt) != DstVNI) 1086 continue; 1087 LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #" 1088 << DstVNI->id << " in " << *DstLI << '\n'); 1089 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def); 1090 assert(CopyMI && CopyMI->isCopy() && "Bad copy value"); 1091 unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0)); 1092 NewValue = NewValue.changeLocNo(LocNo, NewLocNo); 1093 FoundCopy = true; 1094 break; 1095 } 1096 // If there are any killed locations we can't find a copy for, we can't 1097 // extend the variable value. 1098 if (!FoundCopy) 1099 return; 1100 } 1101 I.insert(KilledAt, KilledAt.getNextSlot(), NewValue); 1102 NewDefs.push_back(std::make_pair(KilledAt, NewValue)); 1103 } 1104 1105 void UserValue::computeIntervals(MachineRegisterInfo &MRI, 1106 const TargetRegisterInfo &TRI, 1107 LiveIntervals &LIS, LexicalScopes &LS) { 1108 SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs; 1109 1110 // Collect all defs to be extended (Skipping undefs). 1111 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) 1112 if (!I.value().isUndef()) 1113 Defs.push_back(std::make_pair(I.start(), I.value())); 1114 1115 // Extend all defs, and possibly add new ones along the way. 1116 for (unsigned i = 0; i != Defs.size(); ++i) { 1117 SlotIndex Idx = Defs[i].first; 1118 DbgVariableValue DbgValue = Defs[i].second; 1119 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs; 1120 SmallVector<const VNInfo *, 4> VNIs; 1121 bool ShouldExtendDef = false; 1122 for (unsigned LocNo : DbgValue.loc_nos()) { 1123 const MachineOperand &LocMO = locations[LocNo]; 1124 if (!LocMO.isReg() || !Register::isVirtualRegister(LocMO.getReg())) { 1125 ShouldExtendDef |= !LocMO.isReg(); 1126 continue; 1127 } 1128 ShouldExtendDef = true; 1129 LiveInterval *LI = nullptr; 1130 const VNInfo *VNI = nullptr; 1131 if (LIS.hasInterval(LocMO.getReg())) { 1132 LI = &LIS.getInterval(LocMO.getReg()); 1133 VNI = LI->getVNInfoAt(Idx); 1134 } 1135 if (LI && VNI) 1136 LIs[LocNo] = {LI, VNI}; 1137 } 1138 if (ShouldExtendDef) { 1139 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills; 1140 extendDef(Idx, DbgValue, LIs, Kills, LIS); 1141 1142 if (Kills) { 1143 SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals; 1144 bool AnySubreg = false; 1145 for (unsigned LocNo : Kills->second) { 1146 const MachineOperand &LocMO = this->locations[LocNo]; 1147 if (LocMO.getSubReg()) { 1148 AnySubreg = true; 1149 break; 1150 } 1151 LiveInterval *LI = &LIS.getInterval(LocMO.getReg()); 1152 KilledLocIntervals.push_back({LocNo, LI}); 1153 } 1154 1155 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that 1156 // if the original location for example is %vreg0:sub_hi, and we find a 1157 // full register copy in addDefsFromCopies (at the moment it only 1158 // handles full register copies), then we must add the sub1 sub-register 1159 // index to the new location. However, that is only possible if the new 1160 // virtual register is of the same regclass (or if there is an 1161 // equivalent sub-register in that regclass). For now, simply skip 1162 // handling copies if a sub-register is involved. 1163 if (!AnySubreg) 1164 addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs, 1165 MRI, LIS); 1166 } 1167 } 1168 1169 // For physregs, we only mark the start slot idx. DwarfDebug will see it 1170 // as if the DBG_VALUE is valid up until the end of the basic block, or 1171 // the next def of the physical register. So we do not need to extend the 1172 // range. It might actually happen that the DBG_VALUE is the last use of 1173 // the physical register (e.g. if this is an unused input argument to a 1174 // function). 1175 } 1176 1177 // The computed intervals may extend beyond the range of the debug 1178 // location's lexical scope. In this case, splitting of an interval 1179 // can result in an interval outside of the scope being created, 1180 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent 1181 // this, trim the intervals to the lexical scope in the case of inlined 1182 // variables, since heavy inlining may cause production of dramatically big 1183 // number of DBG_VALUEs to be generated. 1184 if (!dl.getInlinedAt()) 1185 return; 1186 1187 LexicalScope *Scope = LS.findLexicalScope(dl); 1188 if (!Scope) 1189 return; 1190 1191 SlotIndex PrevEnd; 1192 LocMap::iterator I = locInts.begin(); 1193 1194 // Iterate over the lexical scope ranges. Each time round the loop 1195 // we check the intervals for overlap with the end of the previous 1196 // range and the start of the next. The first range is handled as 1197 // a special case where there is no PrevEnd. 1198 for (const InsnRange &Range : Scope->getRanges()) { 1199 SlotIndex RStart = LIS.getInstructionIndex(*Range.first); 1200 SlotIndex REnd = LIS.getInstructionIndex(*Range.second); 1201 1202 // Variable locations at the first instruction of a block should be 1203 // based on the block's SlotIndex, not the first instruction's index. 1204 if (Range.first == Range.first->getParent()->begin()) 1205 RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first); 1206 1207 // At the start of each iteration I has been advanced so that 1208 // I.stop() >= PrevEnd. Check for overlap. 1209 if (PrevEnd && I.start() < PrevEnd) { 1210 SlotIndex IStop = I.stop(); 1211 DbgVariableValue DbgValue = I.value(); 1212 1213 // Stop overlaps previous end - trim the end of the interval to 1214 // the scope range. 1215 I.setStopUnchecked(PrevEnd); 1216 ++I; 1217 1218 // If the interval also overlaps the start of the "next" (i.e. 1219 // current) range create a new interval for the remainder (which 1220 // may be further trimmed). 1221 if (RStart < IStop) 1222 I.insert(RStart, IStop, DbgValue); 1223 } 1224 1225 // Advance I so that I.stop() >= RStart, and check for overlap. 1226 I.advanceTo(RStart); 1227 if (!I.valid()) 1228 return; 1229 1230 if (I.start() < RStart) { 1231 // Interval start overlaps range - trim to the scope range. 1232 I.setStartUnchecked(RStart); 1233 // Remember that this interval was trimmed. 1234 trimmedDefs.insert(RStart); 1235 } 1236 1237 // The end of a lexical scope range is the last instruction in the 1238 // range. To convert to an interval we need the index of the 1239 // instruction after it. 1240 REnd = REnd.getNextIndex(); 1241 1242 // Advance I to first interval outside current range. 1243 I.advanceTo(REnd); 1244 if (!I.valid()) 1245 return; 1246 1247 PrevEnd = REnd; 1248 } 1249 1250 // Check for overlap with end of final range. 1251 if (PrevEnd && I.start() < PrevEnd) 1252 I.setStopUnchecked(PrevEnd); 1253 } 1254 1255 void LDVImpl::computeIntervals() { 1256 LexicalScopes LS; 1257 LS.initialize(*MF); 1258 1259 for (unsigned i = 0, e = userValues.size(); i != e; ++i) { 1260 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS); 1261 userValues[i]->mapVirtRegs(this); 1262 } 1263 } 1264 1265 bool LDVImpl::runOnMachineFunction(MachineFunction &mf, bool InstrRef) { 1266 clear(); 1267 MF = &mf; 1268 LIS = &pass.getAnalysis<LiveIntervals>(); 1269 TRI = mf.getSubtarget().getRegisterInfo(); 1270 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: " 1271 << mf.getName() << " **********\n"); 1272 1273 bool Changed = collectDebugValues(mf, InstrRef); 1274 computeIntervals(); 1275 LLVM_DEBUG(print(dbgs())); 1276 1277 // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive 1278 // VRegs too, for when we're notified of a range split. 1279 SlotIndexes *Slots = LIS->getSlotIndexes(); 1280 for (const auto &PHIIt : MF->DebugPHIPositions) { 1281 const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second; 1282 MachineBasicBlock *MBB = Position.MBB; 1283 Register Reg = Position.Reg; 1284 unsigned SubReg = Position.SubReg; 1285 SlotIndex SI = Slots->getMBBStartIdx(MBB); 1286 PHIValPos VP = {SI, Reg, SubReg}; 1287 PHIValToPos.insert(std::make_pair(PHIIt.first, VP)); 1288 RegToPHIIdx[Reg].push_back(PHIIt.first); 1289 } 1290 1291 ModifiedMF = Changed; 1292 return Changed; 1293 } 1294 1295 static void removeDebugInstrs(MachineFunction &mf) { 1296 for (MachineBasicBlock &MBB : mf) { 1297 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) 1298 if (MI.isDebugInstr()) 1299 MBB.erase(&MI); 1300 } 1301 } 1302 1303 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) { 1304 if (!EnableLDV) 1305 return false; 1306 if (!mf.getFunction().getSubprogram()) { 1307 removeDebugInstrs(mf); 1308 return false; 1309 } 1310 1311 // Have we been asked to track variable locations using instruction 1312 // referencing? 1313 bool InstrRef = mf.useDebugInstrRef(); 1314 1315 if (!pImpl) 1316 pImpl = new LDVImpl(this); 1317 return static_cast<LDVImpl *>(pImpl)->runOnMachineFunction(mf, InstrRef); 1318 } 1319 1320 void LiveDebugVariables::releaseMemory() { 1321 if (pImpl) 1322 static_cast<LDVImpl*>(pImpl)->clear(); 1323 } 1324 1325 LiveDebugVariables::~LiveDebugVariables() { 1326 if (pImpl) 1327 delete static_cast<LDVImpl*>(pImpl); 1328 } 1329 1330 //===----------------------------------------------------------------------===// 1331 // Live Range Splitting 1332 //===----------------------------------------------------------------------===// 1333 1334 bool 1335 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs, 1336 LiveIntervals& LIS) { 1337 LLVM_DEBUG({ 1338 dbgs() << "Splitting Loc" << OldLocNo << '\t'; 1339 print(dbgs(), nullptr); 1340 }); 1341 bool DidChange = false; 1342 LocMap::iterator LocMapI; 1343 LocMapI.setMap(locInts); 1344 for (Register NewReg : NewRegs) { 1345 LiveInterval *LI = &LIS.getInterval(NewReg); 1346 if (LI->empty()) 1347 continue; 1348 1349 // Don't allocate the new LocNo until it is needed. 1350 unsigned NewLocNo = UndefLocNo; 1351 1352 // Iterate over the overlaps between locInts and LI. 1353 LocMapI.find(LI->beginIndex()); 1354 if (!LocMapI.valid()) 1355 continue; 1356 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start()); 1357 LiveInterval::iterator LIE = LI->end(); 1358 while (LocMapI.valid() && LII != LIE) { 1359 // At this point, we know that LocMapI.stop() > LII->start. 1360 LII = LI->advanceTo(LII, LocMapI.start()); 1361 if (LII == LIE) 1362 break; 1363 1364 // Now LII->end > LocMapI.start(). Do we have an overlap? 1365 if (LocMapI.value().containsLocNo(OldLocNo) && 1366 LII->start < LocMapI.stop()) { 1367 // Overlapping correct location. Allocate NewLocNo now. 1368 if (NewLocNo == UndefLocNo) { 1369 MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false); 1370 MO.setSubReg(locations[OldLocNo].getSubReg()); 1371 NewLocNo = getLocationNo(MO); 1372 DidChange = true; 1373 } 1374 1375 SlotIndex LStart = LocMapI.start(); 1376 SlotIndex LStop = LocMapI.stop(); 1377 DbgVariableValue OldDbgValue = LocMapI.value(); 1378 1379 // Trim LocMapI down to the LII overlap. 1380 if (LStart < LII->start) 1381 LocMapI.setStartUnchecked(LII->start); 1382 if (LStop > LII->end) 1383 LocMapI.setStopUnchecked(LII->end); 1384 1385 // Change the value in the overlap. This may trigger coalescing. 1386 LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo)); 1387 1388 // Re-insert any removed OldDbgValue ranges. 1389 if (LStart < LocMapI.start()) { 1390 LocMapI.insert(LStart, LocMapI.start(), OldDbgValue); 1391 ++LocMapI; 1392 assert(LocMapI.valid() && "Unexpected coalescing"); 1393 } 1394 if (LStop > LocMapI.stop()) { 1395 ++LocMapI; 1396 LocMapI.insert(LII->end, LStop, OldDbgValue); 1397 --LocMapI; 1398 } 1399 } 1400 1401 // Advance to the next overlap. 1402 if (LII->end < LocMapI.stop()) { 1403 if (++LII == LIE) 1404 break; 1405 LocMapI.advanceTo(LII->start); 1406 } else { 1407 ++LocMapI; 1408 if (!LocMapI.valid()) 1409 break; 1410 LII = LI->advanceTo(LII, LocMapI.start()); 1411 } 1412 } 1413 } 1414 1415 // Finally, remove OldLocNo unless it is still used by some interval in the 1416 // locInts map. One case when OldLocNo still is in use is when the register 1417 // has been spilled. In such situations the spilled register is kept as a 1418 // location until rewriteLocations is called (VirtRegMap is mapping the old 1419 // register to the spill slot). So for a while we can have locations that map 1420 // to virtual registers that have been removed from both the MachineFunction 1421 // and from LiveIntervals. 1422 // 1423 // We may also just be using the location for a value with a different 1424 // expression. 1425 removeLocationIfUnused(OldLocNo); 1426 1427 LLVM_DEBUG({ 1428 dbgs() << "Split result: \t"; 1429 print(dbgs(), nullptr); 1430 }); 1431 return DidChange; 1432 } 1433 1434 bool 1435 UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs, 1436 LiveIntervals &LIS) { 1437 bool DidChange = false; 1438 // Split locations referring to OldReg. Iterate backwards so splitLocation can 1439 // safely erase unused locations. 1440 for (unsigned i = locations.size(); i ; --i) { 1441 unsigned LocNo = i-1; 1442 const MachineOperand *Loc = &locations[LocNo]; 1443 if (!Loc->isReg() || Loc->getReg() != OldReg) 1444 continue; 1445 DidChange |= splitLocation(LocNo, NewRegs, LIS); 1446 } 1447 return DidChange; 1448 } 1449 1450 void LDVImpl::splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs) { 1451 auto RegIt = RegToPHIIdx.find(OldReg); 1452 if (RegIt == RegToPHIIdx.end()) 1453 return; 1454 1455 std::vector<std::pair<Register, unsigned>> NewRegIdxes; 1456 // Iterate over all the debug instruction numbers affected by this split. 1457 for (unsigned InstrID : RegIt->second) { 1458 auto PHIIt = PHIValToPos.find(InstrID); 1459 assert(PHIIt != PHIValToPos.end()); 1460 const SlotIndex &Slot = PHIIt->second.SI; 1461 assert(OldReg == PHIIt->second.Reg); 1462 1463 // Find the new register that covers this position. 1464 for (auto NewReg : NewRegs) { 1465 const LiveInterval &LI = LIS->getInterval(NewReg); 1466 auto LII = LI.find(Slot); 1467 if (LII != LI.end() && LII->start <= Slot) { 1468 // This new register covers this PHI position, record this for indexing. 1469 NewRegIdxes.push_back(std::make_pair(NewReg, InstrID)); 1470 // Record that this value lives in a different VReg now. 1471 PHIIt->second.Reg = NewReg; 1472 break; 1473 } 1474 } 1475 1476 // If we do not find a new register covering this PHI, then register 1477 // allocation has dropped its location, for example because it's not live. 1478 // The old VReg will not be mapped to a physreg, and the instruction 1479 // number will have been optimized out. 1480 } 1481 1482 // Re-create register index using the new register numbers. 1483 RegToPHIIdx.erase(RegIt); 1484 for (auto &RegAndInstr : NewRegIdxes) 1485 RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second); 1486 } 1487 1488 void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) { 1489 // Consider whether this split range affects any PHI locations. 1490 splitPHIRegister(OldReg, NewRegs); 1491 1492 // Check whether any intervals mapped by a DBG_VALUE were split and need 1493 // updating. 1494 bool DidChange = false; 1495 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext()) 1496 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS); 1497 1498 if (!DidChange) 1499 return; 1500 1501 // Map all of the new virtual registers. 1502 UserValue *UV = lookupVirtReg(OldReg); 1503 for (Register NewReg : NewRegs) 1504 mapVirtReg(NewReg, UV); 1505 } 1506 1507 void LiveDebugVariables:: 1508 splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) { 1509 if (pImpl) 1510 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs); 1511 } 1512 1513 void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF, 1514 const TargetInstrInfo &TII, 1515 const TargetRegisterInfo &TRI, 1516 SpillOffsetMap &SpillOffsets) { 1517 // Build a set of new locations with new numbers so we can coalesce our 1518 // IntervalMap if two vreg intervals collapse to the same physical location. 1519 // Use MapVector instead of SetVector because MapVector::insert returns the 1520 // position of the previously or newly inserted element. The boolean value 1521 // tracks if the location was produced by a spill. 1522 // FIXME: This will be problematic if we ever support direct and indirect 1523 // frame index locations, i.e. expressing both variables in memory and 1524 // 'int x, *px = &x'. The "spilled" bit must become part of the location. 1525 MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations; 1526 SmallVector<unsigned, 4> LocNoMap(locations.size()); 1527 for (unsigned I = 0, E = locations.size(); I != E; ++I) { 1528 bool Spilled = false; 1529 unsigned SpillOffset = 0; 1530 MachineOperand Loc = locations[I]; 1531 // Only virtual registers are rewritten. 1532 if (Loc.isReg() && Loc.getReg() && 1533 Register::isVirtualRegister(Loc.getReg())) { 1534 Register VirtReg = Loc.getReg(); 1535 if (VRM.isAssignedReg(VirtReg) && 1536 Register::isPhysicalRegister(VRM.getPhys(VirtReg))) { 1537 // This can create a %noreg operand in rare cases when the sub-register 1538 // index is no longer available. That means the user value is in a 1539 // non-existent sub-register, and %noreg is exactly what we want. 1540 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI); 1541 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) { 1542 // Retrieve the stack slot offset. 1543 unsigned SpillSize; 1544 const MachineRegisterInfo &MRI = MF.getRegInfo(); 1545 const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg); 1546 bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize, 1547 SpillOffset, MF); 1548 1549 // FIXME: Invalidate the location if the offset couldn't be calculated. 1550 (void)Success; 1551 1552 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg)); 1553 Spilled = true; 1554 } else { 1555 Loc.setReg(0); 1556 Loc.setSubReg(0); 1557 } 1558 } 1559 1560 // Insert this location if it doesn't already exist and record a mapping 1561 // from the old number to the new number. 1562 auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}}); 1563 unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first); 1564 LocNoMap[I] = NewLocNo; 1565 } 1566 1567 // Rewrite the locations and record the stack slot offsets for spills. 1568 locations.clear(); 1569 SpillOffsets.clear(); 1570 for (auto &Pair : NewLocations) { 1571 bool Spilled; 1572 unsigned SpillOffset; 1573 std::tie(Spilled, SpillOffset) = Pair.second; 1574 locations.push_back(Pair.first); 1575 if (Spilled) { 1576 unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair); 1577 SpillOffsets[NewLocNo] = SpillOffset; 1578 } 1579 } 1580 1581 // Update the interval map, but only coalesce left, since intervals to the 1582 // right use the old location numbers. This should merge two contiguous 1583 // DBG_VALUE intervals with different vregs that were allocated to the same 1584 // physical register. 1585 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) { 1586 I.setValueUnchecked(I.value().remapLocNos(LocNoMap)); 1587 I.setStart(I.start()); 1588 } 1589 } 1590 1591 /// Find an iterator for inserting a DBG_VALUE instruction. 1592 static MachineBasicBlock::iterator 1593 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS, 1594 BlockSkipInstsMap &BBSkipInstsMap) { 1595 SlotIndex Start = LIS.getMBBStartIdx(MBB); 1596 Idx = Idx.getBaseIndex(); 1597 1598 // Try to find an insert location by going backwards from Idx. 1599 MachineInstr *MI; 1600 while (!(MI = LIS.getInstructionFromIndex(Idx))) { 1601 // We've reached the beginning of MBB. 1602 if (Idx == Start) { 1603 // Retrieve the last PHI/Label/Debug location found when calling 1604 // SkipPHIsLabelsAndDebug last time. Start searching from there. 1605 // 1606 // Note the iterator kept in BBSkipInstsMap is one step back based 1607 // on the iterator returned by SkipPHIsLabelsAndDebug last time. 1608 // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(), 1609 // BBSkipInstsMap won't save it. This is to consider the case that 1610 // new instructions may be inserted at the beginning of MBB after 1611 // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in 1612 // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions 1613 // are inserted at the beginning of the MBB, the iterator in 1614 // BBSkipInstsMap won't point to the beginning of the MBB anymore. 1615 // Therefore The next search in SkipPHIsLabelsAndDebug will skip those 1616 // newly added instructions and that is unwanted. 1617 MachineBasicBlock::iterator BeginIt; 1618 auto MapIt = BBSkipInstsMap.find(MBB); 1619 if (MapIt == BBSkipInstsMap.end()) 1620 BeginIt = MBB->begin(); 1621 else 1622 BeginIt = std::next(MapIt->second); 1623 auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt); 1624 if (I != BeginIt) 1625 BBSkipInstsMap[MBB] = std::prev(I); 1626 return I; 1627 } 1628 Idx = Idx.getPrevIndex(); 1629 } 1630 1631 // Don't insert anything after the first terminator, though. 1632 return MI->isTerminator() ? MBB->getFirstTerminator() : 1633 std::next(MachineBasicBlock::iterator(MI)); 1634 } 1635 1636 /// Find an iterator for inserting the next DBG_VALUE instruction 1637 /// (or end if no more insert locations found). 1638 static MachineBasicBlock::iterator 1639 findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I, 1640 SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs, 1641 LiveIntervals &LIS, const TargetRegisterInfo &TRI) { 1642 SmallVector<Register, 4> Regs; 1643 for (const MachineOperand &LocMO : LocMOs) 1644 if (LocMO.isReg()) 1645 Regs.push_back(LocMO.getReg()); 1646 if (Regs.empty()) 1647 return MBB->instr_end(); 1648 1649 // Find the next instruction in the MBB that define the register Reg. 1650 while (I != MBB->end() && !I->isTerminator()) { 1651 if (!LIS.isNotInMIMap(*I) && 1652 SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I))) 1653 break; 1654 if (any_of(Regs, [&I, &TRI](Register &Reg) { 1655 return I->definesRegister(Reg, &TRI); 1656 })) 1657 // The insert location is directly after the instruction/bundle. 1658 return std::next(I); 1659 ++I; 1660 } 1661 return MBB->end(); 1662 } 1663 1664 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx, 1665 SlotIndex StopIdx, DbgVariableValue DbgValue, 1666 ArrayRef<bool> LocSpills, 1667 ArrayRef<unsigned> SpillOffsets, 1668 LiveIntervals &LIS, const TargetInstrInfo &TII, 1669 const TargetRegisterInfo &TRI, 1670 BlockSkipInstsMap &BBSkipInstsMap) { 1671 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB); 1672 // Only search within the current MBB. 1673 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx; 1674 MachineBasicBlock::iterator I = 1675 findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap); 1676 // Undef values don't exist in locations so create new "noreg" register MOs 1677 // for them. See getLocationNo(). 1678 SmallVector<MachineOperand, 8> MOs; 1679 if (DbgValue.isUndef()) { 1680 MOs.assign(DbgValue.loc_nos().size(), 1681 MachineOperand::CreateReg( 1682 /* Reg */ 0, /* isDef */ false, /* isImp */ false, 1683 /* isKill */ false, /* isDead */ false, 1684 /* isUndef */ false, /* isEarlyClobber */ false, 1685 /* SubReg */ 0, /* isDebug */ true)); 1686 } else { 1687 for (unsigned LocNo : DbgValue.loc_nos()) 1688 MOs.push_back(locations[LocNo]); 1689 } 1690 1691 ++NumInsertedDebugValues; 1692 1693 assert(cast<DILocalVariable>(Variable) 1694 ->isValidLocationForIntrinsic(getDebugLoc()) && 1695 "Expected inlined-at fields to agree"); 1696 1697 // If the location was spilled, the new DBG_VALUE will be indirect. If the 1698 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate 1699 // that the original virtual register was a pointer. Also, add the stack slot 1700 // offset for the spilled register to the expression. 1701 const DIExpression *Expr = DbgValue.getExpression(); 1702 bool IsIndirect = DbgValue.getWasIndirect(); 1703 bool IsList = DbgValue.getWasList(); 1704 for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) { 1705 if (LocSpills[I]) { 1706 if (!IsList) { 1707 uint8_t DIExprFlags = DIExpression::ApplyOffset; 1708 if (IsIndirect) 1709 DIExprFlags |= DIExpression::DerefAfter; 1710 Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]); 1711 IsIndirect = true; 1712 } else { 1713 SmallVector<uint64_t, 4> Ops; 1714 DIExpression::appendOffset(Ops, SpillOffsets[I]); 1715 Ops.push_back(dwarf::DW_OP_deref); 1716 Expr = DIExpression::appendOpsToArg(Expr, Ops, I); 1717 } 1718 } 1719 1720 assert((!LocSpills[I] || MOs[I].isFI()) && 1721 "a spilled location must be a frame index"); 1722 } 1723 1724 unsigned DbgValueOpcode = 1725 IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE; 1726 do { 1727 BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs, 1728 Variable, Expr); 1729 1730 // Continue and insert DBG_VALUES after every redefinition of a register 1731 // associated with the debug value within the range 1732 I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI); 1733 } while (I != MBB->end()); 1734 } 1735 1736 void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx, 1737 LiveIntervals &LIS, const TargetInstrInfo &TII, 1738 BlockSkipInstsMap &BBSkipInstsMap) { 1739 MachineBasicBlock::iterator I = 1740 findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap); 1741 ++NumInsertedDebugLabels; 1742 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL)) 1743 .addMetadata(Label); 1744 } 1745 1746 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 1747 const TargetInstrInfo &TII, 1748 const TargetRegisterInfo &TRI, 1749 const SpillOffsetMap &SpillOffsets, 1750 BlockSkipInstsMap &BBSkipInstsMap) { 1751 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end(); 1752 1753 for (LocMap::const_iterator I = locInts.begin(); I.valid();) { 1754 SlotIndex Start = I.start(); 1755 SlotIndex Stop = I.stop(); 1756 DbgVariableValue DbgValue = I.value(); 1757 1758 SmallVector<bool> SpilledLocs; 1759 SmallVector<unsigned> LocSpillOffsets; 1760 for (unsigned LocNo : DbgValue.loc_nos()) { 1761 auto SpillIt = 1762 !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end(); 1763 bool Spilled = SpillIt != SpillOffsets.end(); 1764 SpilledLocs.push_back(Spilled); 1765 LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0); 1766 } 1767 1768 // If the interval start was trimmed to the lexical scope insert the 1769 // DBG_VALUE at the previous index (otherwise it appears after the 1770 // first instruction in the range). 1771 if (trimmedDefs.count(Start)) 1772 Start = Start.getPrevIndex(); 1773 1774 LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):"; 1775 DbgValue.printLocNos(dbg)); 1776 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); 1777 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB); 1778 1779 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd); 1780 insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets, 1781 LIS, TII, TRI, BBSkipInstsMap); 1782 // This interval may span multiple basic blocks. 1783 // Insert a DBG_VALUE into each one. 1784 while (Stop > MBBEnd) { 1785 // Move to the next block. 1786 Start = MBBEnd; 1787 if (++MBB == MFEnd) 1788 break; 1789 MBBEnd = LIS.getMBBEndIdx(&*MBB); 1790 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd); 1791 insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, 1792 LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap); 1793 } 1794 LLVM_DEBUG(dbgs() << '\n'); 1795 if (MBB == MFEnd) 1796 break; 1797 1798 ++I; 1799 } 1800 } 1801 1802 void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII, 1803 BlockSkipInstsMap &BBSkipInstsMap) { 1804 LLVM_DEBUG(dbgs() << "\t" << loc); 1805 MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator(); 1806 1807 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB)); 1808 insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap); 1809 1810 LLVM_DEBUG(dbgs() << '\n'); 1811 } 1812 1813 void LDVImpl::emitDebugValues(VirtRegMap *VRM) { 1814 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n"); 1815 if (!MF) 1816 return; 1817 1818 BlockSkipInstsMap BBSkipInstsMap; 1819 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1820 SpillOffsetMap SpillOffsets; 1821 for (auto &userValue : userValues) { 1822 LLVM_DEBUG(userValue->print(dbgs(), TRI)); 1823 userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets); 1824 userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets, 1825 BBSkipInstsMap); 1826 } 1827 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n"); 1828 for (auto &userLabel : userLabels) { 1829 LLVM_DEBUG(userLabel->print(dbgs(), TRI)); 1830 userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap); 1831 } 1832 1833 LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n"); 1834 1835 auto Slots = LIS->getSlotIndexes(); 1836 for (auto &It : PHIValToPos) { 1837 // For each ex-PHI, identify its physreg location or stack slot, and emit 1838 // a DBG_PHI for it. 1839 unsigned InstNum = It.first; 1840 auto Slot = It.second.SI; 1841 Register Reg = It.second.Reg; 1842 unsigned SubReg = It.second.SubReg; 1843 1844 MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot); 1845 if (VRM->isAssignedReg(Reg) && 1846 Register::isPhysicalRegister(VRM->getPhys(Reg))) { 1847 unsigned PhysReg = VRM->getPhys(Reg); 1848 if (SubReg != 0) 1849 PhysReg = TRI->getSubReg(PhysReg, SubReg); 1850 1851 auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(), 1852 TII->get(TargetOpcode::DBG_PHI)); 1853 Builder.addReg(PhysReg); 1854 Builder.addImm(InstNum); 1855 } else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) { 1856 const MachineRegisterInfo &MRI = MF->getRegInfo(); 1857 const TargetRegisterClass *TRC = MRI.getRegClass(Reg); 1858 unsigned SpillSize, SpillOffset; 1859 1860 unsigned regSizeInBits = TRI->getRegSizeInBits(*TRC); 1861 if (SubReg) 1862 regSizeInBits = TRI->getSubRegIdxSize(SubReg); 1863 1864 // Test whether this location is legal with the given subreg. If the 1865 // subregister has a nonzero offset, drop this location, it's too complex 1866 // to describe. (TODO: future work). 1867 bool Success = 1868 TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF); 1869 1870 if (Success && SpillOffset == 0) { 1871 auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(), 1872 TII->get(TargetOpcode::DBG_PHI)); 1873 Builder.addFrameIndex(VRM->getStackSlot(Reg)); 1874 Builder.addImm(InstNum); 1875 // Record how large the original value is. The stack slot might be 1876 // merged and altered during optimisation, but we will want to know how 1877 // large the value is, at this DBG_PHI. 1878 Builder.addImm(regSizeInBits); 1879 } 1880 1881 LLVM_DEBUG( 1882 if (SpillOffset != 0) { 1883 dbgs() << "DBG_PHI for Vreg " << Reg << " subreg " << SubReg << 1884 " has nonzero offset\n"; 1885 } 1886 ); 1887 } 1888 // If there was no mapping for a value ID, it's optimized out. Create no 1889 // DBG_PHI, and any variables using this value will become optimized out. 1890 } 1891 MF->DebugPHIPositions.clear(); 1892 1893 LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n"); 1894 1895 // Re-insert any debug instrs back in the position they were. We must 1896 // re-insert in the same order to ensure that debug instructions don't swap, 1897 // which could re-order assignments. Do so in a batch -- once we find the 1898 // insert position, insert all instructions at the same SlotIdx. They are 1899 // guaranteed to appear in-sequence in StashedDebugInstrs because we insert 1900 // them in order. 1901 for (auto *StashIt = StashedDebugInstrs.begin(); 1902 StashIt != StashedDebugInstrs.end(); ++StashIt) { 1903 SlotIndex Idx = StashIt->Idx; 1904 MachineBasicBlock *MBB = StashIt->MBB; 1905 MachineInstr *MI = StashIt->MI; 1906 1907 auto EmitInstsHere = [this, &StashIt, MBB, Idx, 1908 MI](MachineBasicBlock::iterator InsertPos) { 1909 // Insert this debug instruction. 1910 MBB->insert(InsertPos, MI); 1911 1912 // Look at subsequent stashed debug instructions: if they're at the same 1913 // index, insert those too. 1914 auto NextItem = std::next(StashIt); 1915 while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) { 1916 assert(NextItem->MBB == MBB && "Instrs with same slot index should be" 1917 "in the same block"); 1918 MBB->insert(InsertPos, NextItem->MI); 1919 StashIt = NextItem; 1920 NextItem = std::next(StashIt); 1921 }; 1922 }; 1923 1924 // Start block index: find the first non-debug instr in the block, and 1925 // insert before it. 1926 if (Idx == Slots->getMBBStartIdx(MBB)) { 1927 MachineBasicBlock::iterator InsertPos = 1928 findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap); 1929 EmitInstsHere(InsertPos); 1930 continue; 1931 } 1932 1933 if (MachineInstr *Pos = Slots->getInstructionFromIndex(Idx)) { 1934 // Insert at the end of any debug instructions. 1935 auto PostDebug = std::next(Pos->getIterator()); 1936 PostDebug = skipDebugInstructionsForward(PostDebug, MBB->instr_end()); 1937 EmitInstsHere(PostDebug); 1938 } else { 1939 // Insert position disappeared; walk forwards through slots until we 1940 // find a new one. 1941 SlotIndex End = Slots->getMBBEndIdx(MBB); 1942 for (; Idx < End; Idx = Slots->getNextNonNullIndex(Idx)) { 1943 Pos = Slots->getInstructionFromIndex(Idx); 1944 if (Pos) { 1945 EmitInstsHere(Pos->getIterator()); 1946 break; 1947 } 1948 } 1949 1950 // We have reached the end of the block and didn't find anywhere to 1951 // insert! It's not safe to discard any debug instructions; place them 1952 // in front of the first terminator, or in front of end(). 1953 if (Idx >= End) { 1954 auto TermIt = MBB->getFirstTerminator(); 1955 EmitInstsHere(TermIt); 1956 } 1957 } 1958 } 1959 1960 EmitDone = true; 1961 BBSkipInstsMap.clear(); 1962 } 1963 1964 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) { 1965 if (pImpl) 1966 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM); 1967 } 1968 1969 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1970 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const { 1971 if (pImpl) 1972 static_cast<LDVImpl*>(pImpl)->print(dbgs()); 1973 } 1974 #endif 1975