LLVM 24.0.0git
SPIRVNonSemanticDebugHandler.cpp
Go to the documentation of this file.
1//===-- SPIRVNonSemanticDebugHandler.cpp - NSDI AsmPrinter handler -*- C++
2//-*-===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
12#include "SPIRVSubtarget.h"
13#include "SPIRVTargetMachine.h"
14#include "SPIRVUtils.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
20#include "llvm/ADT/Twine.h"
26#include "llvm/IR/DebugInfo.h"
32#include "llvm/IR/Module.h"
33#include "llvm/MC/MCInst.h"
34#include "llvm/MC/MCStreamer.h"
37#include "llvm/Support/Path.h"
39#include <cassert>
40
41using namespace llvm;
42
43namespace {
44
45/// Look up \p Key in a register map and return its value, or std::nullopt when
46/// the key is absent.
47template <typename MapT>
48static std::optional<MCRegister> lookupOptReg(const MapT &Map,
49 typename MapT::key_type Key) {
50 auto It = Map.find(Key);
51 if (It == Map.end())
52 return std::nullopt;
53 assert(It->second.isValid() && "invalid register stored in map");
54 return It->second;
55}
56
57enum : uint32_t {
58 NSDIFlagIsProtected = 1u << 0,
59 NSDIFlagIsPrivate = 1u << 1,
60 NSDIFlagIsPublic = NSDIFlagIsPrivate | NSDIFlagIsProtected,
61 NSDIFlagIsLocal = 1u << 2,
62 NSDIFlagIsDefinition = 1u << 3,
63 NSDIFlagFwdDecl = 1u << 4,
64 NSDIFlagArtificial = 1u << 5,
65 NSDIFlagExplicit = 1u << 6,
66 NSDIFlagPrototyped = 1u << 7,
67 NSDIFlagObjectPointer = 1u << 8,
68 NSDIFlagStaticMember = 1u << 9,
69 NSDIFlagIndirectVariable = 1u << 10,
70 NSDIFlagLValueReference = 1u << 11,
71 NSDIFlagRValueReference = 1u << 12,
72 NSDIFlagIsOptimized = 1u << 13,
73 NSDIFlagIsEnumClass = 1u << 14,
74 NSDIFlagTypePassByValue = 1u << 15,
75 NSDIFlagTypePassByReference = 1u << 16,
76 NSDIFlagUnknownPhysicalLayout = 1u << 17,
77};
78
79static uint32_t mapDIFlagsToNonSemantic(DINode::DIFlags DFlags) {
80 uint32_t Flags = 0;
81 if ((DFlags & DINode::FlagAccessibility) == DINode::FlagPublic)
82 Flags |= NSDIFlagIsPublic;
83 if ((DFlags & DINode::FlagAccessibility) == DINode::FlagProtected)
84 Flags |= NSDIFlagIsProtected;
85 if ((DFlags & DINode::FlagAccessibility) == DINode::FlagPrivate)
86 Flags |= NSDIFlagIsPrivate;
87 if (DFlags & DINode::FlagFwdDecl)
88 Flags |= NSDIFlagFwdDecl;
89 if (DFlags & DINode::FlagArtificial)
90 Flags |= NSDIFlagArtificial;
91 if (DFlags & DINode::FlagExplicit)
92 Flags |= NSDIFlagExplicit;
93 if (DFlags & DINode::FlagPrototyped)
94 Flags |= NSDIFlagPrototyped;
95 if (DFlags & DINode::FlagObjectPointer)
96 Flags |= NSDIFlagObjectPointer;
97 if (DFlags & DINode::FlagStaticMember)
98 Flags |= NSDIFlagStaticMember;
99 if (DFlags & DINode::FlagLValueReference)
100 Flags |= NSDIFlagLValueReference;
101 if (DFlags & DINode::FlagRValueReference)
102 Flags |= NSDIFlagRValueReference;
103 if (DFlags & DINode::FlagTypePassByValue)
104 Flags |= NSDIFlagTypePassByValue;
105 if (DFlags & DINode::FlagTypePassByReference)
106 Flags |= NSDIFlagTypePassByReference;
107 if (DFlags & DINode::FlagEnumClass)
108 Flags |= NSDIFlagIsEnumClass;
109 return Flags;
110}
111
112static uint32_t transDebugFlags(const DINode *DN) {
113 uint32_t Flags = 0;
114 if (const auto *GV = dyn_cast<DIGlobalVariable>(DN)) {
115 if (GV->isLocalToUnit())
116 Flags |= NSDIFlagIsLocal;
117 if (GV->isDefinition())
118 Flags |= NSDIFlagIsDefinition;
119 }
120 if (const auto *SP = dyn_cast<DISubprogram>(DN)) {
121 if (SP->isLocalToUnit())
122 Flags |= NSDIFlagIsLocal;
123 if (SP->isOptimized())
124 Flags |= NSDIFlagIsOptimized;
125 if (SP->isDefinition())
126 Flags |= NSDIFlagIsDefinition;
127 Flags |= mapDIFlagsToNonSemantic(SP->getFlags());
128 }
129 if (DN->getTag() == dwarf::DW_TAG_reference_type)
130 Flags |= NSDIFlagLValueReference;
131 if (DN->getTag() == dwarf::DW_TAG_rvalue_reference_type)
132 Flags |= NSDIFlagRValueReference;
133 if (const auto *Ty = dyn_cast<DIType>(DN))
134 Flags |= mapDIFlagsToNonSemantic(Ty->getFlags());
135 if (const auto *LV = dyn_cast<DILocalVariable>(DN))
136 Flags |= mapDIFlagsToNonSemantic(LV->getFlags());
137 return Flags;
138}
139
140// Map a DWARF composite tag to a NonSemantic.Shader.DebugInfo Composite Type
141// value: Class 0, Structure 1, Union 2.
142static uint32_t mapCompositeTypeTag(unsigned Tag) {
143 switch (Tag) {
144 case dwarf::DW_TAG_class_type:
145 return 0;
146 case dwarf::DW_TAG_structure_type:
147 return 1;
148 case dwarf::DW_TAG_union_type:
149 return 2;
150 default:
151 reportFatalInternalError("unexpected DWARF composite tag " + Twine(Tag) +
152 ". Expecting 0, 1 or 2");
153 }
154}
155
156// Map a DWARF qualifier tag to a NonSemantic.Shader.DebugInfo Type Qualifier
157// value: Const 0, Volatile 1, Restrict 2, Atomic 3.
158static std::optional<uint32_t> mapTypeQualifierTag(unsigned Tag) {
159 switch (Tag) {
160 case dwarf::DW_TAG_const_type:
161 return 0;
162 case dwarf::DW_TAG_volatile_type:
163 return 1;
164 case dwarf::DW_TAG_restrict_type:
165 return 2;
166 case dwarf::DW_TAG_atomic_type:
167 return 3;
168 default:
169 return std::nullopt;
170 }
171}
172
173static const MachineInstr *
174findLastFunctionOpVariableDeclaration(const MachineFunction &MF,
176
177 // We iterate over the instructions to find the last OpVariable (or
178 // OpUntypedVariableKHR) instruction if any. The following SPIRV rule is used
179 // to terminate the traversal earlier: SPIR-V 2.16.1, Function Structure: "All
180 // OpVariable instructions in a function must be in the first block in the
181 // function. These instructions, together with any intermixed OpLine and
182 // OpNoLine instructions, must be the first instructions in that block."
183 const MachineInstr *LastOpVariable = nullptr;
184 bool SeenOpVariable = false;
185 for (const MachineInstr &MI : MF.front()) {
186 if (MI.getOpcode() == SPIRV::OpVariable ||
187 MI.getOpcode() == SPIRV::OpUntypedVariableKHR) {
188 SeenOpVariable = true;
189 if (!MAI.getSkipEmission(&MI))
190 LastOpVariable = &MI;
191 continue;
192 }
193
194 bool CanInterleaveWithOpVariable =
195 MI.getOpcode() == SPIRV::OpLine || MI.getOpcode() == SPIRV::OpNoLine;
196 if (SeenOpVariable && !CanInterleaveWithOpVariable &&
197 !MAI.getSkipEmission(&MI))
198 break;
199 }
200 return LastOpVariable;
201}
202
203} // namespace
204
209
210void SPIRVNonSemanticDebugHandler::initOptions(const SPIRVTargetMachine &TM) {
211 const SPIRVOptions &CLOpts = TM.getCLOpts();
212 bool AMDDefault = TM.getTargetTriple().getVendor() == Triple::AMD;
213 UseLexicalBlockDiscriminatorScope =
214 valueOr(CLOpts.debug_lexical_block_discriminator_scope, AMDDefault);
215 UseDebugScopeForwardRefs = CLOpts.debug_scope_forward_refs;
216 AllowDebugDeclareUntypedVariable =
217 valueOr(CLOpts.debug_declare_untyped_variable, AMDDefault);
218}
219
220// Map DWARF source language codes to NonSemantic.Shader.DebugInfo.100 source
221// language codes. Values are from the SourceLanguage enum in the
222// NonSemantic.Shader.DebugInfo.100 specification, section 4.3.
223unsigned SPIRVNonSemanticDebugHandler::toNSDISrcLang(unsigned DwarfSrcLang) {
224 switch (DwarfSrcLang) {
225 case dwarf::DW_LANG_OpenCL:
226 return 3; // OpenCL_C
227 case dwarf::DW_LANG_OpenCL_CPP:
228 return 4; // OpenCL_CPP
229 case dwarf::DW_LANG_CPP_for_OpenCL:
230 return 6; // CPP_for_OpenCL
231 case dwarf::DW_LANG_GLSL:
232 return 2; // GLSL
233 case dwarf::DW_LANG_HLSL:
234 return 5; // HLSL
235 case dwarf::DW_LANG_SYCL:
236 return 7; // SYCL
237 case dwarf::DW_LANG_Zig:
238 return 12; // Zig
239 default:
240 return 0; // Unknown
241 }
242}
243
244static bool isBooleanType(const DIBasicType *BT) {
245 return BT->getEncoding() == dwarf::DW_ATE_boolean;
246}
247
248// \p Value truncated to the width of \p BT, or 0 or 1 for a boolean.
250 // A boolean is one of two values and a DIBasicType may give it no size, so
251 // masking to its width would turn every true into a false.
252 if (isBooleanType(BT))
253 return Value != 0;
254 unsigned Width = BT->getSizeInBits();
255 return Width >= 64 ? Value : Value & ((uint64_t(1) << Width) - 1);
256}
257
258// \p Value truncated to the width of \p BT. APInt::getZExtValue() asserts
259// above 64 bits, so the truncation comes first.
261 unsigned Width = isBooleanType(BT) ? 1 : BT->getSizeInBits();
262 return constantBits(Value.getActiveBits() > 64
263 ? Value.trunc(std::min(Width, 64u)).getZExtValue()
264 : Value.getZExtValue(),
265 BT);
266}
267
268// The DIBasicType that \p Ty resolves to through typedefs and qualifiers, or
269// null.
270static const DIBasicType *stripToScalarType(const DIType *Ty) {
271 // visitDIDerivedType accepts a cyclic chain of typedefs and qualifiers, so
272 // this stops once it reaches an already seen type.
274 while (const auto *DT = dyn_cast_or_null<DIDerivedType>(Ty)) {
275 unsigned Tag = DT->getTag();
276 if ((Tag != dwarf::DW_TAG_typedef && !mapTypeQualifierTag(Tag)) ||
277 !Seen.insert(DT).second)
278 return nullptr;
279 Ty = DT->getBaseType();
280 }
281
282 const auto *BT = dyn_cast_or_null<DIBasicType>(Ty);
283 if (!BT)
284 return nullptr;
285
286 // OpTypeBool carries no width, so a boolean of any size is accepted.
287 if (isBooleanType(BT))
288 return BT;
289
290 unsigned Size = BT->getSizeInBits();
291 switch (BT->getEncoding()) {
292 case dwarf::DW_ATE_signed:
293 case dwarf::DW_ATE_unsigned:
294 case dwarf::DW_ATE_signed_char:
295 case dwarf::DW_ATE_unsigned_char:
296 return Size == 8 || Size == 16 || Size == 32 || Size == 64 ? BT : nullptr;
297 case dwarf::DW_ATE_float:
298 // SPIR-V has no 8-bit float.
299 return Size == 16 || Size == 32 || Size == 64 ? BT : nullptr;
300 default:
301 return nullptr;
302 }
303}
304
305// Collect distinct DILocations and DILocalVariables from LLVM IR.
306//
307// DILocations come from instruction debug locations and from the debug records
308// attached to them. DebugLine pre-emission and MIR lookups assume every
309// machine-instruction debug location already appeared here; a codegen-only
310// location would not be collected and emission will be skipped.
311//
312// DILocalVariables come from the DbgVariableRecords attached to instructions
313// and from the retained nodes of each DISubprogram. Retained nodes are needed
314// because a variable with no remaining debug record (e.g. optimized away) must
315// still get a DebugLocalVariable.
317 const Module &M, SetVector<const DILocation *> &Locations,
319 for (const Function &F : M) {
320 const DISubprogram *SP = F.getSubprogram();
321 if (!SP)
322 continue;
323 for (const MDNode *N : SP->getRetainedNodes())
324 if (const auto *LV = dyn_cast_or_null<DILocalVariable>(N))
325 LVs.insert(LV);
326 for (const Instruction &I : instructions(F)) {
327 if (const DILocation *DL = I.getDebugLoc().get())
328 Locations.insert(DL);
329 for (DbgRecord &DR : I.getDbgRecordRange()) {
330 if (const DILocation *DL = DR.getDebugLoc().get())
331 Locations.insert(DL);
332 if (const auto *DVR = dyn_cast<DbgVariableRecord>(&DR))
333 if (const DILocalVariable *LV = DVR->getVariable())
334 LVs.insert(LV);
335 }
336 }
337 }
338}
339
340// Insert \p S and its enclosing DILexicalBlock/DINamespace/DILexicalBlockFile
341// chain into \p Out, parent before child, so single-pass emission never needs
342// a forward reference for the Parent operand.
345 // Walk up child-first, then insert in reverse to get parents in first.
347 while (S && !Out.contains(S) &&
349 Chain.push_back(S);
350 S = S->getScope();
351 }
352 Out.insert(Chain.rbegin(), Chain.rend());
353}
354
356 // The base class sets Asm = nullptr when the module has no compile units,
357 // and initializes lexical scope tracking otherwise.
359
360 if (!Asm)
361 return;
362
363 CompileUnits.clear();
364 DebugTypes.clear();
365 EnumCompileUnits.clear();
366 Subprograms.clear();
367 UniqueDebugLocations.clear();
368 GlobalVariableDebugInfoMap.clear();
369 LocalVariables.clear();
370 DebugLocalVariableRegs.clear();
371 DebugExpressionRegs.clear();
372 LexicalBlocks.clear();
373 DebugScopeRegs.clear();
374 ScopesInProgress.clear();
375 CanUseForwardRefs = false;
376 UsedForwardRefs = false;
377 PendingStrings.clear();
378 PendingGlobalDI.clear();
379 PendingSink = nullptr;
380 FailedScopes.clear();
381 DebugInlinedAtRegs.clear();
382 ScopeToPathOpStringReg.clear();
383 DebugSourceRegByFileStr.clear();
384 OpStringContentCache.clear();
385 ScalarTypeCache.clear();
386 ScalarConstantCache.clear();
387 ConstantValueRegs.clear();
388 DebugOperationCache.clear();
389 DebugExpressionCache.clear();
390 ModuleScopeIds.clear();
391 GlobalDIEmitted = false;
392 GlobalNSDIEnabled = false;
393 CurrentMAI = nullptr;
394#ifndef NDEBUG
395 DebugStringsGenerated = false;
396#endif
397 CachedDebugInfoNoneReg = MCRegister();
398 CachedEmptyStringReg = MCRegister();
399 CachedOpTypeVoidReg = MCRegister();
400 CachedOpTypeInt32Reg = MCRegister();
401
402 // Collect compile-unit info: file paths and source languages.
403 for (const DICompileUnit *CU : M->debug_compile_units()) {
404 const DIFile *File = CU->getFile();
405 CompileUnitInfo Info;
406 Info.TheCU = CU;
407 if (sys::path::is_absolute(File->getFilename()))
408 Info.FilePath = File->getFilename();
409 else
410 sys::path::append(Info.FilePath, File->getDirectory(),
411 File->getFilename());
412 // getName() returns the language code regardless of whether the name is
413 // versioned. getUnversionedName() would assert on versioned names.
414 Info.SpirvSourceLanguage = toNSDISrcLang(CU->getSourceLanguage().getName());
415 CompileUnits.push_back(std::move(Info));
416 for (const DICompositeType *ET : CU->getEnumTypes())
417 EnumCompileUnits.try_emplace(ET, CU);
418 }
419
420 // Collect DWARF version from module flags. For CodeView modules there is no
421 // "Dwarf Version" flag; DwarfVersion remains 0, which is the correct value
422 // for the DebugCompilationUnit DWARF Version operand in that case.
423 if (const NamedMDNode *Flags = M->getNamedMetadata("llvm.module.flags")) {
424 for (const auto *Op : Flags->operands()) {
425 const MDOperand &NameOp = Op->getOperand(1);
426 if (NameOp.equalsStr("Dwarf Version"))
427 DwarfVersion =
429 cast<ConstantAsMetadata>(Op->getOperand(2))->getValue())
430 ->getSExtValue();
431 }
432 }
433
434 // Find all debug info types that may be referenced by NSDI instructions.
435 // Member types are not roots: each one is emitted only from its composite.
436 DebugInfoFinder Finder;
437 Finder.processModule(*M);
438 copy_if(Finder.types(), std::back_inserter(DebugTypes), [](const DIType *Ty) {
439 return Ty->getTag() != dwarf::DW_TAG_member;
440 });
441
442 Subprograms.assign(Finder.subprograms().begin(), Finder.subprograms().end());
443
444 // Walk LLVM globals to map each DIGlobalVariable to its llvm::GlobalVariable.
446 for (const GlobalVariable &G : M->globals()) {
448 G.getDebugInfo(GVEs);
449 for (DIGlobalVariableExpression *GVE : GVEs) {
450 if (const DIGlobalVariable *GV = GVE->getVariable()) {
451 DIGVToLLVMGV.try_emplace(GV, &G);
452 }
453 }
454 }
455
456 for (const DIGlobalVariableExpression *GVE : Finder.global_variables()) {
457 const DIGlobalVariable *GV = GVE->getVariable();
458 const DIExpression *Expr = GVE->getExpression();
459 GlobalVariableDebugInfoMap.try_emplace(
460 GV, GlobalVariableDebugInfo{Expr, DIGVToLLVMGV.lookup(GV)});
461 }
462
463 collectDebugLocationsAndLocalVariables(*M, UniqueDebugLocations,
464 LocalVariables);
465
466 // DILexicalBlock and DINamespace scopes are lowered to DebugLexicalBlock.
467 // DILexicalBlockFile is lowered to DebugLexicalBlockDiscriminator.
468 // Collect them in parent-before-child order so they can be emitted in a
469 // single pass.
470 for (const DIScope *S : Finder.scopes())
471 collectLexicalBlockChain(S, LexicalBlocks);
472}
473
474// The emitted SPIR-V id of \p MI, or an invalid register when \p MI defines
475// no result.
478 if (MI.getNumOperands() == 0 || !MI.getOperand(0).isReg() ||
479 !MI.getOperand(0).isDef())
480 return MCRegister();
481 return MAI.getRegisterAlias(MI.getMF(), MI.getOperand(0).getReg());
482}
483
486 if (CompileUnits.empty())
487 return;
488 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_non_semantic_info))
489 return;
490
491 // Add the extension to requirements so OpExtension is output.
492 MAI.Reqs.addExtension(SPIRV::Extension::SPV_KHR_non_semantic_info);
493
494 CanUseForwardRefs =
495 UseDebugScopeForwardRefs &&
496 ST.canUseExtension(
497 SPIRV::Extension::SPV_KHR_relaxed_extended_instruction);
498
499 // Add the NonSemantic.Shader.DebugInfo.100 entry to ExtInstSetMap so that
500 // outputOpExtInstImports() emits the OpExtInstImport instruction. Allocate a
501 // fresh result ID for it now; the same ID is used in emitExtInst() operands.
502 if (!MAI.ExtInstSetMap.count(NSSet))
503 MAI.ExtInstSetMap[NSSet] = MAI.getNextIDRegister();
504
506 if (MCRegister Id = getResultId(*MI, MAI))
507 ModuleScopeIds.insert(Id);
508 }
509}
510
511void SPIRVNonSemanticDebugHandler::emitMCInst(MCInst &Inst) {
512 if (PendingSink) {
513 PendingSink->push_back(Inst);
514 return;
515 }
516 Asm->OutStreamer->emitInstruction(Inst, Asm->getSubtargetInfo());
517}
518
519void SPIRVNonSemanticDebugHandler::flushPendingInsts(
521 for (MCInst &Inst : Insts)
522 emitMCInst(Inst);
523 Insts.clear();
524}
525
527SPIRVNonSemanticDebugHandler::emitOpString(StringRef S,
529 MCRegister Reg = MAI.getNextIDRegister();
530 MCInst Inst;
531 Inst.setOpcode(SPIRV::OpString);
533 addStringImm(S, Inst);
534 emitMCInst(Inst);
535 return Reg;
536}
537
538MCRegister SPIRVNonSemanticDebugHandler::emitOpStringIfNew(
540#ifndef NDEBUG
541 assert(!DebugStringsGenerated &&
542 "emitOpStringIfNew is only valid while generating NSDI OpStrings");
543#endif
544 auto [It, Inserted] = OpStringContentCache.try_emplace(S, MCRegister());
545 if (Inserted)
546 It->second = emitOpString(S, MAI);
547
548 return It->second;
549}
550
551MCRegister SPIRVNonSemanticDebugHandler::getCachedOpStringReg(StringRef S) {
552#ifndef NDEBUG
553 assert(DebugStringsGenerated &&
554 "getCachedOpStringReg requires generateDebugStrings() first");
555#endif
556 auto It = OpStringContentCache.find(S);
557 assert(It != OpStringContentCache.end() &&
558 "NSDI OpString missing from cache; generateDebugStrings must cache "
559 "every string used in section 10");
560 return It->second;
561}
562
563MCRegister SPIRVNonSemanticDebugHandler::emitAndCacheScopePathOpStringReg(
564 const DIScope *Scope, SPIRV::ModuleAnalysisInfo &MAI) {
565 auto [It, Inserted] = ScopeToPathOpStringReg.try_emplace(Scope, MCRegister());
566 if (Inserted)
567 It->second = emitOpStringIfNew(getDebugFullPath(Scope), MAI);
568 return It->second;
569}
570
571MCRegister SPIRVNonSemanticDebugHandler::getCachedScopePathOpStringReg(
572 const DIScope *Scope, bool UseEmptyPathIfNullScope) {
573 if (!Scope) {
574 assert(UseEmptyPathIfNullScope &&
575 "null scope path lookup requires UseEmptyPathIfNullScope");
576 assert(CachedEmptyStringReg.isValid() &&
577 "empty path OpString must be cached in generateDebugStrings");
578 return CachedEmptyStringReg;
579 }
580 auto It = ScopeToPathOpStringReg.find(Scope);
581 assert(It != ScopeToPathOpStringReg.end() &&
582 "path OpString must be cached in generateDebugStrings");
583 MCRegister FileStrReg = It->second;
584 assert(FileStrReg.isValid() && "path OpString id must be valid once cached");
585 return FileStrReg;
586}
587
588MCRegister SPIRVNonSemanticDebugHandler::emitOpConstantI32(
589 uint32_t Value, MCRegister I32TypeReg, SPIRV::ModuleAnalysisInfo &MAI) {
590 return findOrEmitConstant(SPIRV::OpConstantI, I32TypeReg, Value,
591 /*Width=*/32, MAI);
592}
593
594bool SPIRVNonSemanticDebugHandler::markForwardReferencedOperands(
596 bool HasForwardRef = false;
597 for (auto &Entry : ScopesInProgress) {
598 InProgressScope &InProgress = Entry.second;
599 assert(InProgress.Id.isValid() &&
600 "in-progress scope must have a reserved id");
601 if (!is_contained(Operands, InProgress.Id))
602 continue;
603 InProgress.ForwardReferenced = true;
604 HasForwardRef = true;
605 }
606 return HasForwardRef;
607}
608
609MCRegister SPIRVNonSemanticDebugHandler::emitExtInst(
610 SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
611 MCRegister VoidTypeReg, MCRegister ExtInstSetReg,
613 std::optional<MCRegister> ResultReg) {
614 assert((!ResultReg || ResultReg->isValid()) &&
615 "ResultReg must be a valid id when provided");
616 MCRegister Reg = ResultReg ? *ResultReg : MAI.getNextIDRegister();
617
618 // An operand that is still an in-progress scope id is a forward reference.
619 // Tag the instruction with OpExtInstWithForwardRefsKHR and remember the id:
620 // if that scope later fails, the id still needs a definition.
621 bool HasForwardRef =
622 CanUseForwardRefs && markForwardReferencedOperands(Operands);
623 assert((!HasForwardRef || PendingSink) &&
624 "forward reference built after OpExtension was printed");
625 UsedForwardRefs |= HasForwardRef;
626
627 MCInst Inst;
628 Inst.setOpcode(HasForwardRef ? SPIRV::OpExtInstWithForwardRefsKHR
629 : SPIRV::OpExtInst);
631 Inst.addOperand(MCOperand::createReg(VoidTypeReg));
632 Inst.addOperand(MCOperand::createReg(ExtInstSetReg));
633 Inst.addOperand(MCOperand::createImm(static_cast<int64_t>(Opcode)));
634 for (MCRegister R : Operands)
636 emitMCInst(Inst);
637 return Reg;
638}
639
640MCRegister SPIRVNonSemanticDebugHandler::getOrEmitOpTypeVoidReg(
642 if (!CachedOpTypeVoidReg.isValid())
643 CachedOpTypeVoidReg = findOrEmitOpTypeVoid(MAI);
644 return CachedOpTypeVoidReg;
645}
646
647MCRegister SPIRVNonSemanticDebugHandler::getOrEmitOpTypeInt32Reg(
649 if (!CachedOpTypeInt32Reg.isValid())
650 CachedOpTypeInt32Reg = findOrEmitOpTypeInt32(MAI);
651 return CachedOpTypeInt32Reg;
652}
653
654MCRegister SPIRVNonSemanticDebugHandler::findOrEmitOpTypeVoid(
656 for (const MachineInstr *MI : MAI.getMSInstrs(SPIRV::MB_TypeConstVars)) {
657 if (MI->getOpcode() == SPIRV::OpTypeVoid)
658 return MAI.getRegisterAlias(MI->getMF(), MI->getOperand(0).getReg());
659 }
660 MCRegister Reg = MAI.getNextIDRegister();
661 MCInst Inst;
662 Inst.setOpcode(SPIRV::OpTypeVoid);
664 emitMCInst(Inst);
665 return Reg;
666}
667
668// Whether declaring \p BT's SPIR-V type would require a capability. The type
669// width determines the requirement: Int8, Int16, Int64, Float16 and Float64 in
670// SPIRVModuleAnalysis::collectReqs(). A boolean and a 32-bit scalar are free.
672 if (isBooleanType(BT))
673 return false;
674 unsigned Width = BT->getSizeInBits();
675 return Width != 32;
676}
677
678MCRegister SPIRVNonSemanticDebugHandler::findOrEmitScalarType(
680 bool IsBool = isBooleanType(BT);
681 bool IsFloat = BT->getEncoding() == dwarf::DW_ATE_float;
682 unsigned Opcode = IsBool ? SPIRV::OpTypeBool
683 : IsFloat ? SPIRV::OpTypeFloat
684 : SPIRV::OpTypeInt;
685 // Two DIBasicTypes can describe one SPIR-V type, and OpTypeBool has no
686 // width, so the key is the opcode and the width rather than the node.
687 int64_t Width = IsBool ? 0 : BT->getSizeInBits();
688
689 // OpTypeInt 32 0 is already owned by getOrEmitOpTypeInt32Reg(), which every
690 // line and column constant needs. Declaring a second one is a duplicate type
691 // declaration, which the validator rejects.
692 if (Opcode == SPIRV::OpTypeInt && Width == 32)
693 return getOrEmitOpTypeInt32Reg(MAI);
694
695 auto [CacheIt, Inserted] =
696 ScalarTypeCache.try_emplace({Opcode, Width}, MCRegister());
697 if (!Inserted)
698 return CacheIt->second;
699
700 // The backend writes every integer type with signedness 0, so a signed and
701 // an unsigned DIBasicType of the same width share one OpTypeInt.
702 for (const MachineInstr *MI : MAI.getMSInstrs(SPIRV::MB_TypeConstVars)) {
703 if (MI->getOpcode() != Opcode)
704 continue;
705 if (IsBool || (MI->getOperand(1).getImm() == Width &&
706 (IsFloat || MI->getOperand(2).getImm() == 0))) {
707 CacheIt->second =
708 MAI.getRegisterAlias(MI->getMF(), MI->getOperand(0).getReg());
709 return CacheIt->second;
710 }
711 }
712
713 // A non-semantic instruction "has no semantic impact, and can be safely
714 // removed from the module", so debug info must leave the module's
715 // requirements alone. Declaring OpTypeInt 64 forces Int64, which Vulkan ties
716 // to a device feature, so this returns nothing if the type requires a new
717 // capability.
719 return MCRegister();
720
721 MCRegister Reg = MAI.getNextIDRegister();
722 MCInst Inst;
723 Inst.setOpcode(Opcode);
725 if (!IsBool) {
726 Inst.addOperand(MCOperand::createImm(Width));
727 if (!IsFloat)
729 }
730 emitMCInst(Inst);
731 CacheIt->second = Reg;
732 return Reg;
733}
734
735// Whether the constant \p MI holds \p Value, read as two words when \p IsWide.
737 bool IsWide) {
738 unsigned Words = IsWide ? 2 : 1;
739 if (MI.getNumOperands() < 2 + Words)
740 return false;
741 uint64_t Found = 0;
742 for (unsigned I = 0; I < Words; ++I) {
743 if (!MI.getOperand(2 + I).isImm())
744 return false;
745 Found |= static_cast<uint64_t>(
746 static_cast<uint32_t>(MI.getOperand(2 + I).getImm()))
747 << (32 * I);
748 }
749 return Found == Value;
750}
751
752MCRegister SPIRVNonSemanticDebugHandler::findModuleConstant(
753 unsigned Opcode, MCRegister TypeReg, uint64_t Value, bool IsBool,
754 bool IsWide, SPIRV::ModuleAnalysisInfo &MAI) {
755 for (const MachineInstr *MI : MAI.getMSInstrs(SPIRV::MB_TypeConstVars)) {
756 if (MI->getOpcode() != Opcode || MI->getNumOperands() < 2)
757 continue;
758 if (MAI.getRegisterAlias(MI->getMF(), MI->getOperand(1).getReg()) !=
759 TypeReg)
760 continue;
761 // A boolean holds its value in its opcode, so there is nothing to compare.
762 if (!IsBool && !constantHasValue(*MI, Value, IsWide))
763 continue;
764 return MAI.getRegisterAlias(MI->getMF(), MI->getOperand(0).getReg());
765 }
766 return MCRegister();
767}
768
769// \p Width is 0 for a boolean, whose value lives in \p Opcode.
770MCRegister SPIRVNonSemanticDebugHandler::findOrEmitConstant(
771 unsigned Opcode, MCRegister TypeReg, uint64_t Value, unsigned Width,
773 bool IsBool = Width == 0;
774 bool IsWide = Width == 64;
775
776 auto [CacheIt, Inserted] =
777 ScalarConstantCache.try_emplace({TypeReg.id(), Value}, MCRegister());
778 if (!Inserted)
779 return CacheIt->second;
780
781 MCRegister Found =
782 findModuleConstant(Opcode, TypeReg, Value, IsBool, IsWide, MAI);
783 if (Found.isValid()) {
784 CacheIt->second = Found;
785 return Found;
786 }
787
788 MCRegister Reg = MAI.getNextIDRegister();
789 MCInst Inst;
790 Inst.setOpcode(Opcode);
792 Inst.addOperand(MCOperand::createReg(TypeReg));
793 if (!IsBool) {
794 // OpConstant's Value is "the bit pattern for the constant. Types 32 bits
795 // wide or smaller take one word. Larger types take multiple words, with
796 // low-order words appearing first" (SPIR-V specification, OpConstant).
797 Inst.addOperand(MCOperand::createImm(static_cast<int64_t>(Lo_32(Value))));
798 if (IsWide) {
799 Inst.addOperand(MCOperand::createImm(static_cast<int64_t>(Hi_32(Value))));
800 } else if (Width == 16) {
801 // A 16-bit float takes one word, the same as a 32-bit one, so the text
802 // printer needs the width to pick the right APFloat semantics.
804 }
805 }
806 emitMCInst(Inst);
807 CacheIt->second = Reg;
808 return Reg;
809}
810
811MCRegister SPIRVNonSemanticDebugHandler::findOrEmitScalarConstant(
813 MCRegister TypeReg = findOrEmitScalarType(BT, MAI);
814 if (!TypeReg.isValid())
815 return MCRegister();
816
817 bool IsBool = isBooleanType(BT);
818 bool IsFloat = BT->getEncoding() == dwarf::DW_ATE_float;
819 unsigned Opcode =
820 IsBool ? (Value ? SPIRV::OpConstantTrue : SPIRV::OpConstantFalse)
821 : IsFloat ? SPIRV::OpConstantF
822 : SPIRV::OpConstantI;
823 return findOrEmitConstant(Opcode, TypeReg, Value,
824 IsBool ? 0 : BT->getSizeInBits(), MAI);
825}
826
827MCRegister SPIRVNonSemanticDebugHandler::findOrEmitOpTypeInt32(
829 for (const MachineInstr *MI : MAI.getMSInstrs(SPIRV::MB_TypeConstVars)) {
830 if (MI->getOpcode() == SPIRV::OpTypeInt &&
831 MI->getOperand(1).getImm() == 32 && MI->getOperand(2).getImm() == 0)
832 return MAI.getRegisterAlias(MI->getMF(), MI->getOperand(0).getReg());
833 }
834 MCRegister Reg = MAI.getNextIDRegister();
835 MCInst Inst;
836 Inst.setOpcode(SPIRV::OpTypeInt);
838 Inst.addOperand(MCOperand::createImm(32)); // width
839 Inst.addOperand(MCOperand::createImm(0)); // signedness (unsigned)
840 emitMCInst(Inst);
841 return Reg;
842}
843
844// Each node emits its dependencies first. E.g. for `void f() { struct L; }`,
845// node L emits f, then L. Entering a scope reserves its result id. For
846// `struct S { S *p; }`, S* is a back edge. When forward references are
847// enabled, that id is used with OpExtInstWithForwardRefsKHR, and a later
848// failure defines it as DebugInfoNone only when an emitted instruction already
849// named it. Otherwise the edge is dropped and the reserved id stays unused.
850auto SPIRVNonSemanticDebugHandler::getOrCreateDebugScope(const DIScope *S)
851 -> EmitResult<MCRegister> {
852 if (!S || FailedScopes.contains(S))
853 return EmitResult<MCRegister>::unsupported();
854 if (auto Reg = lookupOptReg(DebugScopeRegs, S))
855 return EmitResult<MCRegister>::emitted(*Reg);
856
857 // Mark the scope node as in progress while its dependencies are
858 // resolved/emitted.
859 auto [InProgressIt, FirstVisit] = ScopesInProgress.try_emplace(S);
860 if (!FirstVisit) { // We hit a back edge, it is not the first insertion.
861 if (!CanUseForwardRefs)
862 return EmitResult<MCRegister>::inProgress(); // No support for forward
863 // refs.
864 // Use the reserved id for the back edge when forward references are
865 // supported.
866 MCRegister ReservedId = InProgressIt->second.Id;
867 assert(ReservedId.isValid() && "in-progress scope must have a reserved id");
868 return EmitResult<MCRegister>::emitted(ReservedId);
869 }
870
871 // Reserve the result id first: a dependency may refer back to this scope.
872 assert(CurrentMAI && "debug scope id allocation requires CurrentMAI");
873 MCRegister Id = CurrentMAI->getNextIDRegister();
874 assert(Id.isValid() && "debug scope id must be a valid register");
875 InProgressIt->second.Id = Id;
876
877 EmitResult<PreparedScope> P = emitDebugScope(S);
878 assert((!CanUseForwardRefs || P.Status != EmitStatus::InProgress) &&
879 "InProgress is only returned when forward references are unsupported");
880 if (!P) {
881 // Emission during recursion updates the container. Look the scope up again.
882 InProgressIt = ScopesInProgress.find(S);
883 assert(InProgressIt != ScopesInProgress.end() &&
884 "scope must stay in progress until its instruction is emitted");
885 bool ForwardReferenced = InProgressIt->second.ForwardReferenced;
886 ScopesInProgress.erase(InProgressIt);
887 // P here is either unsupported or in progress. When forward references are
888 // supported, P can only be unsupported. Define the id only when an
889 // already-emitted instruction named it.
890 if (ForwardReferenced) {
891 assert(CanUseForwardRefs &&
892 "a forward reference requires relaxed extended instructions");
893 assert(P.Status == EmitStatus::Unsupported &&
894 "a forward-referenced scope fails as unsupported");
895 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
896 emitExtInst(SPIRV::NonSemanticExtInst::DebugInfoNone,
897 getOrEmitOpTypeVoidReg(MAI), MAI.getExtInstSetReg(NSSet), {},
898 MAI, Id);
899 }
900
901 // InProgress is a dropped back edge (when forward references are not
902 // supported). Leave it out of FailedScopes so a later walk can retry the
903 // scope. Regardless of forward references, cache unsupported scopes to
904 // avoid retrying them.
905 if (P.Status == EmitStatus::Unsupported)
906 FailedScopes.insert(S);
907 return P.Status == EmitStatus::InProgress
908 ? EmitResult<MCRegister>::inProgress()
909 : EmitResult<MCRegister>::unsupported();
910 }
911
912 // The scope was successfully emitted.
913 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
915 emitExtInst(P.Value->Opcode, getOrEmitOpTypeVoidReg(MAI),
916 MAI.getExtInstSetReg(NSSet), P.Value->Operands, MAI, Id);
917 assert(Reg == Id &&
918 "debug scope result id must reuse the id reserved at entry");
919 ScopesInProgress.erase(S);
920 assert(!GlobalNSDIEnabled &&
921 "debug type or scope created after module-scope NSDI emission");
922 DebugScopeRegs[S] = Reg;
923 return EmitResult<MCRegister>::emitted(Reg);
924}
925
926auto SPIRVNonSemanticDebugHandler::getOrCreateDebugTypeOrNone(const DIType *Ty)
927 -> EmitResult<MCRegister> {
928 if (Ty)
929 return getOrCreateDebugScope(Ty);
930 assert(CachedDebugInfoNoneReg.isValid() &&
931 "DebugInfoNone must be emitted before debug types");
932 return EmitResult<MCRegister>::emitted(CachedDebugInfoNoneReg);
933}
934
935auto SPIRVNonSemanticDebugHandler::emitDebugTypeBasic(
936 const DIBasicType *BT, MCRegister I32TypeReg,
937 SPIRV::ModuleAnalysisInfo &MAI) -> EmitResult<PreparedScope> {
938 if (!isUInt<32>(BT->getSizeInBits()))
939 return EmitResult<PreparedScope>::unsupported();
940
941 MCRegister NameReg = getCachedOpStringReg(BT->getName());
942 MCRegister SizeReg = emitOpConstantI32(
943 static_cast<uint32_t>(BT->getSizeInBits()), I32TypeReg, MAI);
944
945 // Map DWARF base type encodings to NSDI encoding codes per
946 // NonSemantic.Shader.DebugInfo.100 specification, section 4.5.
947 unsigned Encoding = 0; // Unspecified
948 switch (BT->getEncoding()) {
949 case dwarf::DW_ATE_address:
950 Encoding = 1;
951 break;
952 case dwarf::DW_ATE_boolean:
953 Encoding = 2;
954 break;
955 case dwarf::DW_ATE_float:
956 Encoding = 3;
957 break;
958 case dwarf::DW_ATE_signed:
959 Encoding = 4;
960 break;
961 case dwarf::DW_ATE_signed_char:
962 Encoding = 5;
963 break;
964 case dwarf::DW_ATE_unsigned:
965 Encoding = 6;
966 break;
967 case dwarf::DW_ATE_unsigned_char:
968 Encoding = 7;
969 break;
970 }
971 MCRegister EncodingReg = emitOpConstantI32(Encoding, I32TypeReg, MAI);
972 MCRegister FlagsReg = emitOpConstantI32(0, I32TypeReg, MAI);
973 return EmitResult<PreparedScope>::emitted(
974 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeBasic,
975 {NameReg, SizeReg, EncodingReg, FlagsReg}});
976}
977
978auto SPIRVNonSemanticDebugHandler::emitDebugScope(const DIScope *S)
979 -> EmitResult<PreparedScope> {
980 assert(CurrentMAI && "emitDebugScope requires CurrentMAI");
981 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
982 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
983 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
984 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
985
986 if (const auto *BT = dyn_cast<DIBasicType>(S))
987 return emitDebugTypeBasic(BT, I32TypeReg, MAI);
988 if (const auto *ST = dyn_cast<DISubroutineType>(S))
989 return emitDebugTypeFunctionForSubroutineType(ST, MAI);
990 if (const auto *CT = dyn_cast<DICompositeType>(S))
991 return emitDebugTypeForCompositeType(CT, VoidTypeReg, I32TypeReg,
992 ExtInstSetReg, MAI);
993 if (const auto *DT = dyn_cast<DIDerivedType>(S))
994 return emitDebugTypeForDerivedType(DT, VoidTypeReg, I32TypeReg,
995 ExtInstSetReg, MAI);
997 return emitDebugLexicalBlock(S, VoidTypeReg, I32TypeReg, ExtInstSetReg,
998 MAI);
999 if (const auto *LBF = dyn_cast<DILexicalBlockFile>(S))
1000 return emitDebugLexicalBlockDiscriminator(LBF, VoidTypeReg, I32TypeReg,
1001 ExtInstSetReg, MAI);
1002 if (const auto *SP = dyn_cast<DISubprogram>(S)) {
1003 if (SP->isDefinition())
1004 return emitDebugFunction(SP, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1005 return emitDebugFunctionDeclaration(SP, VoidTypeReg, I32TypeReg,
1006 ExtInstSetReg, MAI);
1007 }
1008 return EmitResult<PreparedScope>::unsupported();
1009}
1010
1011auto SPIRVNonSemanticDebugHandler::emitDebugTypeForCompositeType(
1012 const DICompositeType *CT, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1013 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1014 -> EmitResult<PreparedScope> {
1015 switch (CT->getTag()) {
1016 case dwarf::DW_TAG_array_type:
1017 // A vector is an array with DINode::FlagVector. A plain array is the
1018 // same tag without it. A matrix is also lowered to a DW_TAG_array_type
1019 // (two subranges), so it is indistinguishable from a 2D array here and
1020 // is emitted as a DebugTypeArray.
1021 //
1022 // FIXME: Emitting a matrix as a DebugTypeArray is valid but loses the
1023 // matrix shape. DWARF has no matrix tag, so distinguishing a matrix needs
1024 // a new DINode flag analogous to FlagVector, set on the array, plus a way
1025 // to carry column-major vs row-major traits. Array-of-vectors alone would
1026 // not disambiguate a matrix from a genuine array of vectors. Once the
1027 // frontend marks matrices, route them to a DebugTypeMatrix path here.
1028 if (CT->isVector())
1029 return emitDebugTypeVector(CT, MAI);
1030 return emitDebugTypeArray(CT, MAI);
1031 case dwarf::DW_TAG_structure_type:
1032 case dwarf::DW_TAG_class_type:
1033 case dwarf::DW_TAG_union_type:
1034 return emitDebugTypeComposite(CT, VoidTypeReg, I32TypeReg, ExtInstSetReg,
1035 MAI);
1036 case dwarf::DW_TAG_enumeration_type:
1037 return emitDebugTypeEnum(CT, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1038 default:
1039 return EmitResult<PreparedScope>::unsupported();
1040 }
1041}
1042
1043auto SPIRVNonSemanticDebugHandler::emitDebugTypeForDerivedType(
1044 const DIDerivedType *DT, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1045 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1046 -> EmitResult<PreparedScope> {
1047 switch (DT->getTag()) {
1048 case dwarf::DW_TAG_pointer_type:
1049 return emitDebugTypePointer(DT, MAI);
1050 case dwarf::DW_TAG_typedef:
1051 return emitDebugTypedef(DT, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1052 case dwarf::DW_TAG_member:
1053 return emitDebugTypeMember(DT, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1054 default:
1055 if (std::optional<uint32_t> Qualifier = mapTypeQualifierTag(DT->getTag()))
1056 return emitDebugTypeQualifier(DT, *Qualifier, MAI);
1057 return EmitResult<PreparedScope>::unsupported();
1058 }
1059}
1060
1061auto SPIRVNonSemanticDebugHandler::emitDebugTypePointer(
1063 -> EmitResult<PreparedScope> {
1064 // A DWARF address space is required to determine the SPIR-V storage class.
1065 // Skip pointer types that do not carry one.
1066 if (!PT->getDWARFAddressSpace().has_value())
1067 return EmitResult<PreparedScope>::unsupported();
1068
1069 EmitResult<MCRegister> Base = getOrCreateDebugTypeOrNone(PT->getBaseType());
1070 if (!Base)
1071 return EmitResult<PreparedScope>::failure(Base);
1072
1073 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
1074 MCRegister DebugTypePointerFlagsReg =
1075 emitOpConstantI32(transDebugFlags(PT), I32TypeReg, MAI);
1076
1077 // For SPIR-V targets, Clang sets DwarfAddressSpace to the LLVM IR address
1078 // space, which addressSpaceToStorageClass expects.
1079 const auto &ST = static_cast<const SPIRVSubtarget &>(Asm->getSubtargetInfo());
1080 MCRegister StorageClassReg = emitOpConstantI32(
1081 addressSpaceToStorageClass(PT->getDWARFAddressSpace().value(), ST),
1082 I32TypeReg, MAI);
1083
1084 return EmitResult<PreparedScope>::emitted(
1085 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypePointer,
1086 {*Base.Value, StorageClassReg, DebugTypePointerFlagsReg}});
1087}
1088
1089auto SPIRVNonSemanticDebugHandler::emitDebugTypeQualifier(
1090 const DIDerivedType *QT, uint32_t Qualifier, SPIRV::ModuleAnalysisInfo &MAI)
1091 -> EmitResult<PreparedScope> {
1092 EmitResult<MCRegister> Base = getOrCreateDebugTypeOrNone(QT->getBaseType());
1093 if (!Base)
1094 return EmitResult<PreparedScope>::failure(Base);
1095
1096 MCRegister QualifierReg =
1097 emitOpConstantI32(Qualifier, getOrEmitOpTypeInt32Reg(MAI), MAI);
1098 return EmitResult<PreparedScope>::emitted(
1099 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeQualifier,
1100 {*Base.Value, QualifierReg}});
1101}
1102
1103auto SPIRVNonSemanticDebugHandler::emitDebugTypeFunctionForSubroutineType(
1105 -> EmitResult<PreparedScope> {
1106 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
1107 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
1108 MCRegister DebugTypeFunctionFlagsReg =
1109 emitOpConstantI32(transDebugFlags(ST), I32TypeReg, MAI);
1110 DITypeArray TA = ST->getTypeArray();
1112 Ops.push_back(DebugTypeFunctionFlagsReg);
1113 // Empty DI type tuple: no explicit return or parameter slots (hand-written IR
1114 // may use !{}). Emit void-only prototype. Same as SPIRV-LLVM-Translator when
1115 // DISubroutineType::getTypeArray() has zero elements.
1116 if (TA.empty()) {
1117 Ops.push_back(VoidTypeReg);
1118 } else {
1119 for (unsigned I = 0, E = TA.size(); I != E; ++I) {
1120 bool IsReturnType = (I == 0);
1121 EmitResult<MCRegister> Slot =
1122 mapDISignatureTypeToReg(TA[I], VoidTypeReg, IsReturnType);
1123 // No emitted DebugType* id for this slot (e.g., pointer that
1124 // was skipped due missing address space, etc.).
1125 if (!Slot)
1126 return EmitResult<PreparedScope>::failure(Slot);
1127 Ops.push_back(*Slot.Value);
1128 }
1129 }
1130 return EmitResult<PreparedScope>::emitted(
1131 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeFunction, Ops});
1132}
1133
1134// Match SPIRV-LLVM-Translator's selection logic for the Parent operand.
1135auto SPIRVNonSemanticDebugHandler::resolveScope(const DIScope *Scope,
1136 const DICompileUnit *FallbackCU)
1137 -> EmitResult<MCRegister> {
1138 if (!UseLexicalBlockDiscriminatorScope)
1139 while (const auto *LBF = dyn_cast_or_null<DILexicalBlockFile>(Scope))
1140 Scope = LBF->getScope();
1141
1142 // These scopes have their own debug instruction.
1144 DILexicalBlockFile>(Scope))
1145 return getOrCreateDebugScope(Scope);
1146
1147 // For a file, compile-unit, or absent scope, fall back to a compile unit.
1148 auto CUResult = [](std::optional<MCRegister> Reg) {
1149 return Reg ? EmitResult<MCRegister>::emitted(*Reg)
1150 : EmitResult<MCRegister>::unsupported();
1151 };
1152 if (FallbackCU)
1153 return CUResult(lookupOptReg(DebugScopeRegs, FallbackCU));
1154
1155 if (CompileUnits.empty())
1156 return EmitResult<MCRegister>::unsupported();
1157
1158 return CUResult(lookupOptReg(DebugScopeRegs, CompileUnits[0].TheCU));
1159}
1160
1161auto SPIRVNonSemanticDebugHandler::emitDebugLexicalBlock(
1162 const DIScope *S, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1163 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1164 -> EmitResult<PreparedScope> {
1166 "S must be a DILexicalBlock or DINamespace in emitDebugLexicalBlock");
1167 EmitResult<MCRegister> Parent = resolveScope(S->getScope());
1168 if (!Parent)
1169 return EmitResult<PreparedScope>::failure(Parent);
1170
1171 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1172 S->getFile(), /*UseEmptyPathIfNullScope=*/true);
1173 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1174 ExtInstSetReg, MAI);
1175
1177 if (const auto *LB = dyn_cast<DILexicalBlock>(S)) {
1178 MCRegister LineReg = emitOpConstantI32(static_cast<uint32_t>(LB->getLine()),
1179 I32TypeReg, MAI);
1180 MCRegister ColReg = emitOpConstantI32(
1181 static_cast<uint32_t>(LB->getColumn()), I32TypeReg, MAI);
1182 Ops = {SrcReg, LineReg, ColReg, *Parent.Value};
1183 } else {
1184 const auto *NS = cast<DINamespace>(S);
1185 // DINamespace carries no line/column info.
1186 MCRegister LineReg = emitOpConstantI32(0, I32TypeReg, MAI);
1187 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1188 MCRegister NameReg = getCachedOpStringReg(NS->getName());
1189 Ops = {SrcReg, LineReg, ColReg, *Parent.Value, NameReg};
1190 }
1191
1192 return EmitResult<PreparedScope>::emitted(
1193 PreparedScope{SPIRV::NonSemanticExtInst::DebugLexicalBlock, Ops});
1194}
1195
1196auto SPIRVNonSemanticDebugHandler::emitDebugLexicalBlockDiscriminator(
1197 const DILexicalBlockFile *LBF, MCRegister VoidTypeReg,
1198 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
1199 SPIRV::ModuleAnalysisInfo &MAI) -> EmitResult<PreparedScope> {
1200 assert(LBF && "LBF must not be null");
1201 EmitResult<MCRegister> Parent = resolveScope(LBF->getScope());
1202 if (!Parent)
1203 return EmitResult<PreparedScope>::failure(Parent);
1204
1205 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1206 LBF->getFile(), /*UseEmptyPathIfNullScope=*/true);
1207 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1208 ExtInstSetReg, MAI);
1209 MCRegister DiscReg = emitOpConstantI32(
1210 static_cast<uint32_t>(LBF->getDiscriminator()), I32TypeReg, MAI);
1211 return EmitResult<PreparedScope>::emitted(
1212 PreparedScope{SPIRV::NonSemanticExtInst::DebugLexicalBlockDiscriminator,
1213 {SrcReg, DiscReg, *Parent.Value}});
1214}
1215
1216MCRegister SPIRVNonSemanticDebugHandler::getOrEmitDebugInlinedAt(
1217 const DILocation *IA, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1218 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI) {
1219 assert(IA && "IA must not be null in getOrEmitDebugInlinedAt");
1220
1221 if (MCRegister Cached = DebugInlinedAtRegs.lookup(IA))
1222 return Cached;
1223
1224 EmitResult<MCRegister> Scope = resolveScope(IA->getScope());
1225 if (!Scope)
1226 return MCRegister();
1227
1228 MCRegister LineReg =
1229 emitOpConstantI32(static_cast<uint32_t>(IA->getLine()), I32TypeReg, MAI);
1230
1231 SmallVector<MCRegister, 3> Ops{LineReg, *Scope.Value};
1232 // Recurse before building this instruction's operands so an outer
1233 // inlined-at link is always available.
1234 if (const DILocation *Outer = IA->getInlinedAt()) {
1235 MCRegister OuterReg = getOrEmitDebugInlinedAt(
1236 Outer, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1237 if (!OuterReg.isValid())
1238 return MCRegister();
1239 Ops.push_back(OuterReg);
1240 }
1241
1242 MCRegister Reg = emitExtInst(SPIRV::NonSemanticExtInst::DebugInlinedAt,
1243 VoidTypeReg, ExtInstSetReg, Ops, MAI);
1244 DebugInlinedAtRegs[IA] = Reg;
1245 return Reg;
1246}
1247
1248auto SPIRVNonSemanticDebugHandler::emitDebugFunctionDeclaration(
1249 const DISubprogram *SP, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1250 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1251 -> EmitResult<PreparedScope> {
1252 assert(SP && "SP must not be null in emitDebugFunctionDeclaration");
1253 assert(!SP->isDefinition() &&
1254 "SP must not be a definition in emitDebugFunctionDeclaration");
1255
1256 // The IR verifier already enforces that this cannot be null.
1257 EmitResult<MCRegister> FnTy = getOrCreateDebugScope(SP->getType());
1258 if (!FnTy)
1259 return EmitResult<PreparedScope>::failure(FnTy);
1260
1261 EmitResult<MCRegister> Parent = resolveScope(SP->getScope(), SP->getUnit());
1262 if (!Parent)
1263 return EmitResult<PreparedScope>::failure(Parent);
1264
1265 MCRegister FileStrReg = getCachedScopePathOpStringReg(SP);
1266
1267 MCRegister NameReg = getCachedOpStringReg(SP->getName());
1268 MCRegister LinkageReg = getCachedOpStringReg(SP->getLinkageName());
1269 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1270 ExtInstSetReg, MAI);
1271
1272 MCRegister LineReg =
1273 emitOpConstantI32(static_cast<uint32_t>(SP->getLine()), I32TypeReg, MAI);
1274 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1275
1276 uint32_t FlagsVal = transDebugFlags(SP);
1277 // TODO: When composite scopes are DebugFunctionDeclaration parents (available
1278 // in DebugScopeRegs), sync declaration Flags with SPIRV-LLVM-Translator.
1279 FlagsVal &= ~NSDIFlagIsDefinition;
1280 MCRegister FlagsReg = emitOpConstantI32(FlagsVal, I32TypeReg, MAI);
1281
1282 return EmitResult<PreparedScope>::emitted(
1283 PreparedScope{SPIRV::NonSemanticExtInst::DebugFunctionDeclaration,
1284 {NameReg, *FnTy.Value, SrcReg, LineReg, ColReg,
1285 *Parent.Value, LinkageReg, FlagsReg}});
1286}
1287
1288auto SPIRVNonSemanticDebugHandler::emitDebugFunction(
1289 const DISubprogram *SP, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1290 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1291 -> EmitResult<PreparedScope> {
1292 assert(SP && "SP must not be null in emitDebugFunction");
1293 assert(SP->isDefinition() && "SP must be a definition in emitDebugFunction");
1294
1295 EmitResult<MCRegister> FnTy = getOrCreateDebugScope(SP->getType());
1296 if (!FnTy)
1297 return EmitResult<PreparedScope>::failure(FnTy);
1298
1299 EmitResult<MCRegister> Parent = resolveScope(SP->getScope(), SP->getUnit());
1300 if (!Parent)
1301 return EmitResult<PreparedScope>::failure(Parent);
1302
1303 MCRegister NameReg = getCachedOpStringReg(SP->getName());
1304 MCRegister LinkageReg = getCachedOpStringReg(SP->getLinkageName());
1305 MCRegister FileStrReg = getCachedScopePathOpStringReg(SP);
1306 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1307 ExtInstSetReg, MAI);
1308
1309 MCRegister LineReg =
1310 emitOpConstantI32(static_cast<uint32_t>(SP->getLine()), I32TypeReg, MAI);
1311 // LLVM's DISubprogram has no column field but SPIR-V expects one in
1312 // DebugFunction.
1313 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1314 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(SP), I32TypeReg, MAI);
1315 MCRegister ScopeLineReg = emitOpConstantI32(
1316 static_cast<uint32_t>(SP->getScopeLine()), I32TypeReg, MAI);
1317
1318 SmallVector<MCRegister, 10> Ops = {NameReg, *FnTy.Value, SrcReg,
1319 LineReg, ColReg, *Parent.Value,
1320 LinkageReg, FlagsReg, ScopeLineReg};
1321
1322 if (const DISubprogram *Decl = SP->getDeclaration()) {
1323 EmitResult<MCRegister> DeclRes = getOrCreateDebugScope(Decl);
1324 if (DeclRes)
1325 Ops.push_back(*DeclRes.Value);
1326 }
1327
1328 return EmitResult<PreparedScope>::emitted(
1329 PreparedScope{SPIRV::NonSemanticExtInst::DebugFunction, Ops});
1330}
1331
1332auto SPIRVNonSemanticDebugHandler::mapDISignatureTypeToReg(
1333 const DIType *Ty, MCRegister VoidTypeReg, bool ReturnType)
1334 -> EmitResult<MCRegister> {
1335 if (!Ty && ReturnType)
1336 return EmitResult<MCRegister>::emitted(VoidTypeReg);
1337 return getOrCreateDebugTypeOrNone(Ty);
1338}
1339
1340// NonSemantic.Shader.DebugInfo.100 debug operation encodings
1341// (section 4.5, "Debug Operations").
1354
1355static std::optional<NonSemanticDebugOp>
1357 switch (DwarfOp) {
1358 case dwarf::DW_OP_deref:
1360 case dwarf::DW_OP_plus:
1362 case dwarf::DW_OP_minus:
1364 case dwarf::DW_OP_plus_uconst:
1366 case dwarf::DW_OP_bit_piece:
1368 case dwarf::DW_OP_swap:
1370 case dwarf::DW_OP_xderef:
1372 case dwarf::DW_OP_stack_value:
1374 case dwarf::DW_OP_constu:
1378 default:
1379 return std::nullopt;
1380 }
1381}
1382
1383// The DebugOperation operand values for \p Op. Each becomes an OpConstant of
1384// OpTypeInt 32 0, so every argument must fit in 32 bits.
1385static std::optional<SmallVector<uint32_t, 3>>
1387 std::optional<NonSemanticDebugOp> NSOp =
1389 if (!NSOp)
1390 return std::nullopt;
1391
1392 SmallVector<uint32_t, 3> Operands{static_cast<uint32_t>(*NSOp)};
1393 for (unsigned I = 0, E = Op.getNumArgs(); I != E; ++I) {
1394 uint64_t Arg = Op.getArg(I);
1395 if (!isUInt<32>(Arg))
1396 return std::nullopt;
1397 Operands.push_back(static_cast<uint32_t>(Arg));
1398 }
1399 return Operands;
1400}
1401
1402std::optional<MCRegister> SPIRVNonSemanticDebugHandler::emitDebugOperation(
1403 const DIExpression::ExprOperand &Op, MCRegister VoidTypeReg,
1404 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
1406 std::optional<SmallVector<uint32_t, 3>> Key = mapExprOperand(Op);
1407 if (!Key)
1408 return std::nullopt;
1409
1410 auto [It, Inserted] = DebugOperationCache.try_emplace(std::move(*Key));
1411 if (!Inserted)
1412 return It->second;
1413
1415 for (uint32_t V : It->first)
1416 Operands.push_back(emitOpConstantI32(V, I32TypeReg, MAI));
1417 MCRegister Reg = emitExtInst(SPIRV::NonSemanticExtInst::DebugOperation,
1418 VoidTypeReg, ExtInstSetReg, Operands, MAI);
1419 It->second = Reg;
1420 return Reg;
1421}
1422
1423std::optional<MCRegister> SPIRVNonSemanticDebugHandler::emitDebugExpression(
1424 const DIExpression *Expr, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1425 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI) {
1426 assert(Expr && "Expr must not be null in emitDebugExpression");
1427
1428 SmallVector<MCRegister> OperationRegs;
1429 for (const DIExpression::ExprOperand &Op : Expr->expr_ops()) {
1430 std::optional<MCRegister> OpReg =
1431 emitDebugOperation(Op, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1432 if (!OpReg)
1433 return std::nullopt;
1434 OperationRegs.push_back(*OpReg);
1435 }
1436
1437 auto [It, Inserted] =
1438 DebugExpressionCache.try_emplace(std::move(OperationRegs));
1439 if (!Inserted)
1440 return It->second;
1441
1442 MCRegister Reg = emitExtInst(SPIRV::NonSemanticExtInst::DebugExpression,
1443 VoidTypeReg, ExtInstSetReg, It->first, MAI);
1444 It->second = Reg;
1445 return Reg;
1446}
1447
1448std::optional<MCRegister> SPIRVNonSemanticDebugHandler::emitDebugGlobalVariable(
1449 const DIGlobalVariable *GV, const GlobalVariableDebugInfo &Info,
1450 MCRegister VoidTypeReg, MCRegister I32TypeReg, MCRegister ExtInstSetReg,
1452 assert(GV && "GV must not be null in emitDebugGlobalVariable");
1453
1454 EmitResult<MCRegister> Parent = resolveScope(GV->getScope());
1455 if (!Parent)
1456 return std::nullopt;
1457
1458 MCRegister ParentReg = *Parent.Value;
1459
1460 // TyReg: DebugInfoNone when GV has no DI type (as done in
1461 // SPIRV-LLVM-Translator). Declarations (isDefinition: false) can have null
1462 // getType() while definitions must have a non-null one (enforced by the IR
1463 // verifier).
1464 MCRegister TyReg = CachedDebugInfoNoneReg;
1465 if (const DIType *Ty = GV->getType()) {
1466 auto TyRegOpt = lookupOptReg(DebugScopeRegs, Ty);
1467 if (!TyRegOpt)
1468 return std::nullopt;
1469 TyReg = *TyRegOpt;
1470 }
1471
1472 std::optional<MCRegister> StaticMemberRegOpt;
1473 if (const DIDerivedType *SM = GV->getStaticDataMemberDeclaration()) {
1474 // Do not create the member here, just look it up to avoid orphaning it.
1475 StaticMemberRegOpt = lookupOptReg(DebugScopeRegs, SM);
1476 if (!StaticMemberRegOpt)
1477 return std::nullopt;
1478 }
1479
1480 MCRegister NameReg = getCachedOpStringReg(GV->getName());
1481 MCRegister LinkageReg = getCachedOpStringReg(GV->getLinkageName());
1482 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1483 GV->getFile(), /*UseEmptyPathIfNullScope=*/true);
1484 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1485 ExtInstSetReg, MAI);
1486
1487 MCRegister LineReg =
1488 emitOpConstantI32(static_cast<uint32_t>(GV->getLine()), I32TypeReg, MAI);
1489 // DIGlobalVariable or DIGlobalVariableExpression metadata carry no column
1490 // field. Column is hardcoded to 0 (because it can't be determined), matching
1491 // SPIRV-LLVM-Translator.
1492 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1493
1494 // Variable: @g OpVariable id when !dbg matches; else a DebugExpression for
1495 // the GVE init value when no @g exists and the expression is non-empty; else
1496 // DebugInfoNone. As per spec, the DebugExpression must contain the constant
1497 // value of the variable that was optimized out. An empty expression contains
1498 // no value, so we emit DebugInfoNone instead.
1499 MCRegister VariableReg = CachedDebugInfoNoneReg;
1500 if (const GlobalVariable *LLVMGV = Info.LLVMGV) {
1501 MCRegister GVReg = MAI.getGlobalObjReg(LLVMGV);
1502 if (GVReg.isValid())
1503 VariableReg = GVReg;
1504 } else if (Info.Expr && Info.Expr->getNumElements() != 0) {
1505 if (auto ExprReg = emitDebugExpression(Info.Expr, VoidTypeReg, I32TypeReg,
1506 ExtInstSetReg, MAI))
1507 VariableReg = *ExprReg;
1508 }
1509
1510 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(GV), I32TypeReg, MAI);
1511
1512 SmallVector<MCRegister, 10> Ops = {NameReg, TyReg, SrcReg,
1513 LineReg, ColReg, ParentReg,
1514 LinkageReg, VariableReg, FlagsReg};
1515
1516 if (StaticMemberRegOpt)
1517 Ops.push_back(*StaticMemberRegOpt);
1518
1519 return emitExtInst(SPIRV::NonSemanticExtInst::DebugGlobalVariable,
1520 VoidTypeReg, ExtInstSetReg, Ops, MAI);
1521}
1522
1523std::optional<MCRegister> SPIRVNonSemanticDebugHandler::emitDebugLocalVariable(
1524 const DILocalVariable *LV, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1525 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI) {
1526 assert(LV && "LV must not be null in emitDebugLocalVariable");
1527
1528 EmitResult<MCRegister> Parent = resolveScope(LV->getScope());
1529 if (!Parent)
1530 return std::nullopt;
1531
1532 MCRegister TyReg = CachedDebugInfoNoneReg;
1533 if (const DIType *Ty = LV->getType()) {
1534 auto TyRegOpt = lookupOptReg(DebugScopeRegs, Ty);
1535 if (!TyRegOpt)
1536 return std::nullopt;
1537 TyReg = *TyRegOpt;
1538 }
1539
1540 MCRegister NameReg = getCachedOpStringReg(LV->getName());
1541 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1542 LV->getFile(), /*UseEmptyPathIfNullScope=*/true);
1543 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1544 ExtInstSetReg, MAI);
1545 MCRegister LineReg =
1546 emitOpConstantI32(static_cast<uint32_t>(LV->getLine()), I32TypeReg, MAI);
1547 // DILocalVariable has no column field. Column is hardcoded to 0.
1548 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1549 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(LV), I32TypeReg, MAI);
1550
1551 SmallVector<MCRegister, 8> Ops = {NameReg, TyReg, SrcReg, LineReg,
1552 ColReg, *Parent.Value, FlagsReg};
1553 if (unsigned Arg = LV->getArg())
1554 Ops.push_back(emitOpConstantI32(Arg, I32TypeReg, MAI));
1555
1556 return emitExtInst(SPIRV::NonSemanticExtInst::DebugLocalVariable, VoidTypeReg,
1557 ExtInstSetReg, Ops, MAI);
1558}
1559
1560auto SPIRVNonSemanticDebugHandler::emitDebugTypeVector(
1562 -> EmitResult<PreparedScope> {
1563 const auto *BaseTy = dyn_cast_or_null<DIBasicType>(VT->getBaseType());
1564 if (!BaseTy)
1565 return EmitResult<PreparedScope>::unsupported();
1566
1567 // DebugTypeVector models only 1D vectors (multi-subrange types cannot be
1568 // encoded).
1569 DINodeArray Elements = VT->getElements();
1570 if (Elements.size() != 1)
1571 return EmitResult<PreparedScope>::unsupported();
1572 const auto *SR = cast<DISubrange>(Elements[0]);
1573 const auto *CI = dyn_cast_if_present<ConstantInt *>(SR->getCount());
1574 if (!CI)
1575 return EmitResult<PreparedScope>::unsupported();
1576
1577 EmitResult<MCRegister> Base = getOrCreateDebugScope(BaseTy);
1578 if (!Base)
1579 return EmitResult<PreparedScope>::failure(Base);
1580
1581 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
1582 MCRegister CountReg = emitOpConstantI32(
1583 static_cast<uint32_t>(CI->getZExtValue()), I32TypeReg, MAI);
1584 return EmitResult<PreparedScope>::emitted(PreparedScope{
1585 SPIRV::NonSemanticExtInst::DebugTypeVector, {*Base.Value, CountReg}});
1586}
1587
1588auto SPIRVNonSemanticDebugHandler::emitDebugTypeArray(
1590 -> EmitResult<PreparedScope> {
1591 // Unlike DebugTypeVector, the element may be any debug type, not only a
1592 // basic type. Create it first so this array names an id that already exists.
1593 EmitResult<MCRegister> Base = getOrCreateDebugScope(AT->getBaseType());
1594 if (!Base)
1595 return EmitResult<PreparedScope>::failure(Base);
1596
1597 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
1598
1600 Ops.push_back(*Base.Value);
1601
1602 // One component count per DISubrange, in DWARF subrange order. Emit 0 for
1603 // counts that are not a compile-time constant (dynamic arrays). This matches
1604 // OpTypeRuntimeArray.
1605 for (const DINode *Element : AT->getElements()) {
1606 const auto *SR = dyn_cast<DISubrange>(Element);
1607 if (!SR)
1608 continue;
1609 // A DIVariable count (a variable-length array) is not a ConstantInt, so it
1610 // maps to 0 here. DebugTypeArray also allows a DebugLocalVariable or
1611 // DebugGlobalVariable id for it, but no frontend we target emits one. A
1612 // constant wider than 32 bits maps to 0 too, since the count operand is a
1613 // 32-bit OpConstant and such an array cannot occur in a shader.
1614 uint32_t Count = 0;
1615 if (const auto *CI = dyn_cast_if_present<ConstantInt *>(SR->getCount())) {
1616 const APInt &Value = CI->getValue();
1617 if (Value.getActiveBits() <= 32)
1618 Count = static_cast<uint32_t>(Value.getZExtValue());
1619 }
1620 Ops.push_back(emitOpConstantI32(Count, I32TypeReg, MAI));
1621 }
1622
1623 return EmitResult<PreparedScope>::emitted(
1624 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeArray, Ops});
1625}
1626
1627auto SPIRVNonSemanticDebugHandler::emitDebugTypeMember(
1628 const DIDerivedType *M, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1629 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1630 -> EmitResult<PreparedScope> {
1631 EmitResult<MCRegister> Ty = getOrCreateDebugScope(M->getBaseType());
1632 if (!Ty)
1633 return EmitResult<PreparedScope>::failure(Ty);
1634
1635 if (!isUInt<32>(M->getOffsetInBits()) || !isUInt<32>(M->getSizeInBits()))
1636 return EmitResult<PreparedScope>::unsupported();
1637
1638 MCRegister NameReg = getCachedOpStringReg(M->getName());
1639 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1640 M->getFile(), /*UseEmptyPathIfNullScope=*/true);
1641 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1642 ExtInstSetReg, MAI);
1643 MCRegister LineReg =
1644 emitOpConstantI32(static_cast<uint32_t>(M->getLine()), I32TypeReg, MAI);
1645
1646 // DIDerivedType members carry no column, so emit 0.
1647 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1648 MCRegister OffsetReg = emitOpConstantI32(
1649 static_cast<uint32_t>(M->getOffsetInBits()), I32TypeReg, MAI);
1650 MCRegister SizeReg = emitOpConstantI32(
1651 static_cast<uint32_t>(M->getSizeInBits()), I32TypeReg, MAI);
1652 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(M), I32TypeReg, MAI);
1653
1654 // In NonSemantic.Shader.DebugInfo a DebugTypeMember has no Parent operand:
1655 // only the composite references its members. This is by design, it drops the
1656 // Parent that OpenCL.DebugInfo.100 had, and it avoids a composite/member
1657 // reference cycle.
1658 //
1659 // FIXME: Static members are not handled yet: their constant initializer is
1660 // available but is not emitted as the optional Value operand, and under DWARF
1661 // 5 a static member is tagged DW_TAG_variable, which the caller's member loop
1662 // skips.
1663 return EmitResult<PreparedScope>::emitted(
1664 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeMember,
1665 {NameReg, *Ty.Value, SrcReg, LineReg, ColReg, OffsetReg,
1666 SizeReg, FlagsReg}});
1667}
1668
1669auto SPIRVNonSemanticDebugHandler::emitDebugTypeComposite(
1670 const DICompositeType *CT, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1671 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1672 -> EmitResult<PreparedScope> {
1673 // Parent and size before any member: a failure must stream nothing, or a
1674 // retry would emit the members again.
1675 EmitResult<MCRegister> Parent = resolveScope(CT->getScope());
1676 if (!Parent)
1677 return EmitResult<PreparedScope>::failure(Parent);
1678
1679 if (!isUInt<32>(CT->getSizeInBits()))
1680 return EmitResult<PreparedScope>::unsupported();
1681
1682 SmallVector<MCRegister, 8> MemberRegs;
1683 for (const DINode *Element : CT->getElements()) {
1684 const auto *M = dyn_cast<DIDerivedType>(Element);
1685 if (!M || M->getTag() != dwarf::DW_TAG_member)
1686 continue;
1687 EmitResult<MCRegister> Member = getOrCreateDebugScope(M);
1688 if (Member)
1689 MemberRegs.push_back(*Member.Value);
1690 }
1691
1692 MCRegister NameReg = getCachedOpStringReg(CT->getName());
1693 MCRegister LinkageReg = getCachedOpStringReg(CT->getIdentifier());
1694 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1695 CT->getFile(), /*UseEmptyPathIfNullScope=*/true);
1696 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1697 ExtInstSetReg, MAI);
1698
1699 MCRegister TagReg =
1700 emitOpConstantI32(mapCompositeTypeTag(CT->getTag()), I32TypeReg, MAI);
1701 MCRegister LineReg =
1702 emitOpConstantI32(static_cast<uint32_t>(CT->getLine()), I32TypeReg, MAI);
1703 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1704
1705 // A forward declaration has no known size or members: Size is DebugInfoNone.
1706 MCRegister SizeReg = CachedDebugInfoNoneReg;
1707 if (!CT->isForwardDecl())
1708 SizeReg = emitOpConstantI32(static_cast<uint32_t>(CT->getSizeInBits()),
1709 I32TypeReg, MAI);
1710
1711 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(CT), I32TypeReg, MAI);
1712
1713 SmallVector<MCRegister> Ops = {NameReg, TagReg, SrcReg,
1714 LineReg, ColReg, *Parent.Value,
1715 LinkageReg, SizeReg, FlagsReg};
1716 Ops.append(MemberRegs.begin(), MemberRegs.end());
1717 return EmitResult<PreparedScope>::emitted(
1718 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeComposite, Ops});
1719}
1720
1721auto SPIRVNonSemanticDebugHandler::emitDebugTypeEnum(
1722 const DICompositeType *ET, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1723 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1724 -> EmitResult<PreparedScope> {
1725 // Skip incomplete enums.
1726 uint64_t Size = ET->getSizeInBits();
1727 if (Size == 0 || !isUInt<32>(Size))
1728 return EmitResult<PreparedScope>::unsupported();
1729
1730 EmitResult<MCRegister> Underlying =
1731 getOrCreateDebugTypeOrNone(ET->getBaseType());
1732 if (!Underlying)
1733 return EmitResult<PreparedScope>::failure(Underlying);
1734
1735 EmitResult<MCRegister> Parent =
1736 resolveScope(ET->getScope(), EnumCompileUnits.lookup(ET));
1737 if (!Parent)
1738 return EmitResult<PreparedScope>::failure(Parent);
1739
1740 MCRegister NameReg = getCachedOpStringReg(ET->getName());
1741 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1742 ET->getFile(), /*UseEmptyPathIfNullScope=*/true);
1743 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1744 ExtInstSetReg, MAI);
1745 MCRegister LineReg =
1746 emitOpConstantI32(static_cast<uint32_t>(ET->getLine()), I32TypeReg, MAI);
1747 // DICompositeType carries no column, so emit 0.
1748 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1749 MCRegister SizeReg =
1750 emitOpConstantI32(static_cast<uint32_t>(Size), I32TypeReg, MAI);
1751 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(ET), I32TypeReg, MAI);
1752
1753 SmallVector<MCRegister> Ops = {NameReg, *Underlying.Value, SrcReg, LineReg,
1754 ColReg, *Parent.Value, SizeReg, FlagsReg};
1755
1756 // Each Value is a 32-bit integer constant. Skip the Value and Name pair of an
1757 // enumerator whose value needs more bits. Otherwise, the truncation would
1758 // show a different value.
1759 for (const DINode *Element : ET->getElements()) {
1760 const auto *E = dyn_cast<DIEnumerator>(Element);
1761 if (!E)
1762 continue;
1763 const APInt &Value = E->getValue();
1764 if (E->isUnsigned() ? !Value.isIntN(32) : !Value.isSignedIntN(32))
1765 continue;
1766 uint32_t Bits = E->isUnsigned()
1767 ? static_cast<uint32_t>(Value.getZExtValue())
1768 : static_cast<uint32_t>(Value.getSExtValue());
1769 Ops.push_back(emitOpConstantI32(Bits, I32TypeReg, MAI));
1770 Ops.push_back(getCachedOpStringReg(E->getName()));
1771 }
1772
1773 return EmitResult<PreparedScope>::emitted(
1774 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeEnum, Ops});
1775}
1776
1777auto SPIRVNonSemanticDebugHandler::emitDebugTypedef(
1778 const DIDerivedType *TD, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1779 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1780 -> EmitResult<PreparedScope> {
1781 EmitResult<MCRegister> Base = getOrCreateDebugTypeOrNone(TD->getBaseType());
1782 if (!Base)
1783 return EmitResult<PreparedScope>::failure(Base);
1784
1785 MCRegister NameReg = getCachedOpStringReg(TD->getName());
1786 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1787 TD->getFile(), /*UseEmptyPathIfNullScope=*/true);
1788 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1789 ExtInstSetReg, MAI);
1790 MCRegister LineReg =
1791 emitOpConstantI32(static_cast<uint32_t>(TD->getLine()), I32TypeReg, MAI);
1792 // DIDerivedType typedefs carry no column, so emit 0.
1793 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1794
1795 // Parent must be a lexical scope. Valid NSDI lexical scopes are
1796 // DebugCompilationUnit, DebugFunction, DebugLexicalBlock, or
1797 // DebugTypeComposite.
1798 EmitResult<MCRegister> Parent = resolveScope(TD->getScope());
1799 if (!Parent)
1800 return EmitResult<PreparedScope>::failure(Parent);
1801
1802 return EmitResult<PreparedScope>::emitted(PreparedScope{
1803 SPIRV::NonSemanticExtInst::DebugTypedef,
1804 {NameReg, *Base.Value, SrcReg, LineReg, ColReg, *Parent.Value}});
1805}
1806
1809 if (GlobalDIEmitted)
1810 return;
1811 GlobalDIEmitted = true;
1812
1813 if (CompileUnits.empty())
1814 return;
1815 // Check that prepareModuleOutput() registered the extended instruction set.
1816 // If the subtarget does not support the extension, neither strings nor ext
1817 // insts are emitted.
1818 if (!MAI.ExtInstSetMap.contains(NSSet))
1819 return;
1820
1821 generateDebugStrings(MAI);
1822 generateGlobalDebugInfo(MAI);
1823
1824 if (UsedForwardRefs)
1825 MAI.Reqs.addExtension(
1826 SPIRV::Extension::SPV_KHR_relaxed_extended_instruction);
1827}
1828
1831 flushPendingInsts(PendingStrings);
1832}
1833
1836 flushPendingInsts(PendingGlobalDI);
1837}
1838
1839void SPIRVNonSemanticDebugHandler::generateDebugStrings(
1841 SaveAndRestore Sink(PendingSink, &PendingStrings);
1842 for (const CompileUnitInfo &Info : CompileUnits) {
1843 if (Info.TheCU) {
1844 MCRegister PathReg = emitOpStringIfNew(Info.FilePath, MAI);
1845 ScopeToPathOpStringReg[Info.TheCU] = PathReg;
1846 if (const DIFile *F = Info.TheCU->getFile())
1847 ScopeToPathOpStringReg[F] = PathReg;
1848 }
1849 }
1850
1851 for (const DISubprogram *SP : Subprograms) {
1852 emitOpStringIfNew(SP->getName(), MAI);
1853 emitOpStringIfNew(SP->getLinkageName(), MAI);
1854 emitAndCacheScopePathOpStringReg(SP, MAI);
1855 }
1856
1857 for (const DIType *Ty : DebugTypes) {
1858 if (const auto *BT = dyn_cast<DIBasicType>(Ty)) {
1859 emitOpStringIfNew(BT->getName(), MAI);
1860 continue;
1861 }
1862 if (const auto *CT = dyn_cast<DICompositeType>(Ty)) {
1863 // Cache the enum's name, file path and enumerator names as OpStrings for
1864 // DebugTypeEnum.
1865 if (CT->getTag() == dwarf::DW_TAG_enumeration_type) {
1866 emitOpStringIfNew(CT->getName(), MAI);
1867 emitAndCacheScopePathOpStringReg(CT->getFile(), MAI);
1868 for (const DINode *Element : CT->getElements())
1869 if (const auto *E = dyn_cast<DIEnumerator>(Element))
1870 emitOpStringIfNew(E->getName(), MAI);
1871 continue;
1872 }
1873 // Cache the OpStrings each DebugTypeComposite and its DebugTypeMembers
1874 // use: the composite name, identifier (linkage name), and path, plus
1875 // each member name and path. Arrays and vectors have no such strings.
1876 if (CT->getTag() != dwarf::DW_TAG_structure_type &&
1877 CT->getTag() != dwarf::DW_TAG_class_type &&
1878 CT->getTag() != dwarf::DW_TAG_union_type)
1879 continue;
1880 emitOpStringIfNew(CT->getName(), MAI);
1881 emitOpStringIfNew(CT->getIdentifier(), MAI);
1882 emitAndCacheScopePathOpStringReg(CT->getFile(), MAI);
1883 for (const DINode *Element : CT->getElements()) {
1884 const auto *M = dyn_cast<DIDerivedType>(Element);
1885 if (!M || M->getTag() != dwarf::DW_TAG_member)
1886 continue;
1887 emitOpStringIfNew(M->getName(), MAI);
1888 emitAndCacheScopePathOpStringReg(M->getFile(), MAI);
1889 }
1890 continue;
1891 }
1892 // Cache the name and path OpStrings each DebugTypedef uses.
1893 const auto *TD = dyn_cast<DIDerivedType>(Ty);
1894 if (TD && TD->getTag() == dwarf::DW_TAG_typedef) {
1895 emitOpStringIfNew(TD->getName(), MAI);
1896 emitAndCacheScopePathOpStringReg(TD->getFile(), MAI);
1897 }
1898 }
1899
1900 for (const auto &[GV, _] : GlobalVariableDebugInfoMap) {
1901 emitOpStringIfNew(GV->getName(), MAI);
1902 emitOpStringIfNew(GV->getLinkageName(), MAI);
1903 emitAndCacheScopePathOpStringReg(GV->getFile(), MAI);
1904 }
1905
1906 for (const DILocalVariable *LV : LocalVariables) {
1907 emitOpStringIfNew(LV->getName(), MAI);
1908 emitAndCacheScopePathOpStringReg(LV->getFile(), MAI);
1909 }
1910
1911 for (const DIScope *S : LexicalBlocks) {
1912 emitAndCacheScopePathOpStringReg(S->getFile(), MAI);
1913 if (const auto *NS = dyn_cast<DINamespace>(S))
1914 emitOpStringIfNew(NS->getName(), MAI);
1915 }
1916
1917 for (const DILocation *DL : UniqueDebugLocations)
1918 emitAndCacheScopePathOpStringReg(DL->getScope(), MAI);
1919
1920 CachedEmptyStringReg = emitOpStringIfNew("", MAI);
1921
1922#ifndef NDEBUG
1923 DebugStringsGenerated = true;
1924#endif
1925}
1926
1927void SPIRVNonSemanticDebugHandler::emitDebugFunctionDefinition(
1928 MCRegister DebugFunctionReg, MCRegister OpFunctionReg,
1930 assert(DebugFunctionReg.isValid() && OpFunctionReg.isValid() &&
1931 "DebugFunctionDefinition operands must be valid");
1932 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
1933 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
1934 emitExtInst(SPIRV::NonSemanticExtInst::DebugFunctionDefinition, VoidTypeReg,
1935 ExtInstSetReg, {DebugFunctionReg, OpFunctionReg}, MAI);
1936}
1937
1938void SPIRVNonSemanticDebugHandler::resetPerFunctionDebugState() {
1939 CurrentMF = nullptr;
1940 LastFunctionOpVariable = nullptr;
1941 DebugFunctionDefinitionEmitted = false;
1942 LastLineMI = nullptr;
1943 LastScopeMI = nullptr;
1944 Records.clear();
1945}
1946
1947void SPIRVNonSemanticDebugHandler::preparePerFunctionDebug(
1948 const MachineFunction *MF) {
1949 resetPerFunctionDebugState();
1950 if (!GlobalNSDIEnabled || !CurrentMAI)
1951 return;
1952
1953 CurrentMF = MF;
1954
1955 if (MF->getFunction()
1957 .isValid())
1958 return;
1959
1960 const DISubprogram *SP = MF->getFunction().getSubprogram();
1961 if (!SP || !SP->isDefinition())
1962 return;
1963
1964 // DebugFunctionDefinition is emitted after the last function-level
1965 // OpVariable (or OpUntypedVariableKHR). If there are none, it is emitted
1966 // after the entry OpLabel.
1967 LastFunctionOpVariable =
1968 findLastFunctionOpVariableDeclaration(*MF, *CurrentMAI);
1969
1970 analyzeDebugRecords(*MF);
1971}
1972
1973void SPIRVNonSemanticDebugHandler::tryEmitDebugFunctionDefinition(
1975 if (DebugFunctionDefinitionEmitted || !GlobalNSDIEnabled)
1976 return;
1977
1978 assert(CurrentMF && "no current MachineFunction");
1979 const Function &F = CurrentMF->getFunction();
1980 const DISubprogram *SP = F.getSubprogram();
1981 if (!SP || !SP->isDefinition())
1982 return;
1983
1984 auto DFIt = DebugScopeRegs.find(SP);
1985 if (DFIt == DebugScopeRegs.end())
1986 return;
1987
1988 MCRegister OpFunctionReg = MAI.getGlobalObjReg(&F);
1989 if (!OpFunctionReg.isValid())
1990 return;
1991
1992 emitDebugFunctionDefinition(DFIt->second, OpFunctionReg, MAI);
1993 DebugFunctionDefinitionEmitted = true;
1994}
1995
1997 const MachineFunction *MF) {
1998 preparePerFunctionDebug(MF);
1999}
2000
2002 (void)MF;
2003 resetPerFunctionDebugState();
2004}
2005
2007 assert(CurMI == nullptr && "CurMI must be null");
2008 CurMI = MI;
2009
2010 if (!DebugFunctionDefinitionEmitted)
2011 return;
2012
2013 emitAnalyzedRecords(MI);
2014
2015 std::optional<const MachineInstr *> Target = resolveDebugLocTarget(MI);
2016 if (!Target)
2017 return;
2018
2019 (void)emitDebugScopeForInstruction(*Target);
2020 emitDebugLineForInstruction(*Target);
2021}
2022
2023// The register that holds the variable's address in \p MI, or std::nullopt
2024// when \p MI is not a declare this backend can describe.
2025//
2026// The spec requires DebugDeclare's Variable operand to be "the <id> of an
2027// OpVariable instruction that defines the local variable". MIR has no
2028// DBG_DECLARE, so what this looks for is an indirect DBG_VALUE whose location
2029// register an OpVariable defines. \p AllowUntypedVariable allows an exception
2030// and also accepts an OpUntypedVariableKHR.
2031static std::optional<Register>
2032getDebugDeclareStorageReg(const MachineInstr &MI, bool AllowUntypedVariable) {
2033 // #dbg_declare is an indirect DBG_VALUE in MIR; #dbg_value is normally a
2034 // direct one except for the variadic case.
2035 if (!MI.isIndirectDebugValue())
2036 return std::nullopt;
2037
2038 // A variadic #dbg_value becomes DBG_VALUE $noreg, 0, ... which is indirect
2039 // too, and $noreg is not virtual.
2040 Register LocReg = MI.getDebugOperand(0).getReg();
2041 if (!LocReg.isVirtual())
2042 return std::nullopt;
2043
2044 // DebugDeclare can only encode the address of an OpVariable (or
2045 // OpUntypedVariableKHR). Other legitimate #dbg_declare cannot be encoded.
2046 // Examples: an access chain for a field, an OpFunctionParameter for a byval
2047 // argument, or a module-scope constant for a null or fixed address.
2048
2049 // LocReg may also have no def at all: erasing dead storage leaves the
2050 // DBG_VALUE pointing at an undefined register. MachineVerifier permits that
2051 // because LiveDebugVariables normally clears it, but this pipeline has no
2052 // register allocation, so LiveDebugVariables never runs.
2053 const MachineInstr *Def = MI.getMF()->getRegInfo().getUniqueVRegDef(LocReg);
2054 if (!Def || (Def->getOpcode() != SPIRV::OpVariable &&
2055 !(AllowUntypedVariable &&
2056 Def->getOpcode() == SPIRV::OpUntypedVariableKHR)))
2057 return std::nullopt;
2058
2059 return LocReg;
2060}
2061
2062void SPIRVNonSemanticDebugHandler::emitDebugBinding(
2063 SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
2064 const MachineInstr *MI, MCRegister LocationReg) {
2065 assert(DebugFunctionDefinitionEmitted &&
2066 "DebugFunctionDefinition must be emitted");
2067 assert(CurrentMAI && "CurrentMAI must be set");
2068
2069 auto VarRegOpt = lookupOptReg(DebugLocalVariableRegs, MI->getDebugVariable());
2070 if (!VarRegOpt)
2071 return;
2072
2073 auto ExprRegOpt = lookupOptReg(DebugExpressionRegs, MI->getDebugExpression());
2074 if (!ExprRegOpt)
2075 return;
2076
2077 if (!emitDebugScopeForInstruction(MI))
2078 return;
2079 emitDebugLineForInstruction(MI);
2080
2081 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
2082 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
2083 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
2084 emitExtInst(Opcode, VoidTypeReg, ExtInstSetReg,
2085 {*VarRegOpt, LocationReg, *ExprRegOpt}, MAI);
2086}
2087
2088// The scalar type and value of the constant \p MI assigns, or nullopt when
2089// this backend cannot name it.
2090static std::optional<std::pair<const DIBasicType *, uint64_t>>
2092 if (!MI.isNonListDebugValue() || MI.isIndirectDebugValue())
2093 return std::nullopt;
2094
2095 const MachineOperand &Value = MI.getDebugOperand(0);
2096 if (!Value.isImm() && !Value.isCImm() && !Value.isFPImm())
2097 return std::nullopt;
2098
2099 const DILocalVariable *LV = MI.getDebugVariable();
2100 const DIBasicType *BT = LV ? stripToScalarType(LV->getType()) : nullptr;
2101 if (!BT)
2102 return std::nullopt;
2103
2104 uint64_t Bits;
2105 if (Value.isImm())
2106 Bits = constantBits(static_cast<uint64_t>(Value.getImm()), BT);
2107 else if (Value.isCImm())
2108 Bits = constantBits(Value.getCImm()->getValue(), BT);
2109 else
2110 Bits = constantBits(Value.getFPImm()->getValueAPF().bitcastToAPInt(), BT);
2111 return std::make_pair(BT, Bits);
2112}
2113
2114std::optional<MCRegister> SPIRVNonSemanticDebugHandler::getConstantValueReg(
2115 const MachineInstr &MI) const {
2116 std::optional<std::pair<const DIBasicType *, uint64_t>> Const =
2118 if (!Const)
2119 return std::nullopt;
2120
2121 auto It = ConstantValueRegs.find(*Const);
2122 if (It == ConstantValueRegs.end() || !It->second.isValid())
2123 return std::nullopt;
2124 return It->second;
2125}
2126
2127static std::optional<Register> getDebugValueReg(const MachineInstr &MI) {
2128 if (!MI.isNonListDebugValue() || MI.isIndirectDebugValue())
2129 return std::nullopt;
2130
2131 const MachineOperand &Value = MI.getDebugOperand(0);
2132 if (!Value.isReg())
2133 return std::nullopt;
2134
2135 Register ValueReg = Value.getReg();
2136 if (!ValueReg.isVirtual())
2137 return std::nullopt;
2138
2139 const MachineInstr *Def = MI.getMF()->getRegInfo().getUniqueVRegDef(ValueReg);
2140 if (!Def || (Def->isPseudo() && !Def->isPHI()) || Def->isMetaInstruction() ||
2141 Def->getNumOperands() == 0 || !Def->getOperand(0).isReg() ||
2142 !Def->getOperand(0).isDef() || Def->getOperand(0).getReg() != ValueReg)
2143 return std::nullopt;
2144
2145 return ValueReg;
2146}
2147
2148static bool isMergeInstruction(unsigned Opcode) {
2149 return Opcode == SPIRV::OpSelectionMerge || Opcode == SPIRV::OpLoopMerge ||
2150 Opcode == SPIRV::OpLoopControlINTEL;
2151}
2152
2153// Whether \p MI becomes a SPIR-V instruction in the output.
2155 return !MI->isMetaInstruction() && !MAI.getSkipEmission(MI);
2156}
2157
2160 if (!isEmitted(MI, MAI))
2161 return false;
2162 switch (MI->getOpcode()) {
2163 case SPIRV::OpFunction:
2164 case SPIRV::OpFunctionParameter:
2165 case SPIRV::OpFunctionEnd:
2166 case SPIRV::OpLabel:
2167 case TargetOpcode::PHI:
2168 return false;
2169 default:
2170 return true;
2171 }
2172}
2173
2174static const MachineInstr *
2176 SPIRV::ModuleAnalysisInfo &MAI, bool Forward) {
2177 for (const MachineInstr *Adj = Forward ? MI->getNextNode()
2178 : MI->getPrevNode();
2179 Adj; Adj = Forward ? Adj->getNextNode() : Adj->getPrevNode()) {
2180 if (!isEmitted(Adj, MAI))
2181 continue;
2182 return Adj;
2183 }
2184 return nullptr;
2185}
2186
2187std::optional<const MachineInstr *>
2188SPIRVNonSemanticDebugHandler::resolveDebugLocTarget(const MachineInstr *MI) {
2189 assert(CurrentMAI && "CurrentMAI must be set");
2190 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
2191
2192 // Structural opcodes don't require a DebugLine/DebugScope, other opcodes
2193 // might have already been emitted in the module scope.
2194 if (!isDebugLocTarget(MI, MAI))
2195 return std::nullopt;
2196
2197 // DebugLine/DebugScope can be emitted before a merge instruction, but not
2198 // after it (nothing may sit between the merge and its terminator). We can
2199 // use either the merge's or the terminator's debug info; we emit the
2200 // terminator's one.
2201 const MachineInstr *Prev = findAdjacentEmittedInstruction(MI, MAI, false);
2202 if (Prev && isMergeInstruction(Prev->getOpcode()))
2203 return std::nullopt;
2204
2205 if (isMergeInstruction(MI->getOpcode())) {
2206 // Use the terminator's debug info; when we reach it later, the check
2207 // above skips it.
2208 MI = findAdjacentEmittedInstruction(MI, MAI, true);
2209 assert(MI && "Merge instruction must be followed by a terminator");
2210 // The assert is compiled out in a release build, and returning MI there
2211 // would give an engaged optional holding null.
2212 if (!MI)
2213 return std::nullopt;
2214 }
2215
2216 return MI;
2217}
2218
2219void SPIRVNonSemanticDebugHandler::resolveDebugRecord(
2220 const MachineInstr &MI, const MachineInstr *LastEmitted,
2221 const MachineDominatorTree &DomTree) {
2222 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
2223 const MachineFunction &MF = *MI.getMF();
2224
2225 // A record sits at its own position, except in a merge region: nothing may
2226 // be emitted between a merge and its terminator, so it belongs ahead of the
2227 // merge.
2228 const MachineInstr *Anchor =
2229 LastEmitted && isMergeInstruction(LastEmitted->getOpcode()) ? LastEmitted
2230 : &MI;
2231
2232 // A #dbg_declare reaches Machine IR as an indirect DBG_VALUE. Its storage is
2233 // an OpVariable (or OpUntypedVariableKHR) in the entry block, so it is in the
2234 // output by the time any record naming it is reached.
2235 if (std::optional<Register> LocReg =
2236 getDebugDeclareStorageReg(MI, AllowDebugDeclareUntypedVariable)) {
2237 MCRegister StorageReg = MAI.getRegisterAlias(&MF, *LocReg);
2238 if (StorageReg.isValid())
2239 placeRecord(SPIRV::NonSemanticExtInst::DebugDeclare, MI, StorageReg,
2240 Anchor);
2241 return;
2242 }
2243
2244 if (std::optional<MCRegister> ConstReg = getConstantValueReg(MI)) {
2245 placeRecord(SPIRV::NonSemanticExtInst::DebugValue, MI, *ConstReg, Anchor);
2246 return;
2247 }
2248
2249 std::optional<Register> ValReg = getDebugValueReg(MI);
2250 if (!ValReg)
2251 return;
2252 MCRegister ValueReg = MAI.getRegisterAlias(&MF, *ValReg);
2253 if (!ValueReg.isValid())
2254 return;
2255
2256 // NonSemantic.Shader.DebugInfo states that "Forward references are not
2257 // allowed, to be compliant with SPV_KHR_non_semantic_info", so the id has to
2258 // be in the output already. A module section precedes every function body.
2259 //
2260 // For anything else, SPIR-V requires a definition in a function block to
2261 // dominate a non-phi use, and requires a block to precede every block it
2262 // dominates, so a dominating definition is also one already printed. A
2263 // record naming a definition that does not dominate it is dropped.
2264 const MachineInstr *Def = MF.getRegInfo().getUniqueVRegDef(*ValReg);
2265 if (ModuleScopeIds.contains(ValueReg) ||
2266 (isEmitted(Def, MAI) && DomTree.dominates(Def, &MI)))
2267 placeRecord(SPIRV::NonSemanticExtInst::DebugValue, MI, ValueReg, Anchor);
2268}
2269
2270void SPIRVNonSemanticDebugHandler::analyzeDebugRecords(
2271 const MachineFunction &MF) {
2272 assert(CurrentMAI && "CurrentMAI must be set");
2273
2274 // Built on the first record rather than required as an analysis pass, which
2275 // would build a tree for every SPIR-V compilation.
2276 std::optional<MachineDominatorTree> DomTree;
2277
2278 for (const MachineBasicBlock &MBB : MF) {
2279 const MachineInstr *LastEmitted = nullptr;
2280 for (const MachineInstr &MI : MBB) {
2281 if (MI.isDebugValueLike()) {
2282 if (!DomTree)
2283 DomTree.emplace(const_cast<MachineFunction &>(MF));
2284 resolveDebugRecord(MI, LastEmitted, *DomTree);
2285 }
2286
2287 if (isEmitted(&MI, *CurrentMAI))
2288 LastEmitted = &MI;
2289 }
2290 }
2291}
2292
2293void SPIRVNonSemanticDebugHandler::placeRecord(
2294 SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
2295 const MachineInstr &MI, MCRegister LocationReg,
2296 const MachineInstr *Anchor) {
2297 Records[Anchor].push_back({&MI, Opcode, LocationReg});
2298}
2299
2300void SPIRVNonSemanticDebugHandler::emitAnalyzedRecords(
2301 const MachineInstr *Anchor) {
2302 auto It = Records.find(Anchor);
2303 if (It == Records.end())
2304 return;
2305 for (const DebugRecord &R : It->second)
2306 emitDebugBinding(R.Opcode, R.MI, R.LocationReg);
2307}
2308
2309bool SPIRVNonSemanticDebugHandler::emitDebugScopeForInstruction(
2310 const MachineInstr *MI) {
2311 assert(DebugFunctionDefinitionEmitted &&
2312 "DebugFunctionDefinition must be emitted");
2313 assert(CurrentMAI && "CurrentMAI must be set");
2314
2315 // The region is implicitly closed at each basic block boundary, so a
2316 // LastScopeMI from another block must be dropped before it is read below:
2317 // the new block needs its own DebugScope, and has no region left to close.
2318 if (LastScopeMI && MI->getParent() != LastScopeMI->getParent())
2319 LastScopeMI = nullptr;
2320
2321 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
2322 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
2323 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
2324
2325 const DILocation *CurDL = MI->getDebugLoc().get();
2326 if (!CurDL) {
2327 // No location for the current instruction.
2328 if (LastScopeMI) {
2329 // Close the current DebugScope region.
2330 emitExtInst(SPIRV::NonSemanticExtInst::DebugNoScope, VoidTypeReg,
2331 ExtInstSetReg, {}, MAI);
2332 LastScopeMI = nullptr;
2333 }
2334 return true;
2335 }
2336
2337 const DIScope *CurScope = CurDL->getScope();
2338 const DILocation *CurInlinedAt = CurDL->getInlinedAt();
2339
2340 if (LastScopeMI) {
2341 const DILocation *LastDL = LastScopeMI->getDebugLoc().get();
2342 if (LastDL->getScope() == CurScope &&
2343 LastDL->getInlinedAt() == CurInlinedAt)
2344 return true;
2345 }
2346
2347 EmitResult<MCRegister> CurScopeRes = resolveScope(CurScope);
2348 if (!CurScopeRes)
2349 return false;
2350
2351 SmallVector<MCRegister, 2> Ops{*CurScopeRes.Value};
2352 if (CurInlinedAt) {
2353 // If the global emission did not include this inlined-at case, we skip it.
2354 MCRegister InlinedReg = DebugInlinedAtRegs.lookup(CurInlinedAt);
2355 if (!InlinedReg.isValid())
2356 return false;
2357 Ops.push_back(InlinedReg);
2358 }
2359
2360 // A new DebugScope region is needed.
2361 emitExtInst(SPIRV::NonSemanticExtInst::DebugScope, VoidTypeReg, ExtInstSetReg,
2362 Ops, MAI);
2363
2364 LastScopeMI = MI;
2365 return true;
2366}
2367
2368void SPIRVNonSemanticDebugHandler::emitDebugLineForInstruction(
2369 const MachineInstr *MI) {
2370 assert(DebugFunctionDefinitionEmitted &&
2371 "DebugFunctionDefinition must be emitted");
2372 assert(CurrentMAI && "CurrentMAI must be set");
2373
2374 // The region is implicitly closed at each basic block boundary, so a
2375 // LastLineMI from another block must be dropped before it is read below:
2376 // the new block needs its own DebugLine, and has no region left to close.
2377 if (LastLineMI && MI->getParent() != LastLineMI->getParent())
2378 LastLineMI = nullptr;
2379
2380 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
2381 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
2382 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
2383
2384 const DILocation *DL = MI->getDebugLoc().get();
2385 if (!DL) {
2386 // No location for the current instruction
2387 if (LastLineMI) {
2388 // Close the current DebugLine region.
2389 emitExtInst(SPIRV::NonSemanticExtInst::DebugNoLine, VoidTypeReg,
2390 ExtInstSetReg, {}, MAI);
2391 LastLineMI = nullptr;
2392 }
2393 // No DebugLine region to close.
2394 return;
2395 }
2396
2397 // At this point, there is a location for the current instruction.
2398 // If it matches the last emitted DebugLine, no new DebugLine region is
2399 // needed. Otherwise, emit a new DebugLine region and update LastLineMI.
2400
2401 MCRegister FileStrReg = getCachedScopePathOpStringReg(
2402 DL->getScope(), /*UseEmptyPathIfNullScope=*/true);
2403 unsigned Line = DL->getLine();
2404 unsigned Col = DL->getColumn();
2405
2406 unsigned I32TypeId = CachedOpTypeInt32Reg.id();
2407 MCRegister SrcReg = DebugSourceRegByFileStr.lookup(FileStrReg.id());
2408 MCRegister LineReg = ScalarConstantCache.lookup({I32TypeId, Line});
2409 MCRegister ColStartReg = ScalarConstantCache.lookup({I32TypeId, Col});
2410 MCRegister ColEndReg = ScalarConstantCache.lookup({I32TypeId, Col + 1});
2411
2412 // The elements of each collected DILocation (DebugSource, line/column
2413 // constants) are pre-emitted from LLVM-IR instruction !dbg attachments and
2414 // debug-program records; MIR is expected to reuse those same locations (or
2415 // carry none). A lookup miss means codegen attached a source position whose
2416 // elements were never pre-emitted, and debug-line emission is skipped.
2417 if (!SrcReg.isValid() || !LineReg.isValid() || !ColStartReg.isValid() ||
2418 !ColEndReg.isValid())
2419 return;
2420
2421 // Current location matches the last emitted DebugLine region.
2422 if (LastLineMI && MI->getDebugLoc() == LastLineMI->getDebugLoc())
2423 return;
2424
2425 // A new DebugLine region is needed.
2426 emitExtInst(SPIRV::NonSemanticExtInst::DebugLine, VoidTypeReg, ExtInstSetReg,
2427 {SrcReg, LineReg, LineReg, ColStartReg, ColEndReg}, MAI);
2428
2429 LastLineMI = MI;
2430}
2431
2433 const MachineInstr *MI = CurMI;
2434 CurMI = nullptr;
2435
2436 if (!MI || !GlobalNSDIEnabled || !CurrentMF)
2437 return;
2438
2439 if (DebugFunctionDefinitionEmitted || MI != LastFunctionOpVariable)
2440 return;
2441
2442 // If this is the last function-level OpVariable, emit the
2443 // DebugFunctionDefinition. Otherwise, we had already done it before right
2444 // after the OpLabel (see notifyEntryLabelEmitted).
2445 assert(CurrentMAI && "CurrentMAI must be set");
2446 tryEmitDebugFunctionDefinition(*CurrentMAI);
2447}
2448
2450 const MachineFunction &MF) {
2451 if (!GlobalNSDIEnabled || DebugFunctionDefinitionEmitted || !CurrentMF)
2452 return;
2453
2454 assert(CurrentMF == &MF &&
2455 "notification does not match the current MachineFunction");
2456
2457 if (LastFunctionOpVariable)
2458 return;
2459
2460 // If there are no function-level OpVariables, emit the
2461 // DebugFunctionDefinition. Otherwise, DebugFunctionDefinition is emitted
2462 // after the last OpVariable (see endInstruction).
2463 tryEmitDebugFunctionDefinition(*CurrentMAI);
2464}
2465
2466void SPIRVNonSemanticDebugHandler::collectDebugExpressions(
2467 const SPIRV::ModuleAnalysisInfo &MAI,
2469 for (const MachineInstr *MI : MAI.DebugValueMIs)
2470 Out.insert(MI->getDebugExpression());
2471}
2472
2473void SPIRVNonSemanticDebugHandler::generateGlobalDebugInfo(
2475 SaveAndRestore Sink(PendingSink, &PendingGlobalDI);
2476 // Retrieve the ext inst set register allocated by prepareModuleOutput().
2477 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
2478 assert(ExtInstSetReg.isValid() && "NSDI ext inst set must be registered");
2479
2480#ifndef NDEBUG
2481 assert(DebugStringsGenerated &&
2482 "generateDebugStrings() must run before generateGlobalDebugInfo()");
2483#endif
2484
2485 CurrentMAI = &MAI;
2486
2487 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
2488 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
2489
2490 CachedDebugInfoNoneReg = emitExtInst(SPIRV::NonSemanticExtInst::DebugInfoNone,
2491 VoidTypeReg, ExtInstSetReg, {}, MAI);
2492
2493 // Emit integer constants shared across all NSDI instructions. The constant
2494 // cache ensures each value is emitted at most once even when referenced from
2495 // multiple instructions. All constants are pre-emitted before any DebugSource
2496 // so that the output order is: constants, then
2497 // DebugSource+DebugCompilationUnit pairs. This keeps OpConstant instructions
2498 // grouped before the OpExtInst instructions.
2499
2500 // The Version operand of DebugCompilationUnit is the version of the
2501 // NonSemantic.Shader.DebugInfo instruction set, which is 100 for
2502 // "NonSemantic.Shader.DebugInfo.100" (NonSemanticShaderDebugInfo100Version).
2503 MCRegister DebugInfoVersionReg = emitOpConstantI32(100, I32TypeReg, MAI);
2504 MCRegister DwarfVersionReg =
2505 emitOpConstantI32(static_cast<uint32_t>(DwarfVersion), I32TypeReg, MAI);
2506
2507 // Pre-emit source language constants for all compile units before entering
2508 // the DebugSource loop.
2509 SmallVector<MCRegister> SrcLangRegs =
2510 map_to_vector(CompileUnits, [&](const CompileUnitInfo &Info) {
2511 return emitOpConstantI32(Info.SpirvSourceLanguage, I32TypeReg, MAI);
2512 });
2513
2514 // Emit DebugSource and DebugCompilationUnit for each compile unit.
2515 for (auto [Info, SrcLangReg] : llvm::zip(CompileUnits, SrcLangRegs)) {
2516 MCRegister FileStrReg = ScopeToPathOpStringReg.lookup(Info.TheCU);
2517 assert(FileStrReg.isValid() &&
2518 "CU path OpString must be emitted in generateDebugStrings");
2519 MCRegister DebugSourceReg = getOrEmitDebugSourceForFileStrReg(
2520 FileStrReg, VoidTypeReg, ExtInstSetReg, MAI);
2521 MCRegister CUDbgReg = emitExtInst(
2522 SPIRV::NonSemanticExtInst::DebugCompilationUnit, VoidTypeReg,
2523 ExtInstSetReg,
2524 {DebugInfoVersionReg, DwarfVersionReg, DebugSourceReg, SrcLangReg},
2525 MAI);
2526 if (Info.TheCU)
2527 DebugScopeRegs[Info.TheCU] = CUDbgReg;
2528 }
2529
2530 for (const DIScope *S :
2531 concat<const DIScope *const>(LexicalBlocks, DebugTypes, Subprograms))
2532 getOrCreateDebugScope(S);
2533
2534 // Emit DebugLocalVariable after DebugFunction and their lexical blocks so the
2535 // Parent operand can resolve. Record the ids for DebugDeclare.
2536 for (const DILocalVariable *LV : LocalVariables)
2537 if (auto LVReg = emitDebugLocalVariable(LV, VoidTypeReg, I32TypeReg,
2538 ExtInstSetReg, MAI))
2539 DebugLocalVariableRegs[LV] = *LVReg;
2540
2541 // Opcodes like DebugDeclare are part of the function body, but
2542 // DebugExpression is not. For such opcodes, we collect the expressions
2543 // directly from the MIR to avoid inconsistencies with those in the LLVM IR
2544 // module.
2545 SetVector<const DIExpression *> Expressions;
2546 collectDebugExpressions(MAI, Expressions);
2547 for (const DIExpression *Expr : Expressions)
2548 if (auto ExprReg = emitDebugExpression(Expr, VoidTypeReg, I32TypeReg,
2549 ExtInstSetReg, MAI))
2550 DebugExpressionRegs[Expr] = *ExprReg;
2551
2552 // Emit DebugGlobalVariable for each collected DIGlobalVariable.
2553 for (const auto &[GV, Info] : GlobalVariableDebugInfoMap)
2554 emitDebugGlobalVariable(GV, Info, VoidTypeReg, I32TypeReg, ExtInstSetReg,
2555 MAI);
2556
2557 // Emit DebugInlinedAt allowing recursive inlining.
2558 for (const DILocation *DL : UniqueDebugLocations)
2559 if (const DILocation *IA = DL->getInlinedAt())
2560 getOrEmitDebugInlinedAt(IA, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
2561
2562 // Repeating the lookups emitDebugBinding() performs emits a type and a
2563 // constant only for an assignment that will reach a DebugValue.
2564 for (const MachineInstr *MI : MAI.DebugValueMIs) {
2565 std::optional<std::pair<const DIBasicType *, uint64_t>> Const =
2567 if (!Const)
2568 continue;
2569 if (!DebugLocalVariableRegs.contains(MI->getDebugVariable()) ||
2570 !DebugExpressionRegs.contains(MI->getDebugExpression()))
2571 continue;
2572 auto [It, Inserted] = ConstantValueRegs.try_emplace(*Const, MCRegister());
2573 if (Inserted)
2574 It->second = findOrEmitScalarConstant(Const->first, Const->second, MAI);
2575 if (!It->second.isValid())
2576 ConstantValueRegs.erase(It);
2577 }
2578
2579 for (const DILocation *DL : UniqueDebugLocations) {
2580 emitOpConstantI32(DL->getLine(), I32TypeReg, MAI);
2581 emitOpConstantI32(DL->getColumn(), I32TypeReg, MAI);
2582 emitOpConstantI32(DL->getColumn() + 1, I32TypeReg, MAI);
2583 MCRegister FileStrReg =
2584 getCachedScopePathOpStringReg(DL->getScope(),
2585 /*UseEmptyPathIfNullScope=*/true);
2586 getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg, ExtInstSetReg,
2587 MAI);
2588 }
2589
2590 GlobalNSDIEnabled = true;
2591}
2592
2594SPIRVNonSemanticDebugHandler::getDebugFullPath(const DIScope *Scope) const {
2595 SmallString<128> Out;
2596 if (!Scope)
2597 return Out;
2598 StringRef Filename = Scope->getFilename();
2599 const auto Style = sys::path::Style::native;
2600 if (sys::path::is_absolute(Filename, Style))
2601 Out.assign(Filename.begin(), Filename.end());
2602 else {
2603 StringRef Dir = Scope->getDirectory();
2604 Out.assign(Dir.begin(), Dir.end());
2605 sys::path::append(Out, Style, Filename);
2606 }
2607 return Out;
2608}
2609
2610MCRegister SPIRVNonSemanticDebugHandler::getOrEmitDebugSourceForFileStrReg(
2611 MCRegister FileStrReg, MCRegister VoidTypeReg, MCRegister ExtInstSetReg,
2613 const unsigned Key = FileStrReg.id();
2614 auto It = DebugSourceRegByFileStr.find(Key);
2615 if (It != DebugSourceRegByFileStr.end())
2616 return It->second;
2617
2618 MCRegister DS = emitExtInst(SPIRV::NonSemanticExtInst::DebugSource,
2619 VoidTypeReg, ExtInstSetReg, {FileStrReg}, MAI);
2620 DebugSourceRegByFileStr[Key] = DS;
2621 return DS;
2622}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static Error unsupported(const char *Str, const Triple &T)
Definition MachO.cpp:79
BitTracker BT
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains constants used for implementing Dwarf debug support.
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Register Reg
static NVPTX::Scope resolveScope(NVPTX::Scope S, const NVPTXSubtarget *T)
static constexpr StringLiteral Filename
#define P(N)
SI Fold Operands
static const MachineInstr * findAdjacentEmittedInstruction(const MachineInstr *MI, SPIRV::ModuleAnalysisInfo &MAI, bool Forward)
static std::optional< SmallVector< uint32_t, 3 > > mapExprOperand(const DIExpression::ExprOperand &Op)
static bool scalarTypeNeedsCapability(const DIBasicType *BT)
static bool isBooleanType(const DIBasicType *BT)
static bool constantHasValue(const MachineInstr &MI, uint64_t Value, bool IsWide)
static std::optional< Register > getDebugDeclareStorageReg(const MachineInstr &MI, bool AllowUntypedVariable)
static void collectLexicalBlockChain(const DIScope *S, SetVector< const DIScope * > &Out)
static bool isMergeInstruction(unsigned Opcode)
static std::optional< std::pair< const DIBasicType *, uint64_t > > getConstantDbgValueBits(const MachineInstr &MI)
static MCRegister getResultId(const MachineInstr &MI, SPIRV::ModuleAnalysisInfo &MAI)
static bool isEmitted(const MachineInstr *MI, SPIRV::ModuleAnalysisInfo &MAI)
static std::optional< Register > getDebugValueReg(const MachineInstr &MI)
static bool isDebugLocTarget(const MachineInstr *MI, SPIRV::ModuleAnalysisInfo &MAI)
static uint64_t constantBits(uint64_t Value, const DIBasicType *BT)
static std::optional< NonSemanticDebugOp > mapDwarfOpToNonSemanticOp(uint64_t DwarfOp)
static const DIBasicType * stripToScalarType(const DIType *Ty)
static void collectDebugLocationsAndLocalVariables(const Module &M, SetVector< const DILocation * > &Locations, SetVector< const DILocalVariable * > &LVs)
spirv structurize SPIRV
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition SPIRVUtils.h:561
This file contains some templates that are useful if you are working with the STL at all.
This file provides utility classes that use RAII to save and restore values.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines less commonly used SmallVector utilities.
Class for arbitrary precision integers.
Definition APInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:93
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:96
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition AsmPrinter.h:108
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:260
Basic type, like 'int' or 'float'.
A lightweight wrapper around an expression operand.
DWARF expression.
iterator_range< expr_op_iterator > expr_ops() const
A pair of DIGlobalVariable and DIExpression.
DIDerivedType * getStaticDataMemberDeclaration() const
StringRef getLinkageName() const
Debug lexical block.
DILocalScope * getScope() const
Get the local scope for this variable.
Debug lexical block.
Tagged DWARF-like metadata node.
LLVM_ABI dwarf::Tag getTag() const
DIFlags
Debug info flags.
Base class for scope-like contexts.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
Type array for a subprogram.
Base class for types.
DIFile * getFile() const
DIScope * getScope() const
DIType * getType() const
unsigned getLine() const
StringRef getName() const
Base class for non-instruction debug metadata records that have positions within IR.
const MachineInstr * CurMI
If nonnull, stores the current machine instruction we're processing.
AsmPrinter * Asm
Target of debug info emission.
void beginModule(Module *M) override
Utility to find all debug info in a module.
Definition DebugInfo.h:102
LLVM_ABI void processModule(const Module &M)
Process entire module and collect debug info anchors.
iterator_range< global_variable_expression_iterator > global_variables() const
Definition DebugInfo.h:152
iterator_range< subprogram_iterator > subprograms() const
Definition DebugInfo.h:150
iterator_range< type_iterator > types() const
Definition DebugInfo.h:156
iterator_range< scope_iterator > scopes() const
Definition DebugInfo.h:158
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
DISubprogram * getSubprogram() const
Get the attached subprogram.
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
void setFlags(unsigned F)
Definition MCInst.h:203
void addOperand(const MCOperand Op)
Definition MCInst.h:214
void setOpcode(unsigned Op)
Definition MCInst.h:200
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:137
static MCOperand createImm(int64_t Val)
Definition MCInst.h:144
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
constexpr bool isValid() const
Definition MCRegister.h:87
constexpr unsigned id() const
Definition MCRegister.h:85
Metadata node.
Definition Metadata.h:1087
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
bool equalsStr(StringRef Str) const
Definition Metadata.h:930
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A tuple of MDNodes.
Definition Metadata.h:1806
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
void beginModule(Module *M) override
Collect compile-unit metadata from the module.
void emitNonSemanticGlobalDebugInfo(SPIRV::ModuleAnalysisInfo &)
Output the module-scope NSDI built by generateModuleDebugInfo().
void emitNonSemanticDebugStrings(SPIRV::ModuleAnalysisInfo &)
Output the NSDI OpStrings built by generateModuleDebugInfo() into the debug section (section 7 of the...
void endFunctionImpl(const MachineFunction *MF) override
void beginFunctionImpl(const MachineFunction *MF) override
void prepareModuleOutput(const SPIRVSubtarget &ST, SPIRV::ModuleAnalysisInfo &MAI)
Add SPV_KHR_non_semantic_info extension and NonSemantic.Shader.DebugInfo.100 ext inst set entry to MA...
void generateModuleDebugInfo(SPIRV::ModuleAnalysisInfo &MAI)
Buffer the module-scope NSDI and add SPV_KHR_relaxed_extended_instruction to MAI if a forward referen...
void endInstruction() override
Process end of an instruction.
void notifyEntryLabelEmitted(const MachineFunction &MF)
Called after the synthesized entry OpLabel has been emitted.
const SPIRVOptions & getCLOpts() const
A vector that has set insertion semantics.
Definition SetVector.h:57
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
iterator begin() const
Definition StringRef.h:114
iterator end() const
Definition StringRef.h:116
const Triple & getTargetTriple() const
Target - Wrapper for Target specific information.
VendorType getVendor() const
Get the parsed vendor type of this triple.
Definition Triple.h:524
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
constexpr std::underlying_type_t< E > Underlying(E Val)
Check that Val is in range for E, and return Val cast to E's underlying type.
@ Entry
Definition COFF.h:862
constexpr MCPhysReg SP
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
Definition Dwarf.h:144
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:688
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
This is an optimization pass for GlobalISel generic memory operations.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
void addStringImm(StringRef Str, MCInst &Inst)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1807
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
constexpr bool valueOr(BoolOrDefault X, bool Default)
#define N
MCRegister getExtInstSetReg(unsigned SetNum)
DenseMap< unsigned, MCRegister > ExtInstSetMap
InstrList & getMSInstrs(unsigned MSType)
MCRegister getRegisterAlias(const MachineFunction *MF, Register Reg)
bool getSkipEmission(const MachineInstr *MI)
MCRegister getGlobalObjReg(const GlobalObject *GO)
SmallVector< const MachineInstr * > DebugValueMIs
void addExtension(Extension::Extension ToAdd)
A utility class that uses RAII to save and restore the value of a variable.