1 //===- VarLocBasedImpl.cpp - Tracking Debug Value MIs with VarLoc class----===// 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 /// \file VarLocBasedImpl.cpp 10 /// 11 /// LiveDebugValues is an optimistic "available expressions" dataflow 12 /// algorithm. The set of expressions is the set of machine locations 13 /// (registers, spill slots, constants) that a variable fragment might be 14 /// located, qualified by a DIExpression and indirect-ness flag, while each 15 /// variable is identified by a DebugVariable object. The availability of an 16 /// expression begins when a DBG_VALUE instruction specifies the location of a 17 /// DebugVariable, and continues until that location is clobbered or 18 /// re-specified by a different DBG_VALUE for the same DebugVariable. 19 /// 20 /// The output of LiveDebugValues is additional DBG_VALUE instructions, 21 /// placed to extend variable locations as far they're available. This file 22 /// and the VarLocBasedLDV class is an implementation that explicitly tracks 23 /// locations, using the VarLoc class. 24 /// 25 /// The canonical "available expressions" problem doesn't have expression 26 /// clobbering, instead when a variable is re-assigned, any expressions using 27 /// that variable get invalidated. LiveDebugValues can map onto "available 28 /// expressions" by having every register represented by a variable, which is 29 /// used in an expression that becomes available at a DBG_VALUE instruction. 30 /// When the register is clobbered, its variable is effectively reassigned, and 31 /// expressions computed from it become unavailable. A similar construct is 32 /// needed when a DebugVariable has its location re-specified, to invalidate 33 /// all other locations for that DebugVariable. 34 /// 35 /// Using the dataflow analysis to compute the available expressions, we create 36 /// a DBG_VALUE at the beginning of each block where the expression is 37 /// live-in. This propagates variable locations into every basic block where 38 /// the location can be determined, rather than only having DBG_VALUEs in blocks 39 /// where locations are specified due to an assignment or some optimization. 40 /// Movements of values between registers and spill slots are annotated with 41 /// DBG_VALUEs too to track variable values bewteen locations. All this allows 42 /// DbgEntityHistoryCalculator to focus on only the locations within individual 43 /// blocks, facilitating testing and improving modularity. 44 /// 45 /// We follow an optimisic dataflow approach, with this lattice: 46 /// 47 /// \verbatim 48 /// ┬ "Unknown" 49 /// | 50 /// v 51 /// True 52 /// | 53 /// v 54 /// ⊥ False 55 /// \endverbatim With "True" signifying that the expression is available (and 56 /// thus a DebugVariable's location is the corresponding register), while 57 /// "False" signifies that the expression is unavailable. "Unknown"s never 58 /// survive to the end of the analysis (see below). 59 /// 60 /// Formally, all DebugVariable locations that are live-out of a block are 61 /// initialized to \top. A blocks live-in values take the meet of the lattice 62 /// value for every predecessors live-outs, except for the entry block, where 63 /// all live-ins are \bot. The usual dataflow propagation occurs: the transfer 64 /// function for a block assigns an expression for a DebugVariable to be "True" 65 /// if a DBG_VALUE in the block specifies it; "False" if the location is 66 /// clobbered; or the live-in value if it is unaffected by the block. We 67 /// visit each block in reverse post order until a fixedpoint is reached. The 68 /// solution produced is maximal. 69 /// 70 /// Intuitively, we start by assuming that every expression / variable location 71 /// is at least "True", and then propagate "False" from the entry block and any 72 /// clobbers until there are no more changes to make. This gives us an accurate 73 /// solution because all incorrect locations will have a "False" propagated into 74 /// them. It also gives us a solution that copes well with loops by assuming 75 /// that variable locations are live-through every loop, and then removing those 76 /// that are not through dataflow. 77 /// 78 /// Within LiveDebugValues: each variable location is represented by a 79 /// VarLoc object that identifies the source variable, its current 80 /// machine-location, and the DBG_VALUE inst that specifies the location. Each 81 /// VarLoc is indexed in the (function-scope) \p VarLocMap, giving each VarLoc a 82 /// unique index. Rather than operate directly on machine locations, the 83 /// dataflow analysis in this pass identifies locations by their index in the 84 /// VarLocMap, meaning all the variable locations in a block can be described 85 /// by a sparse vector of VarLocMap indicies. 86 /// 87 /// All the storage for the dataflow analysis is local to the ExtendRanges 88 /// method and passed down to helper methods. "OutLocs" and "InLocs" record the 89 /// in and out lattice values for each block. "OpenRanges" maintains a list of 90 /// variable locations and, with the "process" method, evaluates the transfer 91 /// function of each block. "flushPendingLocs" installs DBG_VALUEs for each 92 /// live-in location at the start of blocks, while "Transfers" records 93 /// transfers of values between machine-locations. 94 /// 95 /// We avoid explicitly representing the "Unknown" (\top) lattice value in the 96 /// implementation. Instead, unvisited blocks implicitly have all lattice 97 /// values set as "Unknown". After being visited, there will be path back to 98 /// the entry block where the lattice value is "False", and as the transfer 99 /// function cannot make new "Unknown" locations, there are no scenarios where 100 /// a block can have an "Unknown" location after being visited. Similarly, we 101 /// don't enumerate all possible variable locations before exploring the 102 /// function: when a new location is discovered, all blocks previously explored 103 /// were implicitly "False" but unrecorded, and become explicitly "False" when 104 /// a new VarLoc is created with its bit not set in predecessor InLocs or 105 /// OutLocs. 106 /// 107 //===----------------------------------------------------------------------===// 108 109 #include "LiveDebugValues.h" 110 111 #include "llvm/ADT/CoalescingBitVector.h" 112 #include "llvm/ADT/DenseMap.h" 113 #include "llvm/ADT/PostOrderIterator.h" 114 #include "llvm/ADT/SmallPtrSet.h" 115 #include "llvm/ADT/SmallSet.h" 116 #include "llvm/ADT/SmallVector.h" 117 #include "llvm/ADT/Statistic.h" 118 #include "llvm/ADT/UniqueVector.h" 119 #include "llvm/CodeGen/LexicalScopes.h" 120 #include "llvm/CodeGen/MachineBasicBlock.h" 121 #include "llvm/CodeGen/MachineFrameInfo.h" 122 #include "llvm/CodeGen/MachineFunction.h" 123 #include "llvm/CodeGen/MachineFunctionPass.h" 124 #include "llvm/CodeGen/MachineInstr.h" 125 #include "llvm/CodeGen/MachineInstrBuilder.h" 126 #include "llvm/CodeGen/MachineMemOperand.h" 127 #include "llvm/CodeGen/MachineOperand.h" 128 #include "llvm/CodeGen/PseudoSourceValue.h" 129 #include "llvm/CodeGen/RegisterScavenging.h" 130 #include "llvm/CodeGen/TargetFrameLowering.h" 131 #include "llvm/CodeGen/TargetInstrInfo.h" 132 #include "llvm/CodeGen/TargetLowering.h" 133 #include "llvm/CodeGen/TargetPassConfig.h" 134 #include "llvm/CodeGen/TargetRegisterInfo.h" 135 #include "llvm/CodeGen/TargetSubtargetInfo.h" 136 #include "llvm/Config/llvm-config.h" 137 #include "llvm/IR/DIBuilder.h" 138 #include "llvm/IR/DebugInfoMetadata.h" 139 #include "llvm/IR/DebugLoc.h" 140 #include "llvm/IR/Function.h" 141 #include "llvm/IR/Module.h" 142 #include "llvm/InitializePasses.h" 143 #include "llvm/MC/MCRegisterInfo.h" 144 #include "llvm/Pass.h" 145 #include "llvm/Support/Casting.h" 146 #include "llvm/Support/Compiler.h" 147 #include "llvm/Support/Debug.h" 148 #include "llvm/Support/raw_ostream.h" 149 #include "llvm/Target/TargetMachine.h" 150 #include <algorithm> 151 #include <cassert> 152 #include <cstdint> 153 #include <functional> 154 #include <queue> 155 #include <tuple> 156 #include <utility> 157 #include <vector> 158 159 using namespace llvm; 160 161 #define DEBUG_TYPE "livedebugvalues" 162 163 STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted"); 164 165 // Options to prevent pathological compile-time behavior. If InputBBLimit and 166 // InputDbgValueLimit are both exceeded, range extension is disabled. 167 static cl::opt<unsigned> InputBBLimit( 168 "livedebugvalues-input-bb-limit", 169 cl::desc("Maximum input basic blocks before DBG_VALUE limit applies"), 170 cl::init(10000), cl::Hidden); 171 static cl::opt<unsigned> InputDbgValueLimit( 172 "livedebugvalues-input-dbg-value-limit", 173 cl::desc( 174 "Maximum input DBG_VALUE insts supported by debug range extension"), 175 cl::init(50000), cl::Hidden); 176 177 // If @MI is a DBG_VALUE with debug value described by a defined 178 // register, returns the number of this register. In the other case, returns 0. 179 static Register isDbgValueDescribedByReg(const MachineInstr &MI) { 180 assert(MI.isDebugValue() && "expected a DBG_VALUE"); 181 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE"); 182 // If location of variable is described using a register (directly 183 // or indirectly), this register is always a first operand. 184 return MI.getDebugOperand(0).isReg() ? MI.getDebugOperand(0).getReg() 185 : Register(); 186 } 187 188 /// If \p Op is a stack or frame register return true, otherwise return false. 189 /// This is used to avoid basing the debug entry values on the registers, since 190 /// we do not support it at the moment. 191 static bool isRegOtherThanSPAndFP(const MachineOperand &Op, 192 const MachineInstr &MI, 193 const TargetRegisterInfo *TRI) { 194 if (!Op.isReg()) 195 return false; 196 197 const MachineFunction *MF = MI.getParent()->getParent(); 198 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 199 Register SP = TLI->getStackPointerRegisterToSaveRestore(); 200 Register FP = TRI->getFrameRegister(*MF); 201 Register Reg = Op.getReg(); 202 203 return Reg && Reg != SP && Reg != FP; 204 } 205 206 namespace { 207 208 // Max out the number of statically allocated elements in DefinedRegsSet, as 209 // this prevents fallback to std::set::count() operations. 210 using DefinedRegsSet = SmallSet<Register, 32>; 211 212 using VarLocSet = CoalescingBitVector<uint64_t>; 213 214 /// A type-checked pair of {Register Location (or 0), Index}, used to index 215 /// into a \ref VarLocMap. This can be efficiently converted to a 64-bit int 216 /// for insertion into a \ref VarLocSet, and efficiently converted back. The 217 /// type-checker helps ensure that the conversions aren't lossy. 218 /// 219 /// Why encode a location /into/ the VarLocMap index? This makes it possible 220 /// to find the open VarLocs killed by a register def very quickly. This is a 221 /// performance-critical operation for LiveDebugValues. 222 struct LocIndex { 223 using u32_location_t = uint32_t; 224 using u32_index_t = uint32_t; 225 226 u32_location_t Location; // Physical registers live in the range [1;2^30) (see 227 // \ref MCRegister), so we have plenty of range left 228 // here to encode non-register locations. 229 u32_index_t Index; 230 231 /// The first location greater than 0 that is not reserved for VarLocs of 232 /// kind RegisterKind. 233 static constexpr u32_location_t kFirstInvalidRegLocation = 1 << 30; 234 235 /// A special location reserved for VarLocs of kind SpillLocKind. 236 static constexpr u32_location_t kSpillLocation = kFirstInvalidRegLocation; 237 238 /// A special location reserved for VarLocs of kind EntryValueBackupKind and 239 /// EntryValueCopyBackupKind. 240 static constexpr u32_location_t kEntryValueBackupLocation = 241 kFirstInvalidRegLocation + 1; 242 243 LocIndex(u32_location_t Location, u32_index_t Index) 244 : Location(Location), Index(Index) {} 245 246 uint64_t getAsRawInteger() const { 247 return (static_cast<uint64_t>(Location) << 32) | Index; 248 } 249 250 template<typename IntT> static LocIndex fromRawInteger(IntT ID) { 251 static_assert(std::is_unsigned<IntT>::value && 252 sizeof(ID) == sizeof(uint64_t), 253 "Cannot convert raw integer to LocIndex"); 254 return {static_cast<u32_location_t>(ID >> 32), 255 static_cast<u32_index_t>(ID)}; 256 } 257 258 /// Get the start of the interval reserved for VarLocs of kind RegisterKind 259 /// which reside in \p Reg. The end is at rawIndexForReg(Reg+1)-1. 260 static uint64_t rawIndexForReg(uint32_t Reg) { 261 return LocIndex(Reg, 0).getAsRawInteger(); 262 } 263 264 /// Return a range covering all set indices in the interval reserved for 265 /// \p Location in \p Set. 266 static auto indexRangeForLocation(const VarLocSet &Set, 267 u32_location_t Location) { 268 uint64_t Start = LocIndex(Location, 0).getAsRawInteger(); 269 uint64_t End = LocIndex(Location + 1, 0).getAsRawInteger(); 270 return Set.half_open_range(Start, End); 271 } 272 }; 273 274 class VarLocBasedLDV : public LDVImpl { 275 private: 276 const TargetRegisterInfo *TRI; 277 const TargetInstrInfo *TII; 278 const TargetFrameLowering *TFI; 279 TargetPassConfig *TPC; 280 BitVector CalleeSavedRegs; 281 LexicalScopes LS; 282 VarLocSet::Allocator Alloc; 283 284 enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore }; 285 286 using FragmentInfo = DIExpression::FragmentInfo; 287 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>; 288 289 /// A pair of debug variable and value location. 290 struct VarLoc { 291 // The location at which a spilled variable resides. It consists of a 292 // register and an offset. 293 struct SpillLoc { 294 unsigned SpillBase; 295 int SpillOffset; 296 bool operator==(const SpillLoc &Other) const { 297 return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset; 298 } 299 bool operator!=(const SpillLoc &Other) const { 300 return !(*this == Other); 301 } 302 }; 303 304 /// Identity of the variable at this location. 305 const DebugVariable Var; 306 307 /// The expression applied to this location. 308 const DIExpression *Expr; 309 310 /// DBG_VALUE to clone var/expr information from if this location 311 /// is moved. 312 const MachineInstr &MI; 313 314 enum VarLocKind { 315 InvalidKind = 0, 316 RegisterKind, 317 SpillLocKind, 318 ImmediateKind, 319 EntryValueKind, 320 EntryValueBackupKind, 321 EntryValueCopyBackupKind 322 } Kind = InvalidKind; 323 324 /// The value location. Stored separately to avoid repeatedly 325 /// extracting it from MI. 326 union { 327 uint64_t RegNo; 328 SpillLoc SpillLocation; 329 uint64_t Hash; 330 int64_t Immediate; 331 const ConstantFP *FPImm; 332 const ConstantInt *CImm; 333 } Loc; 334 335 VarLoc(const MachineInstr &MI, LexicalScopes &LS) 336 : Var(MI.getDebugVariable(), MI.getDebugExpression(), 337 MI.getDebugLoc()->getInlinedAt()), 338 Expr(MI.getDebugExpression()), MI(MI) { 339 static_assert((sizeof(Loc) == sizeof(uint64_t)), 340 "hash does not cover all members of Loc"); 341 assert(MI.isDebugValue() && "not a DBG_VALUE"); 342 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE"); 343 if (int RegNo = isDbgValueDescribedByReg(MI)) { 344 Kind = RegisterKind; 345 Loc.RegNo = RegNo; 346 } else if (MI.getDebugOperand(0).isImm()) { 347 Kind = ImmediateKind; 348 Loc.Immediate = MI.getDebugOperand(0).getImm(); 349 } else if (MI.getDebugOperand(0).isFPImm()) { 350 Kind = ImmediateKind; 351 Loc.FPImm = MI.getDebugOperand(0).getFPImm(); 352 } else if (MI.getDebugOperand(0).isCImm()) { 353 Kind = ImmediateKind; 354 Loc.CImm = MI.getDebugOperand(0).getCImm(); 355 } 356 357 // We create the debug entry values from the factory functions rather than 358 // from this ctor. 359 assert(Kind != EntryValueKind && !isEntryBackupLoc()); 360 } 361 362 /// Take the variable and machine-location in DBG_VALUE MI, and build an 363 /// entry location using the given expression. 364 static VarLoc CreateEntryLoc(const MachineInstr &MI, LexicalScopes &LS, 365 const DIExpression *EntryExpr, Register Reg) { 366 VarLoc VL(MI, LS); 367 assert(VL.Kind == RegisterKind); 368 VL.Kind = EntryValueKind; 369 VL.Expr = EntryExpr; 370 VL.Loc.RegNo = Reg; 371 return VL; 372 } 373 374 /// Take the variable and machine-location from the DBG_VALUE (from the 375 /// function entry), and build an entry value backup location. The backup 376 /// location will turn into the normal location if the backup is valid at 377 /// the time of the primary location clobbering. 378 static VarLoc CreateEntryBackupLoc(const MachineInstr &MI, 379 LexicalScopes &LS, 380 const DIExpression *EntryExpr) { 381 VarLoc VL(MI, LS); 382 assert(VL.Kind == RegisterKind); 383 VL.Kind = EntryValueBackupKind; 384 VL.Expr = EntryExpr; 385 return VL; 386 } 387 388 /// Take the variable and machine-location from the DBG_VALUE (from the 389 /// function entry), and build a copy of an entry value backup location by 390 /// setting the register location to NewReg. 391 static VarLoc CreateEntryCopyBackupLoc(const MachineInstr &MI, 392 LexicalScopes &LS, 393 const DIExpression *EntryExpr, 394 Register NewReg) { 395 VarLoc VL(MI, LS); 396 assert(VL.Kind == RegisterKind); 397 VL.Kind = EntryValueCopyBackupKind; 398 VL.Expr = EntryExpr; 399 VL.Loc.RegNo = NewReg; 400 return VL; 401 } 402 403 /// Copy the register location in DBG_VALUE MI, updating the register to 404 /// be NewReg. 405 static VarLoc CreateCopyLoc(const MachineInstr &MI, LexicalScopes &LS, 406 Register NewReg) { 407 VarLoc VL(MI, LS); 408 assert(VL.Kind == RegisterKind); 409 VL.Loc.RegNo = NewReg; 410 return VL; 411 } 412 413 /// Take the variable described by DBG_VALUE MI, and create a VarLoc 414 /// locating it in the specified spill location. 415 static VarLoc CreateSpillLoc(const MachineInstr &MI, unsigned SpillBase, 416 int SpillOffset, LexicalScopes &LS) { 417 VarLoc VL(MI, LS); 418 assert(VL.Kind == RegisterKind); 419 VL.Kind = SpillLocKind; 420 VL.Loc.SpillLocation = {SpillBase, SpillOffset}; 421 return VL; 422 } 423 424 /// Create a DBG_VALUE representing this VarLoc in the given function. 425 /// Copies variable-specific information such as DILocalVariable and 426 /// inlining information from the original DBG_VALUE instruction, which may 427 /// have been several transfers ago. 428 MachineInstr *BuildDbgValue(MachineFunction &MF) const { 429 const DebugLoc &DbgLoc = MI.getDebugLoc(); 430 bool Indirect = MI.isIndirectDebugValue(); 431 const auto &IID = MI.getDesc(); 432 const DILocalVariable *Var = MI.getDebugVariable(); 433 const DIExpression *DIExpr = MI.getDebugExpression(); 434 NumInserted++; 435 436 switch (Kind) { 437 case EntryValueKind: 438 // An entry value is a register location -- but with an updated 439 // expression. The register location of such DBG_VALUE is always the one 440 // from the entry DBG_VALUE, it does not matter if the entry value was 441 // copied in to another register due to some optimizations. 442 return BuildMI(MF, DbgLoc, IID, Indirect, 443 MI.getDebugOperand(0).getReg(), Var, Expr); 444 case RegisterKind: 445 // Register locations are like the source DBG_VALUE, but with the 446 // register number from this VarLoc. 447 return BuildMI(MF, DbgLoc, IID, Indirect, Loc.RegNo, Var, DIExpr); 448 case SpillLocKind: { 449 // Spills are indirect DBG_VALUEs, with a base register and offset. 450 // Use the original DBG_VALUEs expression to build the spilt location 451 // on top of. FIXME: spill locations created before this pass runs 452 // are not recognized, and not handled here. 453 auto *SpillExpr = DIExpression::prepend( 454 DIExpr, DIExpression::ApplyOffset, Loc.SpillLocation.SpillOffset); 455 unsigned Base = Loc.SpillLocation.SpillBase; 456 return BuildMI(MF, DbgLoc, IID, true, Base, Var, SpillExpr); 457 } 458 case ImmediateKind: { 459 MachineOperand MO = MI.getDebugOperand(0); 460 return BuildMI(MF, DbgLoc, IID, Indirect, MO, Var, DIExpr); 461 } 462 case EntryValueBackupKind: 463 case EntryValueCopyBackupKind: 464 case InvalidKind: 465 llvm_unreachable( 466 "Tried to produce DBG_VALUE for invalid or backup VarLoc"); 467 } 468 llvm_unreachable("Unrecognized VarLocBasedLDV.VarLoc.Kind enum"); 469 } 470 471 /// Is the Loc field a constant or constant object? 472 bool isConstant() const { return Kind == ImmediateKind; } 473 474 /// Check if the Loc field is an entry backup location. 475 bool isEntryBackupLoc() const { 476 return Kind == EntryValueBackupKind || Kind == EntryValueCopyBackupKind; 477 } 478 479 /// If this variable is described by a register holding the entry value, 480 /// return it, otherwise return 0. 481 unsigned getEntryValueBackupReg() const { 482 if (Kind == EntryValueBackupKind) 483 return Loc.RegNo; 484 return 0; 485 } 486 487 /// If this variable is described by a register holding the copy of the 488 /// entry value, return it, otherwise return 0. 489 unsigned getEntryValueCopyBackupReg() const { 490 if (Kind == EntryValueCopyBackupKind) 491 return Loc.RegNo; 492 return 0; 493 } 494 495 /// If this variable is described by a register, return it, 496 /// otherwise return 0. 497 unsigned isDescribedByReg() const { 498 if (Kind == RegisterKind) 499 return Loc.RegNo; 500 return 0; 501 } 502 503 /// Determine whether the lexical scope of this value's debug location 504 /// dominates MBB. 505 bool dominates(LexicalScopes &LS, MachineBasicBlock &MBB) const { 506 return LS.dominates(MI.getDebugLoc().get(), &MBB); 507 } 508 509 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 510 // TRI can be null. 511 void dump(const TargetRegisterInfo *TRI, raw_ostream &Out = dbgs()) const { 512 Out << "VarLoc("; 513 switch (Kind) { 514 case RegisterKind: 515 case EntryValueKind: 516 case EntryValueBackupKind: 517 case EntryValueCopyBackupKind: 518 Out << printReg(Loc.RegNo, TRI); 519 break; 520 case SpillLocKind: 521 Out << printReg(Loc.SpillLocation.SpillBase, TRI); 522 Out << "[" << Loc.SpillLocation.SpillOffset << "]"; 523 break; 524 case ImmediateKind: 525 Out << Loc.Immediate; 526 break; 527 case InvalidKind: 528 llvm_unreachable("Invalid VarLoc in dump method"); 529 } 530 531 Out << ", \"" << Var.getVariable()->getName() << "\", " << *Expr << ", "; 532 if (Var.getInlinedAt()) 533 Out << "!" << Var.getInlinedAt()->getMetadataID() << ")\n"; 534 else 535 Out << "(null))"; 536 537 if (isEntryBackupLoc()) 538 Out << " (backup loc)\n"; 539 else 540 Out << "\n"; 541 } 542 #endif 543 544 bool operator==(const VarLoc &Other) const { 545 return Kind == Other.Kind && Var == Other.Var && 546 Loc.Hash == Other.Loc.Hash && Expr == Other.Expr; 547 } 548 549 /// This operator guarantees that VarLocs are sorted by Variable first. 550 bool operator<(const VarLoc &Other) const { 551 return std::tie(Var, Kind, Loc.Hash, Expr) < 552 std::tie(Other.Var, Other.Kind, Other.Loc.Hash, Other.Expr); 553 } 554 }; 555 556 /// VarLocMap is used for two things: 557 /// 1) Assigning a unique LocIndex to a VarLoc. This LocIndex can be used to 558 /// virtually insert a VarLoc into a VarLocSet. 559 /// 2) Given a LocIndex, look up the unique associated VarLoc. 560 class VarLocMap { 561 /// Map a VarLoc to an index within the vector reserved for its location 562 /// within Loc2Vars. 563 std::map<VarLoc, LocIndex::u32_index_t> Var2Index; 564 565 /// Map a location to a vector which holds VarLocs which live in that 566 /// location. 567 SmallDenseMap<LocIndex::u32_location_t, std::vector<VarLoc>> Loc2Vars; 568 569 /// Determine the 32-bit location reserved for \p VL, based on its kind. 570 static LocIndex::u32_location_t getLocationForVar(const VarLoc &VL) { 571 switch (VL.Kind) { 572 case VarLoc::RegisterKind: 573 assert((VL.Loc.RegNo < LocIndex::kFirstInvalidRegLocation) && 574 "Physreg out of range?"); 575 return VL.Loc.RegNo; 576 case VarLoc::SpillLocKind: 577 return LocIndex::kSpillLocation; 578 case VarLoc::EntryValueBackupKind: 579 case VarLoc::EntryValueCopyBackupKind: 580 return LocIndex::kEntryValueBackupLocation; 581 default: 582 return 0; 583 } 584 } 585 586 public: 587 /// Retrieve a unique LocIndex for \p VL. 588 LocIndex insert(const VarLoc &VL) { 589 LocIndex::u32_location_t Location = getLocationForVar(VL); 590 LocIndex::u32_index_t &Index = Var2Index[VL]; 591 if (!Index) { 592 auto &Vars = Loc2Vars[Location]; 593 Vars.push_back(VL); 594 Index = Vars.size(); 595 } 596 return {Location, Index - 1}; 597 } 598 599 /// Retrieve the unique VarLoc associated with \p ID. 600 const VarLoc &operator[](LocIndex ID) const { 601 auto LocIt = Loc2Vars.find(ID.Location); 602 assert(LocIt != Loc2Vars.end() && "Location not tracked"); 603 return LocIt->second[ID.Index]; 604 } 605 }; 606 607 using VarLocInMBB = 608 SmallDenseMap<const MachineBasicBlock *, std::unique_ptr<VarLocSet>>; 609 struct TransferDebugPair { 610 MachineInstr *TransferInst; ///< Instruction where this transfer occurs. 611 LocIndex LocationID; ///< Location number for the transfer dest. 612 }; 613 using TransferMap = SmallVector<TransferDebugPair, 4>; 614 615 // Types for recording sets of variable fragments that overlap. For a given 616 // local variable, we record all other fragments of that variable that could 617 // overlap it, to reduce search time. 618 using FragmentOfVar = 619 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>; 620 using OverlapMap = 621 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>; 622 623 // Helper while building OverlapMap, a map of all fragments seen for a given 624 // DILocalVariable. 625 using VarToFragments = 626 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>; 627 628 /// This holds the working set of currently open ranges. For fast 629 /// access, this is done both as a set of VarLocIDs, and a map of 630 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all 631 /// previous open ranges for the same variable. In addition, we keep 632 /// two different maps (Vars/EntryValuesBackupVars), so erase/insert 633 /// methods act differently depending on whether a VarLoc is primary 634 /// location or backup one. In the case the VarLoc is backup location 635 /// we will erase/insert from the EntryValuesBackupVars map, otherwise 636 /// we perform the operation on the Vars. 637 class OpenRangesSet { 638 VarLocSet VarLocs; 639 // Map the DebugVariable to recent primary location ID. 640 SmallDenseMap<DebugVariable, LocIndex, 8> Vars; 641 // Map the DebugVariable to recent backup location ID. 642 SmallDenseMap<DebugVariable, LocIndex, 8> EntryValuesBackupVars; 643 OverlapMap &OverlappingFragments; 644 645 public: 646 OpenRangesSet(VarLocSet::Allocator &Alloc, OverlapMap &_OLapMap) 647 : VarLocs(Alloc), OverlappingFragments(_OLapMap) {} 648 649 const VarLocSet &getVarLocs() const { return VarLocs; } 650 651 /// Terminate all open ranges for VL.Var by removing it from the set. 652 void erase(const VarLoc &VL); 653 654 /// Terminate all open ranges listed in \c KillSet by removing 655 /// them from the set. 656 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs); 657 658 /// Insert a new range into the set. 659 void insert(LocIndex VarLocID, const VarLoc &VL); 660 661 /// Insert a set of ranges. 662 void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map) { 663 for (uint64_t ID : ToLoad) { 664 LocIndex Idx = LocIndex::fromRawInteger(ID); 665 const VarLoc &VarL = Map[Idx]; 666 insert(Idx, VarL); 667 } 668 } 669 670 llvm::Optional<LocIndex> getEntryValueBackup(DebugVariable Var); 671 672 /// Empty the set. 673 void clear() { 674 VarLocs.clear(); 675 Vars.clear(); 676 EntryValuesBackupVars.clear(); 677 } 678 679 /// Return whether the set is empty or not. 680 bool empty() const { 681 assert(Vars.empty() == EntryValuesBackupVars.empty() && 682 Vars.empty() == VarLocs.empty() && 683 "open ranges are inconsistent"); 684 return VarLocs.empty(); 685 } 686 687 /// Get an empty range of VarLoc IDs. 688 auto getEmptyVarLocRange() const { 689 return iterator_range<VarLocSet::const_iterator>(getVarLocs().end(), 690 getVarLocs().end()); 691 } 692 693 /// Get all set IDs for VarLocs of kind RegisterKind in \p Reg. 694 auto getRegisterVarLocs(Register Reg) const { 695 return LocIndex::indexRangeForLocation(getVarLocs(), Reg); 696 } 697 698 /// Get all set IDs for VarLocs of kind SpillLocKind. 699 auto getSpillVarLocs() const { 700 return LocIndex::indexRangeForLocation(getVarLocs(), 701 LocIndex::kSpillLocation); 702 } 703 704 /// Get all set IDs for VarLocs of kind EntryValueBackupKind or 705 /// EntryValueCopyBackupKind. 706 auto getEntryValueBackupVarLocs() const { 707 return LocIndex::indexRangeForLocation( 708 getVarLocs(), LocIndex::kEntryValueBackupLocation); 709 } 710 }; 711 712 /// Collect all VarLoc IDs from \p CollectFrom for VarLocs of kind 713 /// RegisterKind which are located in any reg in \p Regs. Insert collected IDs 714 /// into \p Collected. 715 void collectIDsForRegs(VarLocSet &Collected, const DefinedRegsSet &Regs, 716 const VarLocSet &CollectFrom) const; 717 718 /// Get the registers which are used by VarLocs of kind RegisterKind tracked 719 /// by \p CollectFrom. 720 void getUsedRegs(const VarLocSet &CollectFrom, 721 SmallVectorImpl<uint32_t> &UsedRegs) const; 722 723 VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB, VarLocInMBB &Locs) { 724 std::unique_ptr<VarLocSet> &VLS = Locs[MBB]; 725 if (!VLS) 726 VLS = std::make_unique<VarLocSet>(Alloc); 727 return *VLS.get(); 728 } 729 730 const VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB, 731 const VarLocInMBB &Locs) const { 732 auto It = Locs.find(MBB); 733 assert(It != Locs.end() && "MBB not in map"); 734 return *It->second.get(); 735 } 736 737 /// Tests whether this instruction is a spill to a stack location. 738 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF); 739 740 /// Decide if @MI is a spill instruction and return true if it is. We use 2 741 /// criteria to make this decision: 742 /// - Is this instruction a store to a spill slot? 743 /// - Is there a register operand that is both used and killed? 744 /// TODO: Store optimization can fold spills into other stores (including 745 /// other spills). We do not handle this yet (more than one memory operand). 746 bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF, 747 Register &Reg); 748 749 /// Returns true if the given machine instruction is a debug value which we 750 /// can emit entry values for. 751 /// 752 /// Currently, we generate debug entry values only for parameters that are 753 /// unmodified throughout the function and located in a register. 754 bool isEntryValueCandidate(const MachineInstr &MI, 755 const DefinedRegsSet &Regs) const; 756 757 /// If a given instruction is identified as a spill, return the spill location 758 /// and set \p Reg to the spilled register. 759 Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI, 760 MachineFunction *MF, 761 Register &Reg); 762 /// Given a spill instruction, extract the register and offset used to 763 /// address the spill location in a target independent way. 764 VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI); 765 void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges, 766 TransferMap &Transfers, VarLocMap &VarLocIDs, 767 LocIndex OldVarID, TransferKind Kind, 768 Register NewReg = Register()); 769 770 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges, 771 VarLocMap &VarLocIDs); 772 void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges, 773 VarLocMap &VarLocIDs, TransferMap &Transfers); 774 bool removeEntryValue(const MachineInstr &MI, OpenRangesSet &OpenRanges, 775 VarLocMap &VarLocIDs, const VarLoc &EntryVL); 776 void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges, 777 VarLocMap &VarLocIDs, TransferMap &Transfers, 778 VarLocSet &KillSet); 779 void recordEntryValue(const MachineInstr &MI, 780 const DefinedRegsSet &DefinedRegs, 781 OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs); 782 void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges, 783 VarLocMap &VarLocIDs, TransferMap &Transfers); 784 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges, 785 VarLocMap &VarLocIDs, TransferMap &Transfers); 786 bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges, 787 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs); 788 789 void process(MachineInstr &MI, OpenRangesSet &OpenRanges, 790 VarLocMap &VarLocIDs, TransferMap &Transfers); 791 792 void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments, 793 OverlapMap &OLapMap); 794 795 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs, 796 const VarLocMap &VarLocIDs, 797 SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 798 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks); 799 800 /// Create DBG_VALUE insts for inlocs that have been propagated but 801 /// had their instruction creation deferred. 802 void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs); 803 804 bool ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) override; 805 806 public: 807 /// Default construct and initialize the pass. 808 VarLocBasedLDV(); 809 810 ~VarLocBasedLDV(); 811 812 /// Print to ostream with a message. 813 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V, 814 const VarLocMap &VarLocIDs, const char *msg, 815 raw_ostream &Out) const; 816 }; 817 818 } // end anonymous namespace 819 820 //===----------------------------------------------------------------------===// 821 // Implementation 822 //===----------------------------------------------------------------------===// 823 824 VarLocBasedLDV::VarLocBasedLDV() { } 825 826 VarLocBasedLDV::~VarLocBasedLDV() { } 827 828 /// Erase a variable from the set of open ranges, and additionally erase any 829 /// fragments that may overlap it. If the VarLoc is a backup location, erase 830 /// the variable from the EntryValuesBackupVars set, indicating we should stop 831 /// tracking its backup entry location. Otherwise, if the VarLoc is primary 832 /// location, erase the variable from the Vars set. 833 void VarLocBasedLDV::OpenRangesSet::erase(const VarLoc &VL) { 834 // Erasure helper. 835 auto DoErase = [VL, this](DebugVariable VarToErase) { 836 auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars; 837 auto It = EraseFrom->find(VarToErase); 838 if (It != EraseFrom->end()) { 839 LocIndex ID = It->second; 840 VarLocs.reset(ID.getAsRawInteger()); 841 EraseFrom->erase(It); 842 } 843 }; 844 845 DebugVariable Var = VL.Var; 846 847 // Erase the variable/fragment that ends here. 848 DoErase(Var); 849 850 // Extract the fragment. Interpret an empty fragment as one that covers all 851 // possible bits. 852 FragmentInfo ThisFragment = Var.getFragmentOrDefault(); 853 854 // There may be fragments that overlap the designated fragment. Look them up 855 // in the pre-computed overlap map, and erase them too. 856 auto MapIt = OverlappingFragments.find({Var.getVariable(), ThisFragment}); 857 if (MapIt != OverlappingFragments.end()) { 858 for (auto Fragment : MapIt->second) { 859 VarLocBasedLDV::OptFragmentInfo FragmentHolder; 860 if (!DebugVariable::isDefaultFragment(Fragment)) 861 FragmentHolder = VarLocBasedLDV::OptFragmentInfo(Fragment); 862 DoErase({Var.getVariable(), FragmentHolder, Var.getInlinedAt()}); 863 } 864 } 865 } 866 867 void VarLocBasedLDV::OpenRangesSet::erase(const VarLocSet &KillSet, 868 const VarLocMap &VarLocIDs) { 869 VarLocs.intersectWithComplement(KillSet); 870 for (uint64_t ID : KillSet) { 871 const VarLoc *VL = &VarLocIDs[LocIndex::fromRawInteger(ID)]; 872 auto *EraseFrom = VL->isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars; 873 EraseFrom->erase(VL->Var); 874 } 875 } 876 877 void VarLocBasedLDV::OpenRangesSet::insert(LocIndex VarLocID, 878 const VarLoc &VL) { 879 auto *InsertInto = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars; 880 VarLocs.set(VarLocID.getAsRawInteger()); 881 InsertInto->insert({VL.Var, VarLocID}); 882 } 883 884 /// Return the Loc ID of an entry value backup location, if it exists for the 885 /// variable. 886 llvm::Optional<LocIndex> 887 VarLocBasedLDV::OpenRangesSet::getEntryValueBackup(DebugVariable Var) { 888 auto It = EntryValuesBackupVars.find(Var); 889 if (It != EntryValuesBackupVars.end()) 890 return It->second; 891 892 return llvm::None; 893 } 894 895 void VarLocBasedLDV::collectIDsForRegs(VarLocSet &Collected, 896 const DefinedRegsSet &Regs, 897 const VarLocSet &CollectFrom) const { 898 assert(!Regs.empty() && "Nothing to collect"); 899 SmallVector<uint32_t, 32> SortedRegs; 900 for (Register Reg : Regs) 901 SortedRegs.push_back(Reg); 902 array_pod_sort(SortedRegs.begin(), SortedRegs.end()); 903 auto It = CollectFrom.find(LocIndex::rawIndexForReg(SortedRegs.front())); 904 auto End = CollectFrom.end(); 905 for (uint32_t Reg : SortedRegs) { 906 // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains all 907 // possible VarLoc IDs for VarLocs of kind RegisterKind which live in Reg. 908 uint64_t FirstIndexForReg = LocIndex::rawIndexForReg(Reg); 909 uint64_t FirstInvalidIndex = LocIndex::rawIndexForReg(Reg + 1); 910 It.advanceToLowerBound(FirstIndexForReg); 911 912 // Iterate through that half-open interval and collect all the set IDs. 913 for (; It != End && *It < FirstInvalidIndex; ++It) 914 Collected.set(*It); 915 916 if (It == End) 917 return; 918 } 919 } 920 921 void VarLocBasedLDV::getUsedRegs(const VarLocSet &CollectFrom, 922 SmallVectorImpl<uint32_t> &UsedRegs) const { 923 // All register-based VarLocs are assigned indices greater than or equal to 924 // FirstRegIndex. 925 uint64_t FirstRegIndex = LocIndex::rawIndexForReg(1); 926 uint64_t FirstInvalidIndex = 927 LocIndex::rawIndexForReg(LocIndex::kFirstInvalidRegLocation); 928 for (auto It = CollectFrom.find(FirstRegIndex), 929 End = CollectFrom.find(FirstInvalidIndex); 930 It != End;) { 931 // We found a VarLoc ID for a VarLoc that lives in a register. Figure out 932 // which register and add it to UsedRegs. 933 uint32_t FoundReg = LocIndex::fromRawInteger(*It).Location; 934 assert((UsedRegs.empty() || FoundReg != UsedRegs.back()) && 935 "Duplicate used reg"); 936 UsedRegs.push_back(FoundReg); 937 938 // Skip to the next /set/ register. Note that this finds a lower bound, so 939 // even if there aren't any VarLocs living in `FoundReg+1`, we're still 940 // guaranteed to move on to the next register (or to end()). 941 uint64_t NextRegIndex = LocIndex::rawIndexForReg(FoundReg + 1); 942 It.advanceToLowerBound(NextRegIndex); 943 } 944 } 945 946 //===----------------------------------------------------------------------===// 947 // Debug Range Extension Implementation 948 //===----------------------------------------------------------------------===// 949 950 #ifndef NDEBUG 951 void VarLocBasedLDV::printVarLocInMBB(const MachineFunction &MF, 952 const VarLocInMBB &V, 953 const VarLocMap &VarLocIDs, 954 const char *msg, 955 raw_ostream &Out) const { 956 Out << '\n' << msg << '\n'; 957 for (const MachineBasicBlock &BB : MF) { 958 if (!V.count(&BB)) 959 continue; 960 const VarLocSet &L = getVarLocsInMBB(&BB, V); 961 if (L.empty()) 962 continue; 963 Out << "MBB: " << BB.getNumber() << ":\n"; 964 for (uint64_t VLL : L) { 965 const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(VLL)]; 966 Out << " Var: " << VL.Var.getVariable()->getName(); 967 Out << " MI: "; 968 VL.dump(TRI, Out); 969 } 970 } 971 Out << "\n"; 972 } 973 #endif 974 975 VarLocBasedLDV::VarLoc::SpillLoc 976 VarLocBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) { 977 assert(MI.hasOneMemOperand() && 978 "Spill instruction does not have exactly one memory operand?"); 979 auto MMOI = MI.memoperands_begin(); 980 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 981 assert(PVal->kind() == PseudoSourceValue::FixedStack && 982 "Inconsistent memory operand in spill instruction"); 983 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex(); 984 const MachineBasicBlock *MBB = MI.getParent(); 985 Register Reg; 986 StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg); 987 assert(!Offset.getScalable() && 988 "Frame offsets with a scalable component are not supported"); 989 return {Reg, static_cast<int>(Offset.getFixed())}; 990 } 991 992 /// Try to salvage the debug entry value if we encounter a new debug value 993 /// describing the same parameter, otherwise stop tracking the value. Return 994 /// true if we should stop tracking the entry value, otherwise return false. 995 bool VarLocBasedLDV::removeEntryValue(const MachineInstr &MI, 996 OpenRangesSet &OpenRanges, 997 VarLocMap &VarLocIDs, 998 const VarLoc &EntryVL) { 999 // Skip the DBG_VALUE which is the debug entry value itself. 1000 if (MI.isIdenticalTo(EntryVL.MI)) 1001 return false; 1002 1003 // If the parameter's location is not register location, we can not track 1004 // the entry value any more. In addition, if the debug expression from the 1005 // DBG_VALUE is not empty, we can assume the parameter's value has changed 1006 // indicating that we should stop tracking its entry value as well. 1007 if (!MI.getDebugOperand(0).isReg() || 1008 MI.getDebugExpression()->getNumElements() != 0) 1009 return true; 1010 1011 // If the DBG_VALUE comes from a copy instruction that copies the entry value, 1012 // it means the parameter's value has not changed and we should be able to use 1013 // its entry value. 1014 bool TrySalvageEntryValue = false; 1015 Register Reg = MI.getDebugOperand(0).getReg(); 1016 auto I = std::next(MI.getReverseIterator()); 1017 const MachineOperand *SrcRegOp, *DestRegOp; 1018 if (I != MI.getParent()->rend()) { 1019 // TODO: Try to keep tracking of an entry value if we encounter a propagated 1020 // DBG_VALUE describing the copy of the entry value. (Propagated entry value 1021 // does not indicate the parameter modification.) 1022 auto DestSrc = TII->isCopyInstr(*I); 1023 if (!DestSrc) 1024 return true; 1025 1026 SrcRegOp = DestSrc->Source; 1027 DestRegOp = DestSrc->Destination; 1028 if (Reg != DestRegOp->getReg()) 1029 return true; 1030 TrySalvageEntryValue = true; 1031 } 1032 1033 if (TrySalvageEntryValue) { 1034 for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) { 1035 const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(ID)]; 1036 if (VL.getEntryValueCopyBackupReg() == Reg && 1037 VL.MI.getDebugOperand(0).getReg() == SrcRegOp->getReg()) 1038 return false; 1039 } 1040 } 1041 1042 return true; 1043 } 1044 1045 /// End all previous ranges related to @MI and start a new range from @MI 1046 /// if it is a DBG_VALUE instr. 1047 void VarLocBasedLDV::transferDebugValue(const MachineInstr &MI, 1048 OpenRangesSet &OpenRanges, 1049 VarLocMap &VarLocIDs) { 1050 if (!MI.isDebugValue()) 1051 return; 1052 const DILocalVariable *Var = MI.getDebugVariable(); 1053 const DIExpression *Expr = MI.getDebugExpression(); 1054 const DILocation *DebugLoc = MI.getDebugLoc(); 1055 const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 1056 assert(Var->isValidLocationForIntrinsic(DebugLoc) && 1057 "Expected inlined-at fields to agree"); 1058 1059 DebugVariable V(Var, Expr, InlinedAt); 1060 1061 // Check if this DBG_VALUE indicates a parameter's value changing. 1062 // If that is the case, we should stop tracking its entry value. 1063 auto EntryValBackupID = OpenRanges.getEntryValueBackup(V); 1064 if (Var->isParameter() && EntryValBackupID) { 1065 const VarLoc &EntryVL = VarLocIDs[*EntryValBackupID]; 1066 if (removeEntryValue(MI, OpenRanges, VarLocIDs, EntryVL)) { 1067 LLVM_DEBUG(dbgs() << "Deleting a DBG entry value because of: "; 1068 MI.print(dbgs(), /*IsStandalone*/ false, 1069 /*SkipOpers*/ false, /*SkipDebugLoc*/ false, 1070 /*AddNewLine*/ true, TII)); 1071 OpenRanges.erase(EntryVL); 1072 } 1073 } 1074 1075 if (isDbgValueDescribedByReg(MI) || MI.getDebugOperand(0).isImm() || 1076 MI.getDebugOperand(0).isFPImm() || MI.getDebugOperand(0).isCImm()) { 1077 // Use normal VarLoc constructor for registers and immediates. 1078 VarLoc VL(MI, LS); 1079 // End all previous ranges of VL.Var. 1080 OpenRanges.erase(VL); 1081 1082 LocIndex ID = VarLocIDs.insert(VL); 1083 // Add the VarLoc to OpenRanges from this DBG_VALUE. 1084 OpenRanges.insert(ID, VL); 1085 } else if (MI.hasOneMemOperand()) { 1086 llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?"); 1087 } else { 1088 // This must be an undefined location. If it has an open range, erase it. 1089 assert(MI.getDebugOperand(0).isReg() && 1090 MI.getDebugOperand(0).getReg() == 0 && 1091 "Unexpected non-undef DBG_VALUE encountered"); 1092 VarLoc VL(MI, LS); 1093 OpenRanges.erase(VL); 1094 } 1095 } 1096 1097 /// Turn the entry value backup locations into primary locations. 1098 void VarLocBasedLDV::emitEntryValues(MachineInstr &MI, 1099 OpenRangesSet &OpenRanges, 1100 VarLocMap &VarLocIDs, 1101 TransferMap &Transfers, 1102 VarLocSet &KillSet) { 1103 // Do not insert entry value locations after a terminator. 1104 if (MI.isTerminator()) 1105 return; 1106 1107 for (uint64_t ID : KillSet) { 1108 LocIndex Idx = LocIndex::fromRawInteger(ID); 1109 const VarLoc &VL = VarLocIDs[Idx]; 1110 if (!VL.Var.getVariable()->isParameter()) 1111 continue; 1112 1113 auto DebugVar = VL.Var; 1114 Optional<LocIndex> EntryValBackupID = 1115 OpenRanges.getEntryValueBackup(DebugVar); 1116 1117 // If the parameter has the entry value backup, it means we should 1118 // be able to use its entry value. 1119 if (!EntryValBackupID) 1120 continue; 1121 1122 const VarLoc &EntryVL = VarLocIDs[*EntryValBackupID]; 1123 VarLoc EntryLoc = 1124 VarLoc::CreateEntryLoc(EntryVL.MI, LS, EntryVL.Expr, EntryVL.Loc.RegNo); 1125 LocIndex EntryValueID = VarLocIDs.insert(EntryLoc); 1126 Transfers.push_back({&MI, EntryValueID}); 1127 OpenRanges.insert(EntryValueID, EntryLoc); 1128 } 1129 } 1130 1131 /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc 1132 /// with \p OldVarID should be deleted form \p OpenRanges and replaced with 1133 /// new VarLoc. If \p NewReg is different than default zero value then the 1134 /// new location will be register location created by the copy like instruction, 1135 /// otherwise it is variable's location on the stack. 1136 void VarLocBasedLDV::insertTransferDebugPair( 1137 MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers, 1138 VarLocMap &VarLocIDs, LocIndex OldVarID, TransferKind Kind, 1139 Register NewReg) { 1140 const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI; 1141 1142 auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &VarLocIDs](VarLoc &VL) { 1143 LocIndex LocId = VarLocIDs.insert(VL); 1144 1145 // Close this variable's previous location range. 1146 OpenRanges.erase(VL); 1147 1148 // Record the new location as an open range, and a postponed transfer 1149 // inserting a DBG_VALUE for this location. 1150 OpenRanges.insert(LocId, VL); 1151 assert(!MI.isTerminator() && "Cannot insert DBG_VALUE after terminator"); 1152 TransferDebugPair MIP = {&MI, LocId}; 1153 Transfers.push_back(MIP); 1154 }; 1155 1156 // End all previous ranges of VL.Var. 1157 OpenRanges.erase(VarLocIDs[OldVarID]); 1158 switch (Kind) { 1159 case TransferKind::TransferCopy: { 1160 assert(NewReg && 1161 "No register supplied when handling a copy of a debug value"); 1162 // Create a DBG_VALUE instruction to describe the Var in its new 1163 // register location. 1164 VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg); 1165 ProcessVarLoc(VL); 1166 LLVM_DEBUG({ 1167 dbgs() << "Creating VarLoc for register copy:"; 1168 VL.dump(TRI); 1169 }); 1170 return; 1171 } 1172 case TransferKind::TransferSpill: { 1173 // Create a DBG_VALUE instruction to describe the Var in its spilled 1174 // location. 1175 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI); 1176 VarLoc VL = VarLoc::CreateSpillLoc(*DebugInstr, SpillLocation.SpillBase, 1177 SpillLocation.SpillOffset, LS); 1178 ProcessVarLoc(VL); 1179 LLVM_DEBUG({ 1180 dbgs() << "Creating VarLoc for spill:"; 1181 VL.dump(TRI); 1182 }); 1183 return; 1184 } 1185 case TransferKind::TransferRestore: { 1186 assert(NewReg && 1187 "No register supplied when handling a restore of a debug value"); 1188 // DebugInstr refers to the pre-spill location, therefore we can reuse 1189 // its expression. 1190 VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg); 1191 ProcessVarLoc(VL); 1192 LLVM_DEBUG({ 1193 dbgs() << "Creating VarLoc for restore:"; 1194 VL.dump(TRI); 1195 }); 1196 return; 1197 } 1198 } 1199 llvm_unreachable("Invalid transfer kind"); 1200 } 1201 1202 /// A definition of a register may mark the end of a range. 1203 void VarLocBasedLDV::transferRegisterDef( 1204 MachineInstr &MI, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs, 1205 TransferMap &Transfers) { 1206 1207 // Meta Instructions do not affect the debug liveness of any register they 1208 // define. 1209 if (MI.isMetaInstruction()) 1210 return; 1211 1212 MachineFunction *MF = MI.getMF(); 1213 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1214 Register SP = TLI->getStackPointerRegisterToSaveRestore(); 1215 1216 // Find the regs killed by MI, and find regmasks of preserved regs. 1217 DefinedRegsSet DeadRegs; 1218 SmallVector<const uint32_t *, 4> RegMasks; 1219 for (const MachineOperand &MO : MI.operands()) { 1220 // Determine whether the operand is a register def. 1221 if (MO.isReg() && MO.isDef() && MO.getReg() && 1222 Register::isPhysicalRegister(MO.getReg()) && 1223 !(MI.isCall() && MO.getReg() == SP)) { 1224 // Remove ranges of all aliased registers. 1225 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1226 // FIXME: Can we break out of this loop early if no insertion occurs? 1227 DeadRegs.insert(*RAI); 1228 } else if (MO.isRegMask()) { 1229 RegMasks.push_back(MO.getRegMask()); 1230 } 1231 } 1232 1233 // Erase VarLocs which reside in one of the dead registers. For performance 1234 // reasons, it's critical to not iterate over the full set of open VarLocs. 1235 // Iterate over the set of dying/used regs instead. 1236 if (!RegMasks.empty()) { 1237 SmallVector<uint32_t, 32> UsedRegs; 1238 getUsedRegs(OpenRanges.getVarLocs(), UsedRegs); 1239 for (uint32_t Reg : UsedRegs) { 1240 // Remove ranges of all clobbered registers. Register masks don't usually 1241 // list SP as preserved. Assume that call instructions never clobber SP, 1242 // because some backends (e.g., AArch64) never list SP in the regmask. 1243 // While the debug info may be off for an instruction or two around 1244 // callee-cleanup calls, transferring the DEBUG_VALUE across the call is 1245 // still a better user experience. 1246 if (Reg == SP) 1247 continue; 1248 bool AnyRegMaskKillsReg = 1249 any_of(RegMasks, [Reg](const uint32_t *RegMask) { 1250 return MachineOperand::clobbersPhysReg(RegMask, Reg); 1251 }); 1252 if (AnyRegMaskKillsReg) 1253 DeadRegs.insert(Reg); 1254 } 1255 } 1256 1257 if (DeadRegs.empty()) 1258 return; 1259 1260 VarLocSet KillSet(Alloc); 1261 collectIDsForRegs(KillSet, DeadRegs, OpenRanges.getVarLocs()); 1262 OpenRanges.erase(KillSet, VarLocIDs); 1263 1264 if (TPC) { 1265 auto &TM = TPC->getTM<TargetMachine>(); 1266 if (TM.Options.ShouldEmitDebugEntryValues()) 1267 emitEntryValues(MI, OpenRanges, VarLocIDs, Transfers, KillSet); 1268 } 1269 } 1270 1271 bool VarLocBasedLDV::isSpillInstruction(const MachineInstr &MI, 1272 MachineFunction *MF) { 1273 // TODO: Handle multiple stores folded into one. 1274 if (!MI.hasOneMemOperand()) 1275 return false; 1276 1277 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII)) 1278 return false; // This is not a spill instruction, since no valid size was 1279 // returned from either function. 1280 1281 return true; 1282 } 1283 1284 bool VarLocBasedLDV::isLocationSpill(const MachineInstr &MI, 1285 MachineFunction *MF, Register &Reg) { 1286 if (!isSpillInstruction(MI, MF)) 1287 return false; 1288 1289 auto isKilledReg = [&](const MachineOperand MO, Register &Reg) { 1290 if (!MO.isReg() || !MO.isUse()) { 1291 Reg = 0; 1292 return false; 1293 } 1294 Reg = MO.getReg(); 1295 return MO.isKill(); 1296 }; 1297 1298 for (const MachineOperand &MO : MI.operands()) { 1299 // In a spill instruction generated by the InlineSpiller the spilled 1300 // register has its kill flag set. 1301 if (isKilledReg(MO, Reg)) 1302 return true; 1303 if (Reg != 0) { 1304 // Check whether next instruction kills the spilled register. 1305 // FIXME: Current solution does not cover search for killed register in 1306 // bundles and instructions further down the chain. 1307 auto NextI = std::next(MI.getIterator()); 1308 // Skip next instruction that points to basic block end iterator. 1309 if (MI.getParent()->end() == NextI) 1310 continue; 1311 Register RegNext; 1312 for (const MachineOperand &MONext : NextI->operands()) { 1313 // Return true if we came across the register from the 1314 // previous spill instruction that is killed in NextI. 1315 if (isKilledReg(MONext, RegNext) && RegNext == Reg) 1316 return true; 1317 } 1318 } 1319 } 1320 // Return false if we didn't find spilled register. 1321 return false; 1322 } 1323 1324 Optional<VarLocBasedLDV::VarLoc::SpillLoc> 1325 VarLocBasedLDV::isRestoreInstruction(const MachineInstr &MI, 1326 MachineFunction *MF, Register &Reg) { 1327 if (!MI.hasOneMemOperand()) 1328 return None; 1329 1330 // FIXME: Handle folded restore instructions with more than one memory 1331 // operand. 1332 if (MI.getRestoreSize(TII)) { 1333 Reg = MI.getOperand(0).getReg(); 1334 return extractSpillBaseRegAndOffset(MI); 1335 } 1336 return None; 1337 } 1338 1339 /// A spilled register may indicate that we have to end the current range of 1340 /// a variable and create a new one for the spill location. 1341 /// A restored register may indicate the reverse situation. 1342 /// We don't want to insert any instructions in process(), so we just create 1343 /// the DBG_VALUE without inserting it and keep track of it in \p Transfers. 1344 /// It will be inserted into the BB when we're done iterating over the 1345 /// instructions. 1346 void VarLocBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI, 1347 OpenRangesSet &OpenRanges, 1348 VarLocMap &VarLocIDs, 1349 TransferMap &Transfers) { 1350 MachineFunction *MF = MI.getMF(); 1351 TransferKind TKind; 1352 Register Reg; 1353 Optional<VarLoc::SpillLoc> Loc; 1354 1355 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump();); 1356 1357 // First, if there are any DBG_VALUEs pointing at a spill slot that is 1358 // written to, then close the variable location. The value in memory 1359 // will have changed. 1360 VarLocSet KillSet(Alloc); 1361 if (isSpillInstruction(MI, MF)) { 1362 Loc = extractSpillBaseRegAndOffset(MI); 1363 for (uint64_t ID : OpenRanges.getSpillVarLocs()) { 1364 LocIndex Idx = LocIndex::fromRawInteger(ID); 1365 const VarLoc &VL = VarLocIDs[Idx]; 1366 assert(VL.Kind == VarLoc::SpillLocKind && "Broken VarLocSet?"); 1367 if (VL.Loc.SpillLocation == *Loc) { 1368 // This location is overwritten by the current instruction -- terminate 1369 // the open range, and insert an explicit DBG_VALUE $noreg. 1370 // 1371 // Doing this at a later stage would require re-interpreting all 1372 // DBG_VALUes and DIExpressions to identify whether they point at 1373 // memory, and then analysing all memory writes to see if they 1374 // overwrite that memory, which is expensive. 1375 // 1376 // At this stage, we already know which DBG_VALUEs are for spills and 1377 // where they are located; it's best to fix handle overwrites now. 1378 KillSet.set(ID); 1379 VarLoc UndefVL = VarLoc::CreateCopyLoc(VL.MI, LS, 0); 1380 LocIndex UndefLocID = VarLocIDs.insert(UndefVL); 1381 Transfers.push_back({&MI, UndefLocID}); 1382 } 1383 } 1384 OpenRanges.erase(KillSet, VarLocIDs); 1385 } 1386 1387 // Try to recognise spill and restore instructions that may create a new 1388 // variable location. 1389 if (isLocationSpill(MI, MF, Reg)) { 1390 TKind = TransferKind::TransferSpill; 1391 LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump();); 1392 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI) 1393 << "\n"); 1394 } else { 1395 if (!(Loc = isRestoreInstruction(MI, MF, Reg))) 1396 return; 1397 TKind = TransferKind::TransferRestore; 1398 LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump();); 1399 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI) 1400 << "\n"); 1401 } 1402 // Check if the register or spill location is the location of a debug value. 1403 auto TransferCandidates = OpenRanges.getEmptyVarLocRange(); 1404 if (TKind == TransferKind::TransferSpill) 1405 TransferCandidates = OpenRanges.getRegisterVarLocs(Reg); 1406 else if (TKind == TransferKind::TransferRestore) 1407 TransferCandidates = OpenRanges.getSpillVarLocs(); 1408 for (uint64_t ID : TransferCandidates) { 1409 LocIndex Idx = LocIndex::fromRawInteger(ID); 1410 const VarLoc &VL = VarLocIDs[Idx]; 1411 if (TKind == TransferKind::TransferSpill) { 1412 assert(VL.isDescribedByReg() == Reg && "Broken VarLocSet?"); 1413 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '(' 1414 << VL.Var.getVariable()->getName() << ")\n"); 1415 } else { 1416 assert(TKind == TransferKind::TransferRestore && 1417 VL.Kind == VarLoc::SpillLocKind && "Broken VarLocSet?"); 1418 if (VL.Loc.SpillLocation != *Loc) 1419 // The spill location is not the location of a debug value. 1420 continue; 1421 LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '(' 1422 << VL.Var.getVariable()->getName() << ")\n"); 1423 } 1424 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx, TKind, 1425 Reg); 1426 // FIXME: A comment should explain why it's correct to return early here, 1427 // if that is in fact correct. 1428 return; 1429 } 1430 } 1431 1432 /// If \p MI is a register copy instruction, that copies a previously tracked 1433 /// value from one register to another register that is callee saved, we 1434 /// create new DBG_VALUE instruction described with copy destination register. 1435 void VarLocBasedLDV::transferRegisterCopy(MachineInstr &MI, 1436 OpenRangesSet &OpenRanges, 1437 VarLocMap &VarLocIDs, 1438 TransferMap &Transfers) { 1439 auto DestSrc = TII->isCopyInstr(MI); 1440 if (!DestSrc) 1441 return; 1442 1443 const MachineOperand *DestRegOp = DestSrc->Destination; 1444 const MachineOperand *SrcRegOp = DestSrc->Source; 1445 1446 if (!DestRegOp->isDef()) 1447 return; 1448 1449 auto isCalleeSavedReg = [&](Register Reg) { 1450 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1451 if (CalleeSavedRegs.test(*RAI)) 1452 return true; 1453 return false; 1454 }; 1455 1456 Register SrcReg = SrcRegOp->getReg(); 1457 Register DestReg = DestRegOp->getReg(); 1458 1459 // We want to recognize instructions where destination register is callee 1460 // saved register. If register that could be clobbered by the call is 1461 // included, there would be a great chance that it is going to be clobbered 1462 // soon. It is more likely that previous register location, which is callee 1463 // saved, is going to stay unclobbered longer, even if it is killed. 1464 if (!isCalleeSavedReg(DestReg)) 1465 return; 1466 1467 // Remember an entry value movement. If we encounter a new debug value of 1468 // a parameter describing only a moving of the value around, rather then 1469 // modifying it, we are still able to use the entry value if needed. 1470 if (isRegOtherThanSPAndFP(*DestRegOp, MI, TRI)) { 1471 for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) { 1472 LocIndex Idx = LocIndex::fromRawInteger(ID); 1473 const VarLoc &VL = VarLocIDs[Idx]; 1474 if (VL.getEntryValueBackupReg() == SrcReg) { 1475 LLVM_DEBUG(dbgs() << "Copy of the entry value: "; MI.dump();); 1476 VarLoc EntryValLocCopyBackup = 1477 VarLoc::CreateEntryCopyBackupLoc(VL.MI, LS, VL.Expr, DestReg); 1478 1479 // Stop tracking the original entry value. 1480 OpenRanges.erase(VL); 1481 1482 // Start tracking the entry value copy. 1483 LocIndex EntryValCopyLocID = VarLocIDs.insert(EntryValLocCopyBackup); 1484 OpenRanges.insert(EntryValCopyLocID, EntryValLocCopyBackup); 1485 break; 1486 } 1487 } 1488 } 1489 1490 if (!SrcRegOp->isKill()) 1491 return; 1492 1493 for (uint64_t ID : OpenRanges.getRegisterVarLocs(SrcReg)) { 1494 LocIndex Idx = LocIndex::fromRawInteger(ID); 1495 assert(VarLocIDs[Idx].isDescribedByReg() == SrcReg && "Broken VarLocSet?"); 1496 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx, 1497 TransferKind::TransferCopy, DestReg); 1498 // FIXME: A comment should explain why it's correct to return early here, 1499 // if that is in fact correct. 1500 return; 1501 } 1502 } 1503 1504 /// Terminate all open ranges at the end of the current basic block. 1505 bool VarLocBasedLDV::transferTerminator(MachineBasicBlock *CurMBB, 1506 OpenRangesSet &OpenRanges, 1507 VarLocInMBB &OutLocs, 1508 const VarLocMap &VarLocIDs) { 1509 bool Changed = false; 1510 1511 LLVM_DEBUG(for (uint64_t ID 1512 : OpenRanges.getVarLocs()) { 1513 // Copy OpenRanges to OutLocs, if not already present. 1514 dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": "; 1515 VarLocIDs[LocIndex::fromRawInteger(ID)].dump(TRI); 1516 }); 1517 VarLocSet &VLS = getVarLocsInMBB(CurMBB, OutLocs); 1518 Changed = VLS != OpenRanges.getVarLocs(); 1519 // New OutLocs set may be different due to spill, restore or register 1520 // copy instruction processing. 1521 if (Changed) 1522 VLS = OpenRanges.getVarLocs(); 1523 OpenRanges.clear(); 1524 return Changed; 1525 } 1526 1527 /// Accumulate a mapping between each DILocalVariable fragment and other 1528 /// fragments of that DILocalVariable which overlap. This reduces work during 1529 /// the data-flow stage from "Find any overlapping fragments" to "Check if the 1530 /// known-to-overlap fragments are present". 1531 /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for 1532 /// fragment usage. 1533 /// \param SeenFragments Map from DILocalVariable to all fragments of that 1534 /// Variable which are known to exist. 1535 /// \param OverlappingFragments The overlap map being constructed, from one 1536 /// Var/Fragment pair to a vector of fragments known to overlap. 1537 void VarLocBasedLDV::accumulateFragmentMap(MachineInstr &MI, 1538 VarToFragments &SeenFragments, 1539 OverlapMap &OverlappingFragments) { 1540 DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(), 1541 MI.getDebugLoc()->getInlinedAt()); 1542 FragmentInfo ThisFragment = MIVar.getFragmentOrDefault(); 1543 1544 // If this is the first sighting of this variable, then we are guaranteed 1545 // there are currently no overlapping fragments either. Initialize the set 1546 // of seen fragments, record no overlaps for the current one, and return. 1547 auto SeenIt = SeenFragments.find(MIVar.getVariable()); 1548 if (SeenIt == SeenFragments.end()) { 1549 SmallSet<FragmentInfo, 4> OneFragment; 1550 OneFragment.insert(ThisFragment); 1551 SeenFragments.insert({MIVar.getVariable(), OneFragment}); 1552 1553 OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1554 return; 1555 } 1556 1557 // If this particular Variable/Fragment pair already exists in the overlap 1558 // map, it has already been accounted for. 1559 auto IsInOLapMap = 1560 OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1561 if (!IsInOLapMap.second) 1562 return; 1563 1564 auto &ThisFragmentsOverlaps = IsInOLapMap.first->second; 1565 auto &AllSeenFragments = SeenIt->second; 1566 1567 // Otherwise, examine all other seen fragments for this variable, with "this" 1568 // fragment being a previously unseen fragment. Record any pair of 1569 // overlapping fragments. 1570 for (auto &ASeenFragment : AllSeenFragments) { 1571 // Does this previously seen fragment overlap? 1572 if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) { 1573 // Yes: Mark the current fragment as being overlapped. 1574 ThisFragmentsOverlaps.push_back(ASeenFragment); 1575 // Mark the previously seen fragment as being overlapped by the current 1576 // one. 1577 auto ASeenFragmentsOverlaps = 1578 OverlappingFragments.find({MIVar.getVariable(), ASeenFragment}); 1579 assert(ASeenFragmentsOverlaps != OverlappingFragments.end() && 1580 "Previously seen var fragment has no vector of overlaps"); 1581 ASeenFragmentsOverlaps->second.push_back(ThisFragment); 1582 } 1583 } 1584 1585 AllSeenFragments.insert(ThisFragment); 1586 } 1587 1588 /// This routine creates OpenRanges. 1589 void VarLocBasedLDV::process(MachineInstr &MI, OpenRangesSet &OpenRanges, 1590 VarLocMap &VarLocIDs, TransferMap &Transfers) { 1591 transferDebugValue(MI, OpenRanges, VarLocIDs); 1592 transferRegisterDef(MI, OpenRanges, VarLocIDs, Transfers); 1593 transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers); 1594 transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers); 1595 } 1596 1597 /// This routine joins the analysis results of all incoming edges in @MBB by 1598 /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same 1599 /// source variable in all the predecessors of @MBB reside in the same location. 1600 bool VarLocBasedLDV::join( 1601 MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs, 1602 const VarLocMap &VarLocIDs, 1603 SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 1604 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) { 1605 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 1606 1607 VarLocSet InLocsT(Alloc); // Temporary incoming locations. 1608 1609 // For all predecessors of this MBB, find the set of VarLocs that 1610 // can be joined. 1611 int NumVisited = 0; 1612 for (auto p : MBB.predecessors()) { 1613 // Ignore backedges if we have not visited the predecessor yet. As the 1614 // predecessor hasn't yet had locations propagated into it, most locations 1615 // will not yet be valid, so treat them as all being uninitialized and 1616 // potentially valid. If a location guessed to be correct here is 1617 // invalidated later, we will remove it when we revisit this block. 1618 if (!Visited.count(p)) { 1619 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber() 1620 << "\n"); 1621 continue; 1622 } 1623 auto OL = OutLocs.find(p); 1624 // Join is null in case of empty OutLocs from any of the pred. 1625 if (OL == OutLocs.end()) 1626 return false; 1627 1628 // Just copy over the Out locs to incoming locs for the first visited 1629 // predecessor, and for all other predecessors join the Out locs. 1630 VarLocSet &OutLocVLS = *OL->second.get(); 1631 if (!NumVisited) 1632 InLocsT = OutLocVLS; 1633 else 1634 InLocsT &= OutLocVLS; 1635 1636 LLVM_DEBUG({ 1637 if (!InLocsT.empty()) { 1638 for (uint64_t ID : InLocsT) 1639 dbgs() << " gathered candidate incoming var: " 1640 << VarLocIDs[LocIndex::fromRawInteger(ID)] 1641 .Var.getVariable() 1642 ->getName() 1643 << "\n"; 1644 } 1645 }); 1646 1647 NumVisited++; 1648 } 1649 1650 // Filter out DBG_VALUES that are out of scope. 1651 VarLocSet KillSet(Alloc); 1652 bool IsArtificial = ArtificialBlocks.count(&MBB); 1653 if (!IsArtificial) { 1654 for (uint64_t ID : InLocsT) { 1655 LocIndex Idx = LocIndex::fromRawInteger(ID); 1656 if (!VarLocIDs[Idx].dominates(LS, MBB)) { 1657 KillSet.set(ID); 1658 LLVM_DEBUG({ 1659 auto Name = VarLocIDs[Idx].Var.getVariable()->getName(); 1660 dbgs() << " killing " << Name << ", it doesn't dominate MBB\n"; 1661 }); 1662 } 1663 } 1664 } 1665 InLocsT.intersectWithComplement(KillSet); 1666 1667 // As we are processing blocks in reverse post-order we 1668 // should have processed at least one predecessor, unless it 1669 // is the entry block which has no predecessor. 1670 assert((NumVisited || MBB.pred_empty()) && 1671 "Should have processed at least one predecessor"); 1672 1673 VarLocSet &ILS = getVarLocsInMBB(&MBB, InLocs); 1674 bool Changed = false; 1675 if (ILS != InLocsT) { 1676 ILS = InLocsT; 1677 Changed = true; 1678 } 1679 1680 return Changed; 1681 } 1682 1683 void VarLocBasedLDV::flushPendingLocs(VarLocInMBB &PendingInLocs, 1684 VarLocMap &VarLocIDs) { 1685 // PendingInLocs records all locations propagated into blocks, which have 1686 // not had DBG_VALUE insts created. Go through and create those insts now. 1687 for (auto &Iter : PendingInLocs) { 1688 // Map is keyed on a constant pointer, unwrap it so we can insert insts. 1689 auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first); 1690 VarLocSet &Pending = *Iter.second.get(); 1691 1692 for (uint64_t ID : Pending) { 1693 // The ID location is live-in to MBB -- work out what kind of machine 1694 // location it is and create a DBG_VALUE. 1695 const VarLoc &DiffIt = VarLocIDs[LocIndex::fromRawInteger(ID)]; 1696 if (DiffIt.isEntryBackupLoc()) 1697 continue; 1698 MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent()); 1699 MBB.insert(MBB.instr_begin(), MI); 1700 1701 (void)MI; 1702 LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump();); 1703 } 1704 } 1705 } 1706 1707 bool VarLocBasedLDV::isEntryValueCandidate( 1708 const MachineInstr &MI, const DefinedRegsSet &DefinedRegs) const { 1709 assert(MI.isDebugValue() && "This must be DBG_VALUE."); 1710 1711 // TODO: Add support for local variables that are expressed in terms of 1712 // parameters entry values. 1713 // TODO: Add support for modified arguments that can be expressed 1714 // by using its entry value. 1715 auto *DIVar = MI.getDebugVariable(); 1716 if (!DIVar->isParameter()) 1717 return false; 1718 1719 // Do not consider parameters that belong to an inlined function. 1720 if (MI.getDebugLoc()->getInlinedAt()) 1721 return false; 1722 1723 // Only consider parameters that are described using registers. Parameters 1724 // that are passed on the stack are not yet supported, so ignore debug 1725 // values that are described by the frame or stack pointer. 1726 if (!isRegOtherThanSPAndFP(MI.getDebugOperand(0), MI, TRI)) 1727 return false; 1728 1729 // If a parameter's value has been propagated from the caller, then the 1730 // parameter's DBG_VALUE may be described using a register defined by some 1731 // instruction in the entry block, in which case we shouldn't create an 1732 // entry value. 1733 if (DefinedRegs.count(MI.getDebugOperand(0).getReg())) 1734 return false; 1735 1736 // TODO: Add support for parameters that have a pre-existing debug expressions 1737 // (e.g. fragments). 1738 if (MI.getDebugExpression()->getNumElements() > 0) 1739 return false; 1740 1741 return true; 1742 } 1743 1744 /// Collect all register defines (including aliases) for the given instruction. 1745 static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs, 1746 const TargetRegisterInfo *TRI) { 1747 for (const MachineOperand &MO : MI.operands()) 1748 if (MO.isReg() && MO.isDef() && MO.getReg()) 1749 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI) 1750 Regs.insert(*AI); 1751 } 1752 1753 /// This routine records the entry values of function parameters. The values 1754 /// could be used as backup values. If we loose the track of some unmodified 1755 /// parameters, the backup values will be used as a primary locations. 1756 void VarLocBasedLDV::recordEntryValue(const MachineInstr &MI, 1757 const DefinedRegsSet &DefinedRegs, 1758 OpenRangesSet &OpenRanges, 1759 VarLocMap &VarLocIDs) { 1760 if (TPC) { 1761 auto &TM = TPC->getTM<TargetMachine>(); 1762 if (!TM.Options.ShouldEmitDebugEntryValues()) 1763 return; 1764 } 1765 1766 DebugVariable V(MI.getDebugVariable(), MI.getDebugExpression(), 1767 MI.getDebugLoc()->getInlinedAt()); 1768 1769 if (!isEntryValueCandidate(MI, DefinedRegs) || 1770 OpenRanges.getEntryValueBackup(V)) 1771 return; 1772 1773 LLVM_DEBUG(dbgs() << "Creating the backup entry location: "; MI.dump();); 1774 1775 // Create the entry value and use it as a backup location until it is 1776 // valid. It is valid until a parameter is not changed. 1777 DIExpression *NewExpr = 1778 DIExpression::prepend(MI.getDebugExpression(), DIExpression::EntryValue); 1779 VarLoc EntryValLocAsBackup = VarLoc::CreateEntryBackupLoc(MI, LS, NewExpr); 1780 LocIndex EntryValLocID = VarLocIDs.insert(EntryValLocAsBackup); 1781 OpenRanges.insert(EntryValLocID, EntryValLocAsBackup); 1782 } 1783 1784 /// Calculate the liveness information for the given machine function and 1785 /// extend ranges across basic blocks. 1786 bool VarLocBasedLDV::ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) { 1787 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n"); 1788 1789 if (!MF.getFunction().getSubprogram()) 1790 // VarLocBaseLDV will already have removed all DBG_VALUEs. 1791 return false; 1792 1793 // Skip functions from NoDebug compilation units. 1794 if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() == 1795 DICompileUnit::NoDebug) 1796 return false; 1797 1798 TRI = MF.getSubtarget().getRegisterInfo(); 1799 TII = MF.getSubtarget().getInstrInfo(); 1800 TFI = MF.getSubtarget().getFrameLowering(); 1801 TFI->getCalleeSaves(MF, CalleeSavedRegs); 1802 this->TPC = TPC; 1803 LS.initialize(MF); 1804 1805 bool Changed = false; 1806 bool OLChanged = false; 1807 bool MBBJoined = false; 1808 1809 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors. 1810 OverlapMap OverlapFragments; // Map of overlapping variable fragments. 1811 OpenRangesSet OpenRanges(Alloc, OverlapFragments); 1812 // Ranges that are open until end of bb. 1813 VarLocInMBB OutLocs; // Ranges that exist beyond bb. 1814 VarLocInMBB InLocs; // Ranges that are incoming after joining. 1815 TransferMap Transfers; // DBG_VALUEs associated with transfers (such as 1816 // spills, copies and restores). 1817 1818 VarToFragments SeenFragments; 1819 1820 // Blocks which are artificial, i.e. blocks which exclusively contain 1821 // instructions without locations, or with line 0 locations. 1822 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks; 1823 1824 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB; 1825 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder; 1826 std::priority_queue<unsigned int, std::vector<unsigned int>, 1827 std::greater<unsigned int>> 1828 Worklist; 1829 std::priority_queue<unsigned int, std::vector<unsigned int>, 1830 std::greater<unsigned int>> 1831 Pending; 1832 1833 // Set of register defines that are seen when traversing the entry block 1834 // looking for debug entry value candidates. 1835 DefinedRegsSet DefinedRegs; 1836 1837 // Only in the case of entry MBB collect DBG_VALUEs representing 1838 // function parameters in order to generate debug entry values for them. 1839 MachineBasicBlock &First_MBB = *(MF.begin()); 1840 for (auto &MI : First_MBB) { 1841 collectRegDefs(MI, DefinedRegs, TRI); 1842 if (MI.isDebugValue()) 1843 recordEntryValue(MI, DefinedRegs, OpenRanges, VarLocIDs); 1844 } 1845 1846 // Initialize per-block structures and scan for fragment overlaps. 1847 for (auto &MBB : MF) 1848 for (auto &MI : MBB) 1849 if (MI.isDebugValue()) 1850 accumulateFragmentMap(MI, SeenFragments, OverlapFragments); 1851 1852 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool { 1853 if (const DebugLoc &DL = MI.getDebugLoc()) 1854 return DL.getLine() != 0; 1855 return false; 1856 }; 1857 for (auto &MBB : MF) 1858 if (none_of(MBB.instrs(), hasNonArtificialLocation)) 1859 ArtificialBlocks.insert(&MBB); 1860 1861 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, 1862 "OutLocs after initialization", dbgs())); 1863 1864 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF); 1865 unsigned int RPONumber = 0; 1866 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) { 1867 OrderToBB[RPONumber] = *RI; 1868 BBToOrder[*RI] = RPONumber; 1869 Worklist.push(RPONumber); 1870 ++RPONumber; 1871 } 1872 1873 if (RPONumber > InputBBLimit) { 1874 unsigned NumInputDbgValues = 0; 1875 for (auto &MBB : MF) 1876 for (auto &MI : MBB) 1877 if (MI.isDebugValue()) 1878 ++NumInputDbgValues; 1879 if (NumInputDbgValues > InputDbgValueLimit) { 1880 LLVM_DEBUG(dbgs() << "Disabling VarLocBasedLDV: " << MF.getName() 1881 << " has " << RPONumber << " basic blocks and " 1882 << NumInputDbgValues 1883 << " input DBG_VALUEs, exceeding limits.\n"); 1884 return false; 1885 } 1886 } 1887 1888 // This is a standard "union of predecessor outs" dataflow problem. 1889 // To solve it, we perform join() and process() using the two worklist method 1890 // until the ranges converge. 1891 // Ranges have converged when both worklists are empty. 1892 SmallPtrSet<const MachineBasicBlock *, 16> Visited; 1893 while (!Worklist.empty() || !Pending.empty()) { 1894 // We track what is on the pending worklist to avoid inserting the same 1895 // thing twice. We could avoid this with a custom priority queue, but this 1896 // is probably not worth it. 1897 SmallPtrSet<MachineBasicBlock *, 16> OnPending; 1898 LLVM_DEBUG(dbgs() << "Processing Worklist\n"); 1899 while (!Worklist.empty()) { 1900 MachineBasicBlock *MBB = OrderToBB[Worklist.top()]; 1901 Worklist.pop(); 1902 MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited, 1903 ArtificialBlocks); 1904 MBBJoined |= Visited.insert(MBB).second; 1905 if (MBBJoined) { 1906 MBBJoined = false; 1907 Changed = true; 1908 // Now that we have started to extend ranges across BBs we need to 1909 // examine spill, copy and restore instructions to see whether they 1910 // operate with registers that correspond to user variables. 1911 // First load any pending inlocs. 1912 OpenRanges.insertFromLocSet(getVarLocsInMBB(MBB, InLocs), VarLocIDs); 1913 for (auto &MI : *MBB) 1914 process(MI, OpenRanges, VarLocIDs, Transfers); 1915 OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs); 1916 1917 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, 1918 "OutLocs after propagating", dbgs())); 1919 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, 1920 "InLocs after propagating", dbgs())); 1921 1922 if (OLChanged) { 1923 OLChanged = false; 1924 for (auto s : MBB->successors()) 1925 if (OnPending.insert(s).second) { 1926 Pending.push(BBToOrder[s]); 1927 } 1928 } 1929 } 1930 } 1931 Worklist.swap(Pending); 1932 // At this point, pending must be empty, since it was just the empty 1933 // worklist 1934 assert(Pending.empty() && "Pending should be empty"); 1935 } 1936 1937 // Add any DBG_VALUE instructions created by location transfers. 1938 for (auto &TR : Transfers) { 1939 assert(!TR.TransferInst->isTerminator() && 1940 "Cannot insert DBG_VALUE after terminator"); 1941 MachineBasicBlock *MBB = TR.TransferInst->getParent(); 1942 const VarLoc &VL = VarLocIDs[TR.LocationID]; 1943 MachineInstr *MI = VL.BuildDbgValue(MF); 1944 MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI); 1945 } 1946 Transfers.clear(); 1947 1948 // Deferred inlocs will not have had any DBG_VALUE insts created; do 1949 // that now. 1950 flushPendingLocs(InLocs, VarLocIDs); 1951 1952 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs())); 1953 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs())); 1954 return Changed; 1955 } 1956 1957 LDVImpl * 1958 llvm::makeVarLocBasedLiveDebugValues() 1959 { 1960 return new VarLocBasedLDV(); 1961 } 1962