1//===-- NVPTXDwarfDebug.cpp - NVPTX DwarfDebug Implementation ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements helper functions for NVPTX-specific debug information
10// processing.
11//
12//===----------------------------------------------------------------------===//
13
14#include "NVPTXDwarfDebug.h"
15#include "NVPTXSubtarget.h"
16#include "llvm/BinaryFormat/Dwarf.h"
17#include "llvm/CodeGen/MachineFunction.h"
18#include "llvm/CodeGen/MachineInstr.h"
19#include "llvm/IR/DebugInfoMetadata.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/GlobalVariable.h"
22#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCStreamer.h"
25#include "llvm/Support/NVPTXAddrSpace.h"
26#include "llvm/Target/TargetMachine.h"
27
28using namespace llvm;
29
30NVPTXDwarfDebug::NVPTXDwarfDebug(AsmPrinter *A) : DwarfDebug(A) {
31 // PTX emits debug strings inline (no .debug_str section), does not support
32 // .debug_ranges, and uses sections as references (no temp symbols inside
33 // DWARF sections). DWARF v2 is the default for NVPTX and does not support
34 // accelerator tables.
35 setUseInlineStrings(true);
36 setUseRangesSection(false);
37 setUseSectionsAsReferences(true);
38 applyDwarfVersion(DwarfVersion: 2);
39 setTheAccelTableKind(AccelTableKind::None);
40}
41
42MCSymbol *NVPTXDwarfDebug::getOrCreateFuncNameSymbol(StringRef LinkageName) {
43 return InfoHolder.getStringPool().getEntry(Asm&: *Asm, Str: LinkageName).getSymbol();
44}
45
46bool NVPTXDwarfDebug::isEnhancedLineinfo(const MachineFunction &MF) const {
47 const DISubprogram *SP = MF.getFunction().getSubprogram();
48 const NVPTXSubtarget &STI = MF.getSubtarget<NVPTXSubtarget>();
49 return STI.getCLOpts().line_info_inlined_at &&
50 (STI.hasFeature(Feature: NVPTX::PTX72)) && SP &&
51 (SP->getUnit()->isDebugDirectivesOnly() ||
52 SP->getUnit()->getEmissionKind() == DICompileUnit::LineTablesOnly);
53}
54
55/// NVPTX-specific source line recording with inlined_at support.
56///
57/// Why this exists:
58/// NVPTX supports an "enhanced lineinfo" mode where inlining context is carried
59/// via line-table directives, rather than full DWARF DIEs. This is conceptually
60/// similar to proposals[1] for richer DWARF line tables that carry inline call
61/// context and callee identity in the line table. NVPTX implements this via
62/// target-specific `.loc` extensions in the PTX ISA[3].
63///
64/// How it impacts PTX assembly generation:
65/// - When enabled (PTX ISA >= 7.2 + line-tables-only / debug-directives-only),
66/// we emit multiple consecutive `.loc` directives for a single inlined
67/// instruction: the instruction's own location and its `inlined_at` parent
68/// chain.
69/// - During emission we use `MCStreamer::emitDwarfLocDirectiveWithInlinedAt` to
70/// emit an enhanced `.loc` directive[3] that carries the extra
71/// `function_name` and `inlined_at` operands in the PTX assembly stream.
72///
73/// Example (conceptual PTX `.loc` sequence for an inlined callsite):
74/// .loc 1 16 3 // caller location
75/// .loc 1 5 3, function_name $L__info_stringN, inlined_at 1 16 3
76/// // inlined callee location
77/// Here, $L__info_stringN is a label (or label+immediate) referring into
78/// `.debug_str`.
79///
80/// How this impacts DWARF :
81/// DWARF generation tools that consume this PTX(e.g. ptxas assembler) can use
82/// the `inlined_at` and `function_name` operands to extend the DWARF v2
83/// line table information.
84/// This adds:
85/// - a `context` column[2]: the `inlined_at <file> <line> <col>` information
86/// populates an inlining "context" (a reference to the parent/callsite row)
87/// enabling reconstruction of inline call chains from the line table.
88/// - a `function_name` column[2]: the `.loc ... function_name <sym>` identifies
89/// the inlined callee associated with a non-zero context.
90///
91/// References:
92/// - [1] DWARF line tables / Two-Level Line Tables:
93/// https://wiki.dwarfstd.org/TwoLevelLineTables.md
94/// - [2] DWARF issue tracking for Two-Level Line Tables:
95/// https://dwarfstd.org/issues/140906.1.html
96/// - [3] NVIDIA PTX ISA `.loc` (debugging directives; PTX ISA 7.2+):
97/// https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#debugging-directives-loc
98void NVPTXDwarfDebug::recordTargetSourceLine(const DebugLoc &DL,
99 unsigned Flags) {
100 // Maintain a work list of .loc to be emitted. If we are emitting the
101 // inlined_at directive, we might need to emit additional .loc prior
102 // to it for the location contained in the inlined_at.
103 SmallVector<const DILocation *, 8> WorkList;
104 SmallDenseSet<const DILocation *, 8> WorkListSet;
105 const DILocation *EmitLoc = DL.get();
106
107 if (!EmitLoc)
108 return;
109
110 const MachineFunction *MF = Asm->MF;
111 if (!MF)
112 return;
113
114 const bool EnhancedLineinfo = isEnhancedLineinfo(MF: *MF);
115
116 while (EmitLoc) {
117 // Get the scope for the current location.
118 const DIScope *Scope = EmitLoc->getScope();
119 if (!Scope)
120 break; // scope is null, we are done.
121
122 // Check if this loc is already in work list, if so, we are done.
123 if (WorkListSet.contains(V: EmitLoc))
124 break;
125
126 // Add this location to the work list.
127 WorkList.push_back(Elt: EmitLoc);
128 WorkListSet.insert(V: EmitLoc);
129
130 if (!EnhancedLineinfo) // No enhanced lineinfo, we are done.
131 break;
132
133 const DILocation *IA = EmitLoc->getInlinedAt();
134 // Check if this has inlined_at information, and if the parent location
135 // has not yet been emitted. If already emitted, we don't need to
136 // re-emit the parent chain.
137 if (IA && !EmittedInlinedAtLocs.contains(V: IA))
138 EmitLoc = IA;
139 else // We are done.
140 break;
141 }
142
143 const unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
144 // Traverse the work list, and emit .loc.
145 while (!WorkList.empty()) {
146 const DILocation *Current = WorkList.pop_back_val();
147 const DIScope *Scope = Current->getScope();
148
149 if (!Scope)
150 llvm_unreachable("we shouldn't be here for null scope");
151
152 const DILocation *InlinedAt = Current->getInlinedAt();
153 StringRef Fn = Scope->getFilename();
154 const unsigned Line = Current->getLine();
155 const unsigned Col = Current->getColumn();
156 unsigned Discriminator = 0;
157 if (Line != 0 && getDwarfVersion() >= 4)
158 if (const DILexicalBlockFile *LBF = dyn_cast<DILexicalBlockFile>(Val: Scope))
159 Discriminator = LBF->getDiscriminator();
160
161 const unsigned FileNo = static_cast<DwarfCompileUnit &>(*getUnits()[CUID])
162 .getOrCreateSourceID(File: Scope->getFile());
163
164 if (EnhancedLineinfo && InlinedAt) {
165 const unsigned FileIA = static_cast<DwarfCompileUnit &>(*getUnits()[CUID])
166 .getOrCreateSourceID(File: InlinedAt->getFile());
167 const DISubprogram *SubProgram = getDISubprogram(Scope: Current->getScope());
168 DwarfStringPoolEntryRef Entry = InfoHolder.getStringPool().getEntry(
169 Asm&: *Asm, Str: SubProgram->getLinkageName());
170 Asm->OutStreamer->emitDwarfLocDirectiveWithInlinedAt(
171 FileNo, Line, Column: Col, FileIA, LineIA: InlinedAt->getLine(),
172 ColumnIA: InlinedAt->getColumn(), Sym: Entry.getSymbol(), Flags, Isa: 0, Discriminator,
173 FileName: Fn);
174 } else {
175 Asm->OutStreamer->emitDwarfLocDirective(FileNo, Line, Column: Col, Flags, Isa: 0,
176 Discriminator, FileName: Fn);
177 }
178 // Mark this location as emitted so we don't re-emit the parent chain
179 // for subsequent instructions that share the same inlined_at parent.
180 if (EnhancedLineinfo)
181 EmittedInlinedAtLocs.insert(V: Current);
182 }
183}
184
185/// NVPTX-specific debug info initialization.
186void NVPTXDwarfDebug::initializeTargetDebugInfo(const MachineFunction &MF) {
187 EmittedInlinedAtLocs.clear();
188}
189
190// PTX does not support subtracting labels from the code section in the
191// debug_loc section. To work around this, the NVPTX backend needs the
192// compile unit to have no low_pc in order to have a zero base_address
193// when handling debug_loc in cuda-gdb.
194bool NVPTXDwarfDebug::shouldAttachCompileUnitRanges() const {
195 return !tuneForGDB();
196}
197
198// Same label-subtraction limitation as above: cuda-gdb doesn't handle
199// setting a per-variable base to zero, so we emit labels with no base
200// while having no compile unit low_pc.
201bool NVPTXDwarfDebug::shouldResetBaseAddress(const MCSection &Section) const {
202 return tuneForGDB();
203}
204
205static unsigned translateToNVVMDWARFAddrSpace(unsigned AddrSpace) {
206 switch (AddrSpace) {
207 case NVPTXAS::ADDRESS_SPACE_GENERIC:
208 return NVPTXAS::DWARF_ADDR_generic_space;
209 case NVPTXAS::ADDRESS_SPACE_GLOBAL:
210 return NVPTXAS::DWARF_ADDR_global_space;
211 case NVPTXAS::ADDRESS_SPACE_SHARED:
212 return NVPTXAS::DWARF_ADDR_shared_space;
213 case NVPTXAS::ADDRESS_SPACE_CONST:
214 return NVPTXAS::DWARF_ADDR_const_space;
215 case NVPTXAS::ADDRESS_SPACE_LOCAL:
216 return NVPTXAS::DWARF_ADDR_local_space;
217 default:
218 llvm_unreachable(
219 "Cannot translate unknown address space to DWARF address space");
220 return AddrSpace;
221 }
222}
223
224// cuda-gdb requires DW_AT_address_class on variable DIEs. The address space
225// is encoded in the DIExpression as a DW_OP_constu <DWARF Address Space>
226// DW_OP_swap DW_OP_xderef sequence. We strip that sequence from the
227// expression and return the address space so the caller can emit
228// DW_AT_address_class separately.
229const DIExpression *NVPTXDwarfDebug::adjustExpressionForTarget(
230 const DIExpression *Expr, std::optional<unsigned> &TargetAddrSpace) const {
231 if (!tuneForGDB())
232 return Expr;
233 unsigned LocalAddrSpace;
234 const DIExpression *NewExpr =
235 DIExpression::extractAddressClass(Expr, AddrClass&: LocalAddrSpace);
236 if (NewExpr != Expr) {
237 TargetAddrSpace = LocalAddrSpace;
238 return NewExpr;
239 }
240 return Expr;
241}
242
243// Emit DW_AT_address_class for cuda-gdb. See NVPTXAS::DWARF_AddressSpace.
244//
245// The address class depends on the variable's storage kind:
246// Global: from the expression (if encoded) or the IR address space
247// Register: DWARF_ADDR_reg_space (no expression means register location)
248// FrameIndex: from the expression (if encoded) or DWARF_ADDR_local_space
249void NVPTXDwarfDebug::addTargetVariableAttributes(
250 DwarfCompileUnit &CU, DIE &Die, std::optional<unsigned> TargetAddrSpace,
251 VariableLocationKind VarLocKind, const GlobalVariable *GV) const {
252 if (!tuneForGDB())
253 return;
254
255 unsigned DefaultAddrSpace = NVPTXAS::DWARF_ADDR_global_space;
256 switch (VarLocKind) {
257 case VariableLocationKind::Global:
258 if (!TargetAddrSpace && GV)
259 TargetAddrSpace =
260 translateToNVVMDWARFAddrSpace(AddrSpace: GV->getType()->getAddressSpace());
261 DefaultAddrSpace = NVPTXAS::DWARF_ADDR_global_space;
262 break;
263 case VariableLocationKind::Register:
264 DefaultAddrSpace = NVPTXAS::DWARF_ADDR_reg_space;
265 break;
266 case VariableLocationKind::FrameIndex:
267 DefaultAddrSpace = NVPTXAS::DWARF_ADDR_local_space;
268 break;
269 }
270
271 CU.addUInt(Die, Attribute: dwarf::DW_AT_address_class, Form: dwarf::DW_FORM_data1,
272 Integer: TargetAddrSpace.value_or(u&: DefaultAddrSpace));
273}
274
275void NVPTXDwarfDebug::finishTargetUnitAttributes(const DICompileUnit &DIUnit,
276 DwarfCompileUnit &NewCU) {
277 uint16_t Dialect = DIUnit.getSourceLanguage().getDialect();
278 // A zero dialect means "no dialect specified"; nothing to emit. This field
279 // should have already been range-checked by the assembly parser, IR verifier,
280 // and bitcode reader.
281 assert(Dialect <= dwarf::DW_LLVM_LANG_DIALECT_max &&
282 "Invalid or unsupported NVPTX language dialect.");
283 if (Dialect == 0)
284 return;
285
286 NewCU.addUInt(Die&: NewCU.getUnitDie(), Attribute: dwarf::DW_AT_LLVM_language_dialect,
287 Form: dwarf::DW_FORM_data1, Integer: Dialect);
288}
289