1 //===------ LiveDebugValues.cpp - Tracking Debug Value MIs ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// This pass implements a data flow analysis that propagates debug location 11 /// information by inserting additional DBG_VALUE instructions into the machine 12 /// instruction stream. The pass internally builds debug location liveness 13 /// ranges to determine the points where additional DBG_VALUEs need to be 14 /// inserted. 15 /// 16 /// This is a separate pass from DbgValueHistoryCalculator to facilitate 17 /// testing and improve modularity. 18 /// 19 //===----------------------------------------------------------------------===// 20 21 #include "llvm/ADT/PostOrderIterator.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SparseBitVector.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/UniqueVector.h" 26 #include "llvm/CodeGen/LexicalScopes.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineFunctionPass.h" 29 #include "llvm/CodeGen/MachineInstrBuilder.h" 30 #include "llvm/CodeGen/Passes.h" 31 #include "llvm/IR/DebugInfo.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Target/TargetInstrInfo.h" 35 #include "llvm/Target/TargetLowering.h" 36 #include "llvm/Target/TargetRegisterInfo.h" 37 #include "llvm/Target/TargetSubtargetInfo.h" 38 #include <list> 39 #include <queue> 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "live-debug-values" 44 45 STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted"); 46 47 namespace { 48 49 // \brief If @MI is a DBG_VALUE with debug value described by a defined 50 // register, returns the number of this register. In the other case, returns 0. 51 static unsigned isDbgValueDescribedByReg(const MachineInstr &MI) { 52 assert(MI.isDebugValue() && "expected a DBG_VALUE"); 53 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE"); 54 // If location of variable is described using a register (directly 55 // or indirectly), this register is always a first operand. 56 return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0; 57 } 58 59 class LiveDebugValues : public MachineFunctionPass { 60 61 private: 62 const TargetRegisterInfo *TRI; 63 const TargetInstrInfo *TII; 64 LexicalScopes LS; 65 66 /// Keeps track of lexical scopes associated with a user value's source 67 /// location. 68 class UserValueScopes { 69 DebugLoc DL; 70 LexicalScopes &LS; 71 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks; 72 73 public: 74 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {} 75 76 /// Return true if current scope dominates at least one machine 77 /// instruction in a given machine basic block. 78 bool dominates(MachineBasicBlock *MBB) { 79 if (LBlocks.empty()) 80 LS.getMachineBasicBlocks(DL, LBlocks); 81 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB); 82 } 83 }; 84 85 /// Based on std::pair so it can be used as an index into a DenseMap. 86 typedef std::pair<const DILocalVariable *, const DILocation *> 87 DebugVariableBase; 88 /// A potentially inlined instance of a variable. 89 struct DebugVariable : public DebugVariableBase { 90 DebugVariable(const DILocalVariable *Var, const DILocation *InlinedAt) 91 : DebugVariableBase(Var, InlinedAt) {} 92 93 const DILocalVariable *getVar() const { return this->first; }; 94 const DILocation *getInlinedAt() const { return this->second; }; 95 96 bool operator<(const DebugVariable &DV) const { 97 if (getVar() == DV.getVar()) 98 return getInlinedAt() < DV.getInlinedAt(); 99 return getVar() < DV.getVar(); 100 } 101 }; 102 103 /// A pair of debug variable and value location. 104 struct VarLoc { 105 const DebugVariable Var; 106 const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE. 107 mutable UserValueScopes UVS; 108 enum { InvalidKind = 0, RegisterKind } Kind; 109 110 /// The value location. Stored separately to avoid repeatedly 111 /// extracting it from MI. 112 union { 113 struct { 114 uint32_t RegNo; 115 uint32_t Offset; 116 } RegisterLoc; 117 uint64_t Hash; 118 } Loc; 119 120 VarLoc(const MachineInstr &MI, LexicalScopes &LS) 121 : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI), 122 UVS(MI.getDebugLoc(), LS), Kind(InvalidKind) { 123 static_assert((sizeof(Loc) == sizeof(uint64_t)), 124 "hash does not cover all members of Loc"); 125 assert(MI.isDebugValue() && "not a DBG_VALUE"); 126 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE"); 127 if (int RegNo = isDbgValueDescribedByReg(MI)) { 128 Kind = RegisterKind; 129 Loc.RegisterLoc.RegNo = RegNo; 130 uint64_t Offset = 131 MI.isIndirectDebugValue() ? MI.getOperand(1).getImm() : 0; 132 // We don't support offsets larger than 4GiB here. They are 133 // slated to be replaced with DIExpressions anyway. 134 if (Offset >= (1ULL << 32)) 135 Kind = InvalidKind; 136 else 137 Loc.RegisterLoc.Offset = Offset; 138 } 139 } 140 141 /// If this variable is described by a register, return it, 142 /// otherwise return 0. 143 unsigned isDescribedByReg() const { 144 if (Kind == RegisterKind) 145 return Loc.RegisterLoc.RegNo; 146 return 0; 147 } 148 149 /// Determine whether the lexical scope of this value's debug location 150 /// dominates MBB. 151 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); } 152 153 void dump() const { MI.dump(); } 154 155 bool operator==(const VarLoc &Other) const { 156 return Var == Other.Var && Loc.Hash == Other.Loc.Hash; 157 } 158 159 /// This operator guarantees that VarLocs are sorted by Variable first. 160 bool operator<(const VarLoc &Other) const { 161 if (Var == Other.Var) 162 return Loc.Hash < Other.Loc.Hash; 163 return Var < Other.Var; 164 } 165 }; 166 167 typedef UniqueVector<VarLoc> VarLocMap; 168 typedef SparseBitVector<> VarLocSet; 169 typedef SmallDenseMap<const MachineBasicBlock *, VarLocSet> VarLocInMBB; 170 171 /// This holds the working set of currently open ranges. For fast 172 /// access, this is done both as a set of VarLocIDs, and a map of 173 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all 174 /// previous open ranges for the same variable. 175 class OpenRangesSet { 176 VarLocSet VarLocs; 177 SmallDenseMap<DebugVariableBase, unsigned, 8> Vars; 178 179 public: 180 const VarLocSet &getVarLocs() const { return VarLocs; } 181 182 /// Terminate all open ranges for Var by removing it from the set. 183 void erase(DebugVariable Var) { 184 auto It = Vars.find(Var); 185 if (It != Vars.end()) { 186 unsigned ID = It->second; 187 VarLocs.reset(ID); 188 Vars.erase(It); 189 } 190 } 191 192 /// Terminate all open ranges listed in \c KillSet by removing 193 /// them from the set. 194 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) { 195 VarLocs.intersectWithComplement(KillSet); 196 for (unsigned ID : KillSet) 197 Vars.erase(VarLocIDs[ID].Var); 198 } 199 200 /// Insert a new range into the set. 201 void insert(unsigned VarLocID, DebugVariableBase Var) { 202 VarLocs.set(VarLocID); 203 Vars.insert({Var, VarLocID}); 204 } 205 206 /// Empty the set. 207 void clear() { 208 VarLocs.clear(); 209 Vars.clear(); 210 } 211 212 /// Return whether the set is empty or not. 213 bool empty() const { 214 assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent"); 215 return VarLocs.empty(); 216 } 217 }; 218 219 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges, 220 VarLocMap &VarLocIDs); 221 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges, 222 const VarLocMap &VarLocIDs); 223 bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges, 224 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs); 225 bool transfer(MachineInstr &MI, OpenRangesSet &OpenRanges, 226 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs); 227 228 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs, 229 const VarLocMap &VarLocIDs, 230 SmallPtrSet<const MachineBasicBlock *, 16> &Visited); 231 232 bool ExtendRanges(MachineFunction &MF); 233 234 public: 235 static char ID; 236 237 /// Default construct and initialize the pass. 238 LiveDebugValues(); 239 240 /// Tell the pass manager which passes we depend on and what 241 /// information we preserve. 242 void getAnalysisUsage(AnalysisUsage &AU) const override; 243 244 MachineFunctionProperties getRequiredProperties() const override { 245 return MachineFunctionProperties().set( 246 MachineFunctionProperties::Property::NoVRegs); 247 } 248 249 /// Print to ostream with a message. 250 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V, 251 const VarLocMap &VarLocIDs, const char *msg, 252 raw_ostream &Out) const; 253 254 /// Calculate the liveness information for the given machine function. 255 bool runOnMachineFunction(MachineFunction &MF) override; 256 }; 257 258 } // namespace 259 260 //===----------------------------------------------------------------------===// 261 // Implementation 262 //===----------------------------------------------------------------------===// 263 264 char LiveDebugValues::ID = 0; 265 char &llvm::LiveDebugValuesID = LiveDebugValues::ID; 266 INITIALIZE_PASS(LiveDebugValues, "livedebugvalues", "Live DEBUG_VALUE analysis", 267 false, false) 268 269 /// Default construct and initialize the pass. 270 LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) { 271 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry()); 272 } 273 274 /// Tell the pass manager which passes we depend on and what information we 275 /// preserve. 276 void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const { 277 AU.setPreservesCFG(); 278 MachineFunctionPass::getAnalysisUsage(AU); 279 } 280 281 //===----------------------------------------------------------------------===// 282 // Debug Range Extension Implementation 283 //===----------------------------------------------------------------------===// 284 285 void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF, 286 const VarLocInMBB &V, 287 const VarLocMap &VarLocIDs, 288 const char *msg, 289 raw_ostream &Out) const { 290 Out << '\n' << msg << '\n'; 291 for (const MachineBasicBlock &BB : MF) { 292 const auto &L = V.lookup(&BB); 293 Out << "MBB: " << BB.getName() << ":\n"; 294 for (unsigned VLL : L) { 295 const VarLoc &VL = VarLocIDs[VLL]; 296 Out << " Var: " << VL.Var.getVar()->getName(); 297 Out << " MI: "; 298 VL.dump(); 299 } 300 } 301 Out << "\n"; 302 } 303 304 /// End all previous ranges related to @MI and start a new range from @MI 305 /// if it is a DBG_VALUE instr. 306 void LiveDebugValues::transferDebugValue(const MachineInstr &MI, 307 OpenRangesSet &OpenRanges, 308 VarLocMap &VarLocIDs) { 309 if (!MI.isDebugValue()) 310 return; 311 const DILocalVariable *Var = MI.getDebugVariable(); 312 const DILocation *DebugLoc = MI.getDebugLoc(); 313 const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 314 assert(Var->isValidLocationForIntrinsic(DebugLoc) && 315 "Expected inlined-at fields to agree"); 316 317 // End all previous ranges of Var. 318 DebugVariable V(Var, InlinedAt); 319 OpenRanges.erase(V); 320 321 // Add the VarLoc to OpenRanges from this DBG_VALUE. 322 // TODO: Currently handles DBG_VALUE which has only reg as location. 323 if (isDbgValueDescribedByReg(MI)) { 324 VarLoc VL(MI, LS); 325 unsigned ID = VarLocIDs.insert(VL); 326 OpenRanges.insert(ID, VL.Var); 327 } 328 } 329 330 /// A definition of a register may mark the end of a range. 331 void LiveDebugValues::transferRegisterDef(MachineInstr &MI, 332 OpenRangesSet &OpenRanges, 333 const VarLocMap &VarLocIDs) { 334 MachineFunction *MF = MI.getParent()->getParent(); 335 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 336 unsigned SP = TLI->getStackPointerRegisterToSaveRestore(); 337 SparseBitVector<> KillSet; 338 for (const MachineOperand &MO : MI.operands()) { 339 if (MO.isReg() && MO.isDef() && MO.getReg() && 340 TRI->isPhysicalRegister(MO.getReg())) { 341 // Remove ranges of all aliased registers. 342 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 343 for (unsigned ID : OpenRanges.getVarLocs()) 344 if (VarLocIDs[ID].isDescribedByReg() == *RAI) 345 KillSet.set(ID); 346 } else if (MO.isRegMask()) { 347 // Remove ranges of all clobbered registers. Register masks don't usually 348 // list SP as preserved. While the debug info may be off for an 349 // instruction or two around callee-cleanup calls, transferring the 350 // DEBUG_VALUE across the call is still a better user experience. 351 for (unsigned ID : OpenRanges.getVarLocs()) { 352 unsigned Reg = VarLocIDs[ID].isDescribedByReg(); 353 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg)) 354 KillSet.set(ID); 355 } 356 } 357 } 358 OpenRanges.erase(KillSet, VarLocIDs); 359 } 360 361 /// Terminate all open ranges at the end of the current basic block. 362 bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI, 363 OpenRangesSet &OpenRanges, 364 VarLocInMBB &OutLocs, 365 const VarLocMap &VarLocIDs) { 366 bool Changed = false; 367 const MachineBasicBlock *CurMBB = MI.getParent(); 368 if (!(MI.isTerminator() || (&MI == &CurMBB->instr_back()))) 369 return false; 370 371 if (OpenRanges.empty()) 372 return false; 373 374 DEBUG(for (unsigned ID : OpenRanges.getVarLocs()) { 375 // Copy OpenRanges to OutLocs, if not already present. 376 dbgs() << "Add to OutLocs: "; VarLocIDs[ID].dump(); 377 }); 378 VarLocSet &VLS = OutLocs[CurMBB]; 379 Changed = VLS |= OpenRanges.getVarLocs(); 380 OpenRanges.clear(); 381 return Changed; 382 } 383 384 /// This routine creates OpenRanges and OutLocs. 385 bool LiveDebugValues::transfer(MachineInstr &MI, OpenRangesSet &OpenRanges, 386 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs) { 387 bool Changed = false; 388 transferDebugValue(MI, OpenRanges, VarLocIDs); 389 transferRegisterDef(MI, OpenRanges, VarLocIDs); 390 Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs); 391 return Changed; 392 } 393 394 /// This routine joins the analysis results of all incoming edges in @MBB by 395 /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same 396 /// source variable in all the predecessors of @MBB reside in the same location. 397 bool LiveDebugValues::join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, 398 VarLocInMBB &InLocs, const VarLocMap &VarLocIDs, 399 SmallPtrSet<const MachineBasicBlock *, 16> &Visited) { 400 DEBUG(dbgs() << "join MBB: " << MBB.getName() << "\n"); 401 bool Changed = false; 402 403 VarLocSet InLocsT; // Temporary incoming locations. 404 405 // For all predecessors of this MBB, find the set of VarLocs that 406 // can be joined. 407 int NumVisited = 0; 408 for (auto p : MBB.predecessors()) { 409 // Ignore unvisited predecessor blocks. As we are processing 410 // the blocks in reverse post-order any unvisited block can 411 // be considered to not remove any incoming values. 412 if (!Visited.count(p)) 413 continue; 414 auto OL = OutLocs.find(p); 415 // Join is null in case of empty OutLocs from any of the pred. 416 if (OL == OutLocs.end()) 417 return false; 418 419 // Just copy over the Out locs to incoming locs for the first visited 420 // predecessor, and for all other predecessors join the Out locs. 421 if (!NumVisited) 422 InLocsT = OL->second; 423 else 424 InLocsT &= OL->second; 425 NumVisited++; 426 } 427 428 // Filter out DBG_VALUES that are out of scope. 429 VarLocSet KillSet; 430 for (auto ID : InLocsT) 431 if (!VarLocIDs[ID].dominates(MBB)) 432 KillSet.set(ID); 433 InLocsT.intersectWithComplement(KillSet); 434 435 // As we are processing blocks in reverse post-order we 436 // should have processed at least one predecessor, unless it 437 // is the entry block which has no predecessor. 438 assert((NumVisited || MBB.pred_empty()) && 439 "Should have processed at least one predecessor"); 440 if (InLocsT.empty()) 441 return false; 442 443 VarLocSet &ILS = InLocs[&MBB]; 444 445 // Insert DBG_VALUE instructions, if not already inserted. 446 VarLocSet Diff = InLocsT; 447 Diff.intersectWithComplement(ILS); 448 for (auto ID : Diff) { 449 // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a 450 // new range is started for the var from the mbb's beginning by inserting 451 // a new DBG_VALUE. transfer() will end this range however appropriate. 452 const VarLoc &DiffIt = VarLocIDs[ID]; 453 const MachineInstr *DMI = &DiffIt.MI; 454 MachineInstr *MI = 455 BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(), 456 DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(), 0, 457 DMI->getDebugVariable(), DMI->getDebugExpression()); 458 if (DMI->isIndirectDebugValue()) 459 MI->getOperand(1).setImm(DMI->getOperand(1).getImm()); 460 DEBUG(dbgs() << "Inserted: "; MI->dump();); 461 ILS.set(ID); 462 ++NumInserted; 463 Changed = true; 464 } 465 return Changed; 466 } 467 468 /// Calculate the liveness information for the given machine function and 469 /// extend ranges across basic blocks. 470 bool LiveDebugValues::ExtendRanges(MachineFunction &MF) { 471 472 DEBUG(dbgs() << "\nDebug Range Extension\n"); 473 474 bool Changed = false; 475 bool OLChanged = false; 476 bool MBBJoined = false; 477 478 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors. 479 OpenRangesSet OpenRanges; // Ranges that are open until end of bb. 480 VarLocInMBB OutLocs; // Ranges that exist beyond bb. 481 VarLocInMBB InLocs; // Ranges that are incoming after joining. 482 483 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB; 484 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder; 485 std::priority_queue<unsigned int, std::vector<unsigned int>, 486 std::greater<unsigned int>> 487 Worklist; 488 std::priority_queue<unsigned int, std::vector<unsigned int>, 489 std::greater<unsigned int>> 490 Pending; 491 492 // Initialize every mbb with OutLocs. 493 for (auto &MBB : MF) 494 for (auto &MI : MBB) 495 transfer(MI, OpenRanges, OutLocs, VarLocIDs); 496 497 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "OutLocs after initialization", 498 dbgs())); 499 500 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF); 501 unsigned int RPONumber = 0; 502 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) { 503 OrderToBB[RPONumber] = *RI; 504 BBToOrder[*RI] = RPONumber; 505 Worklist.push(RPONumber); 506 ++RPONumber; 507 } 508 // This is a standard "union of predecessor outs" dataflow problem. 509 // To solve it, we perform join() and transfer() using the two worklist method 510 // until the ranges converge. 511 // Ranges have converged when both worklists are empty. 512 SmallPtrSet<const MachineBasicBlock *, 16> Visited; 513 while (!Worklist.empty() || !Pending.empty()) { 514 // We track what is on the pending worklist to avoid inserting the same 515 // thing twice. We could avoid this with a custom priority queue, but this 516 // is probably not worth it. 517 SmallPtrSet<MachineBasicBlock *, 16> OnPending; 518 DEBUG(dbgs() << "Processing Worklist\n"); 519 while (!Worklist.empty()) { 520 MachineBasicBlock *MBB = OrderToBB[Worklist.top()]; 521 Worklist.pop(); 522 MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited); 523 Visited.insert(MBB); 524 if (MBBJoined) { 525 MBBJoined = false; 526 Changed = true; 527 for (auto &MI : *MBB) 528 OLChanged |= transfer(MI, OpenRanges, OutLocs, VarLocIDs); 529 530 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, 531 "OutLocs after propagating", dbgs())); 532 DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, 533 "InLocs after propagating", dbgs())); 534 535 if (OLChanged) { 536 OLChanged = false; 537 for (auto s : MBB->successors()) 538 if (OnPending.insert(s).second) { 539 Pending.push(BBToOrder[s]); 540 } 541 } 542 } 543 } 544 Worklist.swap(Pending); 545 // At this point, pending must be empty, since it was just the empty 546 // worklist 547 assert(Pending.empty() && "Pending should be empty"); 548 } 549 550 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs())); 551 DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs())); 552 return Changed; 553 } 554 555 bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) { 556 if (!MF.getFunction()->getSubprogram()) 557 // LiveDebugValues will already have removed all DBG_VALUEs. 558 return false; 559 560 TRI = MF.getSubtarget().getRegisterInfo(); 561 TII = MF.getSubtarget().getInstrInfo(); 562 LS.initialize(MF); 563 564 bool Changed = ExtendRanges(MF); 565 return Changed; 566 } 567