Debian Codegraph @

llvm-project/llvm/projects/llvm-spirv/lib/SPIRV/SPIRVToLLVMDbgTran.cpp

raw
1 //===- SPIRVToLLVMDbgTran.cpp - Converts debug info to LLVM -----*- C++ -*-===//
2 //
3 // The LLVM/SPIR-V Translator
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 // Copyright (c) 2018 Intel Corporation. All rights reserved.
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining a
11 // copy of this software and associated documentation files (the "Software"),
12 // to deal with the Software without restriction, including without limitation
13 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
14 // and/or sell copies of the Software, and to permit persons to whom the
15 // Software is furnished to do so, subject to the following conditions:
16 //
17 // Redistributions of source code must retain the above copyright notice,
18 // this list of conditions and the following disclaimers.
19 // Redistributions in binary form must reproduce the above copyright notice,
20 // this list of conditions and the following disclaimers in the documentation
21 // and/or other materials provided with the distribution.
22 // Neither the names of Intel Corporation, nor the names of its
23 // contributors may be used to endorse or promote products derived from this
24 // Software without specific prior written permission.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 // CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
31 // THE SOFTWARE.
32 //
33 //===----------------------------------------------------------------------===//
34 //
35 // This file implements translation of debug info from SPIR-V to LLVM metadata
36 //
37 //===----------------------------------------------------------------------===//
38
39 #include "SPIRVToLLVMDbgTran.h"
40 #include "SPIRV.debug.h"
41 #include "SPIRVEntry.h"
42 #include "SPIRVFunction.h"
43 #include "SPIRVInstruction.h"
44 #include "SPIRVInternal.h"
45 #include "SPIRVReader.h"
46 #include "SPIRVType.h"
47
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/IR/DIBuilder.h"
50 #include "llvm/IR/IntrinsicInst.h"
51 #include "llvm/IR/Module.h"
52
53 using namespace std;
54 using namespace SPIRVDebug::Operand;
55
56 namespace SPIRV {
57
58 static uint64_t getDerivedSizeInBits(const DIType *Ty) {
59 if (auto Size = Ty->getSizeInBits())
60 return Size;
61 if (auto *DT = llvm::dyn_cast<const llvm::DIDerivedType>(Ty))
62 if (auto *BT = llvm::dyn_cast<const llvm::DIType>(DT->getRawBaseType()))
63 return getDerivedSizeInBits(BT);
64 return 0;
65 }
66 SPIRVToLLVMDbgTran::SPIRVToLLVMDbgTran(SPIRVModule *TBM, Module *TM,
67 SPIRVToLLVM *Reader)
68 : BM(TBM), M(TM), SPIRVReader(Reader) {
69 Enable = BM->hasDebugInfo();
70 }
71
72 void SPIRVToLLVMDbgTran::addDbgInfoVersion() {
73 if (!Enable)
74 return;
75 M->addModuleFlag(Module::Warning, "Debug Info Version",
76 DEBUG_METADATA_VERSION);
77 }
78
79 DIFile *SPIRVToLLVMDbgTran::getDIFile(
80 const std::string &FileName,
81 std::optional<DIFile::ChecksumInfo<StringRef>> CS,
82 std::optional<std::string> Source) {
83 return getOrInsert(FileMap, FileName, [=]() {
84 SplitFileName Split(FileName);
85 // Use the first builder from the map to crete DIFile since it's
86 // relations with other debug metadata is not going through DICompileUnit
87 if (!Split.BaseName.empty()) {
88 if (Source.has_value()) {
89 const StringRef SourceRef = StringRef(Source.value());
90 return BuilderMap.begin()->second->createFile(
91 Split.BaseName, Split.Path, CS, SourceRef);
92 }
93 return BuilderMap.begin()->second->createFile(Split.BaseName, Split.Path,
94 CS);
95 }
96 return static_cast<DIFile *>(nullptr);
97 });
98 }
99
100 SPIRVExtInst *SPIRVToLLVMDbgTran::getDbgInst(const SPIRVId Id) {
101 SPIRVEntry *E = BM->getEntry(Id);
102 if (isa<OpExtInst>(E)) {
103 SPIRVExtInst *EI = static_cast<SPIRVExtInst *>(E);
104 if (EI->getExtSetKind() == SPIRV::SPIRVEIS_Debug ||
105 EI->getExtSetKind() == SPIRV::SPIRVEIS_OpenCL_DebugInfo_100 ||
106 EI->getExtSetKind() ==
107 SPIRV::SPIRVEIS_NonSemantic_Shader_DebugInfo_100 ||
108 EI->getExtSetKind() == SPIRV::SPIRVEIS_NonSemantic_Shader_DebugInfo_200)
109 return EI;
110 }
111 return nullptr;
112 }
113
114 // Check if module is generated using NonSemantic.Shader.DebugInfo.XXX
115 // extended instruction set
116 inline bool isNonSemanticDebugInfo(const SPIRVExtInstSetKind Kind) {
117 return (Kind == SPIRVEIS_NonSemantic_Shader_DebugInfo_100 ||
118 Kind == SPIRVEIS_NonSemantic_Shader_DebugInfo_200);
119 }
120
121 // Get integer parameter of debug instruction considering whether it's
122 // Literal or <id> of OpConstant instruction depending on DebugInfo
123 // extended instruction set kind
124 SPIRVWord
125 SPIRVToLLVMDbgTran::getConstantValueOrLiteral(const std::vector<SPIRVWord> &Ops,
126 const SPIRVWord Idx,
127 const SPIRVExtInstSetKind Kind) {
128 if (!isNonSemanticDebugInfo(Kind))
129 return Ops[Idx];
130
131 SPIRVValue *SPVConst = BM->get<SPIRVValue>(Ops[Idx]);
132 assert(isConstantOpCode(SPVConst->getOpCode()) &&
133 "NonSemantic Debug instruction's parameters must be OpConstant");
134 ConstantInt *Const =
135 cast<ConstantInt>(SPIRVReader->transValue(SPVConst, nullptr, nullptr));
136 return Const->getZExtValue();
137 }
138
139 const std::string &SPIRVToLLVMDbgTran::getString(const SPIRVId Id) {
140 SPIRVString *String = BM->get<SPIRVString>(Id);
141 assert(String && "Invalid string");
142 return String->getStr();
143 }
144
145 std::optional<std::string>
146 SPIRVToLLVMDbgTran::getStringSourceContinued(const SPIRVId Id,
147 SPIRVExtInst *DebugInst) {
148 if (!isValidId(Id) || getDbgInst<SPIRVDebug::DebugInfoNone>(Id))
149 return {};
150 std::string Str = BM->get<SPIRVString>(Id)->getStr();
151 using namespace SPIRVDebug::Operand::SourceContinued;
152 for (auto *I : DebugInst->getContinuedInstructions()) {
153 const std::string TmpStr =
154 BM->get<SPIRVString>(I->getArguments()[TextIdx])->getStr();
155 Str.append(TmpStr);
156 }
157 return Str;
158 }
159
160 void SPIRVToLLVMDbgTran::transDbgInfo(const SPIRVValue *SV, Value *V) {
161 // Constant samplers and composites do not have a corresponding
162 // SPIRVInstruction, but they may be mapped to an LLVM Instruction.
163 if (SV->getOpCode() == OpConstantSampler ||
164 SV->getOpCode() == OpConstantComposite)
165 return;
166
167 if (Instruction *I = dyn_cast<Instruction>(V)) {
168 const SPIRVInstruction *SI = static_cast<const SPIRVInstruction *>(SV);
169 I->setDebugLoc(transDebugScope(SI));
170 }
171 }
172
173 DIScope *SPIRVToLLVMDbgTran::getScope(const SPIRVEntry *ScopeInst) {
174 if (ScopeInst->getOpCode() == OpString)
175 return getDIFile(static_cast<const SPIRVString *>(ScopeInst)->getStr());
176 return transDebugInst<DIScope>(static_cast<const SPIRVExtInst *>(ScopeInst));
177 }
178
179 void SPIRVToLLVMDbgTran::appendToSourceLangLiteral(DICompileUnit *CompileUnit,
180 SPIRVWord SourceLang) {
181 if (!M->getModuleFlag("Source Lang Literal")) {
182 M->addModuleFlag(llvm::Module::Warning, "Source Lang Literal",
183 MDTuple::get(M->getContext(), {}));
184 }
185 auto *SourceLangLiteral =
186 dyn_cast<MDTuple>(M->getModuleFlag("Source Lang Literal"));
187
188 // Copy old content
189 SmallVector<Metadata *, 4> Nodes;
190 for (auto &Node : SourceLangLiteral->operands()) {
191 Nodes.push_back(Node);
192 }
193
194 // Add new entry
195 Nodes.push_back(MDTuple::get(
196 M->getContext(), SmallVector<Metadata *, 2>{
197 CompileUnit,
198 ConstantAsMetadata::get(ConstantInt::get(
199 Type::getInt32Ty(M->getContext()), SourceLang)),
200 }));
201
202 // Update
203 M->setModuleFlag(llvm::Module::Warning, "Source Lang Literal",
204 MDTuple::get(M->getContext(), Nodes));
205 }
206
207 DICompileUnit *
208 SPIRVToLLVMDbgTran::transCompilationUnit(const SPIRVExtInst *DebugInst,
209 const std::string CompilerVersion,
210 const std::string Flags) {
211 // Do nothing in case we have already translated the CU (e.g. during
212 // DebugEntryPoint translation)
213 if (BuilderMap[DebugInst->getId()])
214 return cast<DICompileUnit>(DebugInstCache[DebugInst]);
215
216 const SPIRVWordVec &Ops = DebugInst->getArguments();
217
218 using namespace SPIRVDebug::Operand::CompilationUnit;
219 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
220 // We must preserve only one Dwarf version module level metadata
221 // UpgradeDebugInfo from llvm/lib/IR/AutoUpgrade.cpp has already done all
222 // work for us during linking stage leaving a single Dwarf version in the
223 // module
224 if (!M->getModuleFlag("Dwarf Version")) {
225 SPIRVWord DWARFVersion = getConstantValueOrLiteral(
226 Ops, DWARFVersionIdx, DebugInst->getExtSetKind());
227 M->addModuleFlag(llvm::Module::Max, "Dwarf Version", DWARFVersion);
228 }
229 SPIRVWord SourceLang =
230 getConstantValueOrLiteral(Ops, LanguageIdx, DebugInst->getExtSetKind());
231 SPIRVWord OriginalSourceLang = SourceLang;
232 bool InvalidSourceLang = false;
233 if (DebugInst->getExtSetKind() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200) {
234 SourceLang = convertSPIRVSourceLangToDWARFNonSemanticDbgInfo(SourceLang);
235 } else if (isSPIRVSourceLangValid(SourceLang)) {
236 SourceLang = convertSPIRVSourceLangToDWARF(SourceLang);
237 } else {
238 // Some SPIR-V producers generate invalid source language value. In such
239 // case the original value should be preserved in "Source Lang Literal"
240 // module flag for later use by LLVM IR consumers.
241 SourceLang = dwarf::DW_LANG_OpenCL;
242 InvalidSourceLang = true;
243 }
244
245 BuilderMap[DebugInst->getId()] = std::make_unique<DIBuilder>(*M);
246
247 assert(BuilderMap.size() != 0 && "No debug compile units");
248 if (isNonSemanticDebugInfo(DebugInst->getExtSetKind())) {
249 // Only initialize once
250 if (BuilderMap.size() == 1)
251 setBuildIdentifierAndStoragePath();
252
253 // This assertion is a guard/reminder to update the Producer argument to
254 // createCompileUnit() if a new DebugInfo type is ever created
255 assert(DebugInst->getExtSetKind() ==
256 SPIRVEIS_NonSemantic_Shader_DebugInfo_100 ||
257 DebugInst->getExtSetKind() ==
258 SPIRVEIS_NonSemantic_Shader_DebugInfo_200);
259
260 auto *CompileUnit = BuilderMap[DebugInst->getId()]->createCompileUnit(
261 SourceLang, getFile(Ops[SourceIdx]),
262 DebugInst->getExtSetKind() == SPIRVEIS_NonSemantic_Shader_DebugInfo_100
263 ? CompilerVersion
264 : getString(Ops[ProducerIdx]),
265 false, Flags, 0, StoragePath,
266 DICompileUnit::DebugEmissionKind::FullDebug, BuildIdentifier);
267 if (InvalidSourceLang) {
268 appendToSourceLangLiteral(CompileUnit, OriginalSourceLang);
269 }
270 return CompileUnit;
271 }
272
273 // TODO: Remove this workaround once we switch to NonSemantic.Shader.* debug
274 // info by default
275 auto Producer = findModuleProducer();
276 auto *CompileUnit = BuilderMap[DebugInst->getId()]->createCompileUnit(
277 SourceLang, getFile(Ops[SourceIdx]), Producer, false, Flags, 0);
278 if (InvalidSourceLang) {
279 appendToSourceLangLiteral(CompileUnit, OriginalSourceLang);
280 }
281 return CompileUnit;
282 }
283
284 DIBasicType *SPIRVToLLVMDbgTran::transTypeBasic(const SPIRVExtInst *DebugInst) {
285 using namespace SPIRVDebug::Operand::TypeBasic;
286 const SPIRVWordVec &Ops = DebugInst->getArguments();
287 assert((Ops.size() == OperandCountOCL ||
288 Ops.size() == OperandCountNonSemantic) &&
289 "Invalid number of operands");
290 StringRef Name = getString(Ops[NameIdx]);
291 auto Tag = static_cast<SPIRVDebug::EncodingTag>(
292 getConstantValueOrLiteral(Ops, EncodingIdx, DebugInst->getExtSetKind()));
293 unsigned Encoding = SPIRV::DbgEncodingMap::rmap(Tag);
294 if (Encoding == 0)
295 return getDIBuilder(DebugInst).createUnspecifiedType(Name);
296 uint64_t Size = BM->get<SPIRVConstant>(Ops[SizeIdx])->getZExtIntValue();
297 return getDIBuilder(DebugInst).createBasicType(Name, Size, Encoding);
298 }
299
300 DIDerivedType *
301 SPIRVToLLVMDbgTran::transTypeQualifier(const SPIRVExtInst *DebugInst) {
302 using namespace SPIRVDebug::Operand::TypeQualifier;
303 const SPIRVWordVec &Ops = DebugInst->getArguments();
304 assert(Ops.size() == OperandCount && "Invalid number of operands");
305 DIType *BaseTy =
306 transDebugInst<DIType>(BM->get<SPIRVExtInst>(Ops[BaseTypeIdx]));
307 SPIRVWord Tag = SPIRV::DbgTypeQulifierMap::rmap(
308 static_cast<SPIRVDebug::TypeQualifierTag>(getConstantValueOrLiteral(
309 Ops, QualifierIdx, DebugInst->getExtSetKind())));
310 return getDIBuilder(DebugInst).createQualifiedType(Tag, BaseTy);
311 }
312
313 DIType *SPIRVToLLVMDbgTran::transTypePointer(const SPIRVExtInst *DebugInst) {
314 using namespace SPIRVDebug::Operand::TypePointer;
315 const SPIRVWordVec &Ops = DebugInst->getArguments();
316 assert(Ops.size() == OperandCount && "Invalid number of operands");
317 DIType *PointeeTy = nullptr;
318 if (BM->getEntry(Ops[BaseTypeIdx])->getOpCode() != OpTypeVoid)
319 PointeeTy = transDebugInst<DIType>(BM->get<SPIRVExtInst>(Ops[BaseTypeIdx]));
320 std::optional<unsigned> AS;
321 SPIRVWord SC = getConstantValueOrLiteral(Ops, StorageClassIdx,
322 DebugInst->getExtSetKind());
323 if (SC != ~0U) // all ones denote no address space
324 AS = SPIRSPIRVAddrSpaceMap::rmap(static_cast<SPIRVStorageClassKind>(SC));
325 DIType *Ty;
326 SPIRVWord Flags =
327 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
328 if (Flags & SPIRVDebug::FlagIsLValueReference)
329 Ty = getDIBuilder(DebugInst).createReferenceType(
330 dwarf::DW_TAG_reference_type, PointeeTy, 0, 0, AS);
331 else if (Flags & SPIRVDebug::FlagIsRValueReference)
332 Ty = getDIBuilder(DebugInst).createReferenceType(
333 dwarf::DW_TAG_rvalue_reference_type, PointeeTy, 0, 0, AS);
334 else
335 Ty = getDIBuilder(DebugInst).createPointerType(
336 PointeeTy, BM->getAddressingModel() * 32, 0, AS);
337
338 if (Flags & SPIRVDebug::FlagIsObjectPointer)
339 Ty = getDIBuilder(DebugInst).createObjectPointerType(Ty);
340 else if (Flags & SPIRVDebug::FlagIsArtificial)
341 Ty = getDIBuilder(DebugInst).createArtificialType(Ty);
342
343 return Ty;
344 }
345
346 DICompositeType *
347 SPIRVToLLVMDbgTran::transTypeArray(const SPIRVExtInst *DebugInst) {
348 if (DebugInst->getExtSetKind() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200)
349 return transTypeArrayNonSemantic(DebugInst);
350
351 // TODO: figure out better naming for transTypeArrayOpenCL since
352 // it also handles SPIRVEIS_NonSemantic_Shader_DebugInfo_100.
353 // Also to consider separating OpenCL from NonSemantic, as OpenCL has several
354 // workarounds
355 return transTypeArrayOpenCL(DebugInst);
356 }
357
358 DICompositeType *
359 SPIRVToLLVMDbgTran::transTypeArrayOpenCL(const SPIRVExtInst *DebugInst) {
360 using namespace SPIRVDebug::Operand::TypeArray;
361 const SPIRVWordVec &Ops = DebugInst->getArguments();
362 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
363 DIType *BaseTy =
364 transNonNullDebugType(BM->get<SPIRVExtInst>(Ops[BaseTypeIdx]));
365 size_t TotalCount = 1;
366 SmallVector<llvm::Metadata *, 8> Subscripts;
367 // Ops looks like: { BaseType, count1|upperBound1, count2|upperBound2, ...,
368 // countN|upperBoundN, lowerBound1, lowerBound2, ..., lowerBoundN }
369 for (size_t I = ComponentCountIdx, E = Ops.size() / 2 + 1; I < E; ++I) {
370 if (auto *LocalVar = getDbgInst<SPIRVDebug::LocalVariable>(Ops[I])) {
371 auto *UpperBound = transDebugInst<DILocalVariable>(LocalVar);
372 SPIRVConstant *C = BM->get<SPIRVConstant>(Ops[Ops.size() / 2 + I]);
373 int64_t ConstantAsInt = static_cast<int64_t>(C->getZExtIntValue());
374 auto *LowerBound = ConstantAsMetadata::get(
375 ConstantInt::get(M->getContext(), APInt(64, ConstantAsInt)));
376 Subscripts.push_back(getDIBuilder(DebugInst).getOrCreateSubrange(
377 nullptr, LowerBound, UpperBound, nullptr));
378 continue;
379 }
380 const SPIRVExtInst *ExprUB, *ExprLB;
381 if ((ExprUB = getDbgInst<SPIRVDebug::Expression>(Ops[I])) &&
382 (ExprLB =
383 getDbgInst<SPIRVDebug::Expression>(Ops[Ops.size() / 2 + I]))) {
384 auto *UpperBound = transDebugInst<DIExpression>(ExprUB);
385 auto *LowerBound = transDebugInst<DIExpression>(ExprLB);
386 Subscripts.push_back(getDIBuilder(DebugInst).getOrCreateSubrange(
387 nullptr, LowerBound, UpperBound, nullptr));
388 continue;
389 }
390 if (!getDbgInst<SPIRVDebug::DebugInfoNone>(Ops[I])) {
391 SPIRVConstant *C = BM->get<SPIRVConstant>(Ops[I]);
392 int64_t Count = static_cast<int64_t>(C->getZExtIntValue());
393 // If the SPIR-V file was generated by an older version of the translator,
394 // Ops may not contain the LowerBound
395 if (Ops.size() / 2 + I < Ops.size()) {
396 C = BM->get<SPIRVConstant>(Ops[Ops.size() / 2 + I]);
397 int64_t LowerBound = static_cast<int64_t>(C->getZExtIntValue());
398 Subscripts.push_back(
399 getDIBuilder(DebugInst).getOrCreateSubrange(LowerBound, Count));
400 } else {
401 auto *CountAsMD = ConstantAsMetadata::get(
402 ConstantInt::get(M->getContext(), APInt(64, Count)));
403 Subscripts.push_back(getDIBuilder(DebugInst).getOrCreateSubrange(
404 CountAsMD, nullptr, nullptr, nullptr));
405 }
406 // Count = -1 means that the array is empty
407 TotalCount *= Count > 0 ? static_cast<size_t>(Count) : 0;
408 continue;
409 }
410 }
411 DINodeArray SubscriptArray =
412 getDIBuilder(DebugInst).getOrCreateArray(Subscripts);
413 size_t Size = getDerivedSizeInBits(BaseTy) * TotalCount;
414 return getDIBuilder(DebugInst).createArrayType(Size, 0 /*align*/, BaseTy,
415 SubscriptArray);
416 }
417
418 DICompositeType *
419 SPIRVToLLVMDbgTran::transTypeArrayNonSemantic(const SPIRVExtInst *DebugInst) {
420 using namespace SPIRVDebug::Operand::TypeArray;
421 const SPIRVWordVec &Ops = DebugInst->getArguments();
422 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
423 DIType *BaseTy =
424 transNonNullDebugType(BM->get<SPIRVExtInst>(Ops[BaseTypeIdx]));
425 size_t TotalCount = 1;
426 SmallVector<llvm::Metadata *, 8> Subscripts;
427 if (DebugInst->getExtOp() == SPIRVDebug::TypeArray) {
428 for (size_t I = SubrangesIdx; I < Ops.size(); ++I) {
429 auto *SR = transDebugInst<DISubrange>(BM->get<SPIRVExtInst>(Ops[I]));
430 // LLVM 15 - exclusive workaround, get from a pointer union seem to be
431 // bugged
432 if (isa<ConstantInt *>(SR->getCount()))
433 if (auto *Count = SR->getCount().get<ConstantInt *>())
434 TotalCount *= Count->getSExtValue() > 0 ? Count->getSExtValue() : 0;
435 Subscripts.push_back(SR);
436 }
437 }
438 DINodeArray SubscriptArray =
439 getDIBuilder(DebugInst).getOrCreateArray(Subscripts);
440 size_t Size = getDerivedSizeInBits(BaseTy) * TotalCount;
441 return getDIBuilder(DebugInst).createArrayType(Size, 0 /*align*/, BaseTy,
442 SubscriptArray);
443 }
444
445 DICompositeType *
446 SPIRVToLLVMDbgTran::transTypeArrayDynamic(const SPIRVExtInst *DebugInst) {
447 using namespace SPIRVDebug::Operand::TypeArrayDynamic;
448 const SPIRVWordVec &Ops = DebugInst->getArguments();
449 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
450 DIType *BaseTy =
451 transNonNullDebugType(BM->get<SPIRVExtInst>(Ops[BaseTypeIdx]));
452 size_t TotalCount = 1;
453 SmallVector<llvm::Metadata *, 8> Subscripts;
454 for (size_t I = SubrangesIdx; I < Ops.size(); ++I) {
455 auto *SR = transDebugInst<DISubrange>(BM->get<SPIRVExtInst>(Ops[I]));
456 // LLVM 15 - exclusive workaround, get from a pointer union seem to be
457 // bugged
458 if (isa<ConstantInt *>(SR->getCount()))
459 if (auto *Count = SR->getCount().get<ConstantInt *>())
460 TotalCount *= Count->getSExtValue() > 0 ? Count->getSExtValue() : 0;
461 Subscripts.push_back(SR);
462 }
463 DINodeArray SubscriptArray =
464 getDIBuilder(DebugInst).getOrCreateArray(Subscripts);
465 size_t Size = getDerivedSizeInBits(BaseTy) * TotalCount;
466
467 auto TransOperand =
468 [&](SPIRVWord Idx) -> PointerUnion<DIExpression *, DIVariable *> {
469 if (!getDbgInst<SPIRVDebug::DebugInfoNone>(Ops[Idx])) {
470 if (const auto *GV = getDbgInst<SPIRVDebug::GlobalVariable>(Ops[Idx]))
471 return transDebugInst<DIGlobalVariable>(GV);
472 if (const auto *LV = getDbgInst<SPIRVDebug::LocalVariable>(Ops[Idx]))
473 return transDebugInst<DILocalVariable>(LV);
474 if (const auto *DIExpr = getDbgInst<SPIRVDebug::Expression>(Ops[Idx]))
475 return transDebugInst<DIExpression>(DIExpr);
476 }
477 return nullptr;
478 };
479 PointerUnion<DIExpression *, DIVariable *> DataLocation =
480 TransOperand(DataLocationIdx);
481 PointerUnion<DIExpression *, DIVariable *> Associated =
482 TransOperand(AssociatedIdx);
483 PointerUnion<DIExpression *, DIVariable *> Allocated =
484 TransOperand(AllocatedIdx);
485 PointerUnion<DIExpression *, DIVariable *> Rank = TransOperand(RankIdx);
486 return getDIBuilder(DebugInst).createArrayType(Size, 0 /*align*/, BaseTy,
487 SubscriptArray, DataLocation,
488 Associated, Allocated, Rank);
489 }
490
491 DICompositeType *
492 SPIRVToLLVMDbgTran::transTypeVector(const SPIRVExtInst *DebugInst) {
493 using namespace SPIRVDebug::Operand::TypeVector;
494 const SPIRVWordVec &Ops = DebugInst->getArguments();
495 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
496 DIType *BaseTy =
497 transNonNullDebugType(BM->get<SPIRVExtInst>(Ops[BaseTypeIdx]));
498 SPIRVWord Count = getConstantValueOrLiteral(Ops, ComponentCountIdx,
499 DebugInst->getExtSetKind());
500 // Round up to a power of two.
501 // OpenCL/SYCL 3-element vectors
502 // occupy the same amount of memory as 4-element vectors
503 // Clang rounds up the memory size of vectors to a power of 2.
504 // Vulkan allows vec3 to have a memory size of 12, but in RenderDoc memory
505 // size is not derived from debug info.
506 uint64_t Size = getDerivedSizeInBits(BaseTy) * llvm::bit_ceil(Count);
507
508 SmallVector<llvm::Metadata *, 8> Subscripts;
509 Subscripts.push_back(getDIBuilder(DebugInst).getOrCreateSubrange(0, Count));
510 DINodeArray SubscriptArray =
511 getDIBuilder(DebugInst).getOrCreateArray(Subscripts);
512
513 return getDIBuilder(DebugInst).createVectorType(Size, 0 /*align*/, BaseTy,
514 SubscriptArray);
515 }
516
517 DICompositeType *
518 SPIRVToLLVMDbgTran::transTypeComposite(const SPIRVExtInst *DebugInst) {
519 using namespace SPIRVDebug::Operand::TypeComposite;
520 const SPIRVWordVec &Ops = DebugInst->getArguments();
521 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
522
523 StringRef Name = getString(Ops[NameIdx]);
524 DIFile *File = getFile(Ops[SourceIdx]);
525 SPIRVWord LineNo =
526 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
527 DIScope *ParentScope = getScope(BM->getEntry(Ops[ParentIdx]));
528
529 uint64_t Size = 0;
530 SPIRVEntry *SizeEntry = BM->getEntry(Ops[SizeIdx]);
531 if (!(SizeEntry->isExtInst(SPIRVEIS_Debug, SPIRVDebug::DebugInfoNone) ||
532 SizeEntry->isExtInst(SPIRVEIS_OpenCL_DebugInfo_100,
533 SPIRVDebug::DebugInfoNone) ||
534 SizeEntry->isExtInst(SPIRVEIS_NonSemantic_Shader_DebugInfo_200,
535 SPIRVDebug::DebugInfoNone))) {
536 Size = BM->get<SPIRVConstant>(Ops[SizeIdx])->getZExtIntValue();
537 }
538
539 uint64_t Align = 0;
540 DIType *DerivedFrom = nullptr;
541 StringRef Identifier;
542 SPIRVEntry *UniqId = BM->get<SPIRVEntry>(Ops[LinkageNameIdx]);
543 if (UniqId->getOpCode() == OpString)
544 Identifier = static_cast<SPIRVString *>(UniqId)->getStr();
545
546 DINode::DIFlags Flags = DINode::FlagZero;
547 SPIRVWord SPIRVFlags =
548 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
549 if (SPIRVFlags & SPIRVDebug::FlagIsFwdDecl)
550 Flags |= DINode::FlagFwdDecl;
551 if (SPIRVFlags & SPIRVDebug::FlagTypePassByValue)
552 Flags |= DINode::FlagTypePassByValue;
553 if (SPIRVFlags & SPIRVDebug::FlagTypePassByReference)
554 Flags |= DINode::FlagTypePassByReference;
555
556 DICompositeType *CT = nullptr;
557 switch (getConstantValueOrLiteral(Ops, TagIdx, DebugInst->getExtSetKind())) {
558 case SPIRVDebug::Class:
559 // TODO: should be replaced with createClassType, when bug with creating
560 // ClassType with llvm::dwarf::DW_TAG_struct_type tag will be fixed
561 CT = getDIBuilder(DebugInst).createReplaceableCompositeType(
562 llvm::dwarf::DW_TAG_class_type, Name, ParentScope, File, LineNo, 0,
563 Size, Align, Flags, Identifier);
564 CT = llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(CT));
565 break;
566 case SPIRVDebug::Structure:
567 CT = getDIBuilder(DebugInst).createStructType(
568 ParentScope, Name, File, LineNo, Size, Align, Flags, DerivedFrom,
569 DINodeArray() /*elements*/, 0 /*RunTimeLang*/, nullptr /*VTableHolder*/,
570 Identifier);
571 break;
572 case SPIRVDebug::Union:
573 CT = getDIBuilder(DebugInst).createUnionType(
574 ParentScope, Name, File, LineNo, Size, Align, Flags, DINodeArray(),
575 0 /*RuntimrLang*/, Identifier);
576 break;
577 default:
578 llvm_unreachable("Unexpected composite type");
579 break;
580 }
581 DebugInstCache[DebugInst] = CT;
582 SmallVector<llvm::Metadata *, 8> EltTys;
583 for (size_t I = FirstMemberIdx; I < Ops.size(); ++I) {
584 auto *MemberInst = BM->get<SPIRVExtInst>(Ops[I]);
585 if (MemberInst->getExtOp() == SPIRVDebug::TypeMember) {
586 auto *SPVMemberInst = BM->get<SPIRVExtInst>(Ops[I]);
587 DINode *MemberMD =
588 transTypeMember(SPVMemberInst, DebugInst, cast<DIScope>(CT));
589 EltTys.push_back(MemberMD);
590 DebugInstCache[SPVMemberInst] = MemberMD;
591 } else if (MemberInst->getExtOp() == SPIRVDebug::TypeInheritance) {
592 auto *SPVMemberInst = BM->get<SPIRVExtInst>(Ops[I]);
593 DINode *MemberMD = transTypeInheritance(SPVMemberInst, cast<DIType>(CT));
594 EltTys.push_back(MemberMD);
595 DebugInstCache[SPVMemberInst] = MemberMD;
596 } else {
597 EltTys.emplace_back(transDebugInst(BM->get<SPIRVExtInst>(Ops[I])));
598 }
599 }
600 DINodeArray Elements = getDIBuilder(DebugInst).getOrCreateArray(EltTys);
601 getDIBuilder(DebugInst).replaceArrays(CT, Elements);
602 assert(CT && "Composite type translation failed.");
603 return CT;
604 }
605
606 DISubrange *
607 SPIRVToLLVMDbgTran::transTypeSubrange(const SPIRVExtInst *DebugInst) {
608 using namespace SPIRVDebug::Operand::TypeSubrange;
609 const SPIRVWordVec &Ops = DebugInst->getArguments();
610 assert((Ops.size() == MinOperandCount || Ops.size() == MaxOperandCount) &&
611 "Invalid number of operands");
612 std::vector<Metadata *> TranslatedOps(MaxOperandCount, nullptr);
613 auto TransOperand = [&Ops, &TranslatedOps, this](int Idx) -> void {
614 if (!getDbgInst<SPIRVDebug::DebugInfoNone>(Ops[Idx])) {
615 if (auto *GlobalVar = getDbgInst<SPIRVDebug::GlobalVariable>(Ops[Idx])) {
616 TranslatedOps[Idx] =
617 cast<Metadata>(transDebugInst<DIGlobalVariable>(GlobalVar));
618 } else if (auto *LocalVar =
619 getDbgInst<SPIRVDebug::LocalVariable>(Ops[Idx])) {
620 TranslatedOps[Idx] =
621 cast<Metadata>(transDebugInst<DILocalVariable>(LocalVar));
622 } else if (auto *Expr = getDbgInst<SPIRVDebug::Expression>(Ops[Idx])) {
623 TranslatedOps[Idx] = cast<Metadata>(transDebugInst<DIExpression>(Expr));
624 } else if (auto *Const = BM->get<SPIRVConstant>(Ops[Idx])) {
625 int64_t ConstantAsInt = static_cast<int64_t>(Const->getZExtIntValue());
626 TranslatedOps[Idx] = cast<Metadata>(ConstantAsMetadata::get(
627 ConstantInt::get(M->getContext(), APInt(64, ConstantAsInt))));
628 }
629 }
630 };
631 for (size_t Idx = 0; Idx < Ops.size(); ++Idx)
632 TransOperand(Idx);
633 return getDIBuilder(DebugInst).getOrCreateSubrange(
634 TranslatedOps[CountIdx], TranslatedOps[LowerBoundIdx],
635 TranslatedOps[UpperBoundIdx], TranslatedOps[StrideIdx]);
636 }
637
638 DIStringType *
639 SPIRVToLLVMDbgTran::transTypeString(const SPIRVExtInst *DebugInst) {
640 using namespace SPIRVDebug::Operand::TypeString;
641 const SPIRVWordVec &Ops = DebugInst->getArguments();
642 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
643
644 StringRef Name = getString(Ops[NameIdx]);
645 unsigned Encoding = 0;
646 if (!getDbgInst<SPIRVDebug::DebugInfoNone>((Ops[BaseTypeIdx]))) {
647 DIBasicType *BaseTy =
648 transTypeBasic(BM->get<SPIRVExtInst>(Ops[BaseTypeIdx]));
649 Encoding = BaseTy->getEncoding();
650 }
651
652 DIExpression *StrLocationExp = nullptr;
653 if (!getDbgInst<SPIRVDebug::DebugInfoNone>(Ops[DataLocationIdx])) {
654 if (const auto *DIExpr =
655 getDbgInst<SPIRVDebug::Expression>(Ops[DataLocationIdx]))
656 StrLocationExp = transDebugInst<DIExpression>(DIExpr);
657 }
658
659 uint64_t SizeInBits = BM->get<SPIRVConstant>(Ops[SizeIdx])->getZExtIntValue();
660
661 DIExpression *StringLengthExp = nullptr;
662 DIVariable *StringLengthVar = nullptr;
663 if (!getDbgInst<SPIRVDebug::DebugInfoNone>(Ops[LengthAddrIdx])) {
664 if (const auto *GV =
665 getDbgInst<SPIRVDebug::GlobalVariable>(Ops[LengthAddrIdx]))
666 StringLengthVar = transDebugInst<DIGlobalVariable>(GV);
667 if (const auto *LV =
668 getDbgInst<SPIRVDebug::LocalVariable>(Ops[LengthAddrIdx]))
669 StringLengthVar = transDebugInst<DILocalVariable>(LV);
670 if (const auto *DIExpr =
671 getDbgInst<SPIRVDebug::Expression>(Ops[LengthAddrIdx]))
672 StringLengthExp = transDebugInst<DIExpression>(DIExpr);
673 }
674
675 return DIStringType::get(M->getContext(), dwarf::DW_TAG_string_type, Name,
676 cast_or_null<Metadata>(StringLengthVar),
677 cast_or_null<Metadata>(StringLengthExp),
678 cast_or_null<Metadata>(StrLocationExp), SizeInBits,
679 0 /*AlignInBits*/, Encoding);
680 }
681
682 DINode *SPIRVToLLVMDbgTran::transTypeMember(const SPIRVExtInst *DebugInst,
683 const SPIRVExtInst *ParentInst,
684 DIScope *Scope) {
685 if (isNonSemanticDebugInfo(DebugInst->getExtSetKind()))
686 // In NonSemantic spec TypeMember doesn't have Scope parameter
687 return transTypeMemberNonSemantic(DebugInst, ParentInst, Scope);
688 return transTypeMemberOpenCL(DebugInst);
689 }
690
691 DINode *
692 SPIRVToLLVMDbgTran::transTypeMemberOpenCL(const SPIRVExtInst *DebugInst) {
693 using namespace SPIRVDebug::Operand::TypeMember::OpenCL;
694 const SPIRVWordVec &Ops = DebugInst->getArguments();
695 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
696
697 DIFile *File = getFile(Ops[SourceIdx]);
698 SPIRVWord LineNo =
699 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
700 StringRef Name = getString(Ops[NameIdx]);
701 DIScope *Scope = getScope(BM->getEntry(Ops[ParentIdx]));
702 DIType *BaseType = transNonNullDebugType(BM->get<SPIRVExtInst>(Ops[TypeIdx]));
703 uint64_t OffsetInBits =
704 BM->get<SPIRVConstant>(Ops[OffsetIdx])->getZExtIntValue();
705 SPIRVWord SPIRVFlags =
706 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
707 DINode::DIFlags Flags = DINode::FlagZero;
708 if ((SPIRVDebug::FlagAccess & SPIRVFlags) == SPIRVDebug::FlagIsPublic) {
709 Flags |= DINode::FlagPublic;
710 } else if (SPIRVFlags & SPIRVDebug::FlagIsProtected) {
711 Flags |= DINode::FlagProtected;
712 } else if (SPIRVFlags & SPIRVDebug::FlagIsPrivate) {
713 Flags |= DINode::FlagPrivate;
714 }
715 if (SPIRVFlags & SPIRVDebug::FlagIsStaticMember)
716 Flags |= DINode::FlagStaticMember;
717 if (Flags & DINode::FlagStaticMember && Ops.size() > MinOperandCount) {
718 SPIRVValue *ConstVal = BM->get<SPIRVValue>(Ops[ValueIdx]);
719 assert(isConstantOpCode(ConstVal->getOpCode()) &&
720 "Static member must be a constant");
721 llvm::Value *Val = SPIRVReader->transValue(ConstVal, nullptr, nullptr);
722 return getDIBuilder(DebugInst).createStaticMemberType(
723 Scope, Name, File, LineNo, BaseType, Flags, cast<llvm::Constant>(Val));
724 }
725 uint64_t Size = BM->get<SPIRVConstant>(Ops[SizeIdx])->getZExtIntValue();
726 uint64_t Alignment = 0;
727
728 return getDIBuilder(DebugInst).createMemberType(Scope, Name, File, LineNo,
729 Size, Alignment, OffsetInBits,
730 Flags, BaseType);
731 }
732
733 DINode *
734 SPIRVToLLVMDbgTran::transTypeMemberNonSemantic(const SPIRVExtInst *DebugInst,
735 const SPIRVExtInst *ParentInst,
736 DIScope *Scope) {
737 if (!Scope)
738 // Will be translated later when processing TypeMember's parent
739 return nullptr;
740 using namespace SPIRVDebug::Operand::TypeMember::NonSemantic;
741 const SPIRVWordVec &Ops = DebugInst->getArguments();
742 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
743
744 DIFile *File = getFile(Ops[SourceIdx]);
745 const SPIRVWord LineNo =
746 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
747 const StringRef Name = getString(Ops[NameIdx]);
748 DIType *BaseType =
749 transNonNullDebugType(BM->get<SPIRVExtInst>(Ops[TypeIdx]));
750 const uint64_t OffsetInBits =
751 BM->get<SPIRVConstant>(Ops[OffsetIdx])->getZExtIntValue();
752 const SPIRVWord SPIRVFlags =
753 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
754 DINode::DIFlags Flags = DINode::FlagZero;
755 if ((SPIRVDebug::FlagAccess & SPIRVFlags) == SPIRVDebug::FlagIsPublic) {
756 Flags |= DINode::FlagPublic;
757 } else if (SPIRVFlags & SPIRVDebug::FlagIsProtected) {
758 Flags |= DINode::FlagProtected;
759 } else if (SPIRVFlags & SPIRVDebug::FlagIsPrivate) {
760 Flags |= DINode::FlagPrivate;
761 }
762 if (SPIRVFlags & SPIRVDebug::FlagIsStaticMember)
763 Flags |= DINode::FlagStaticMember;
764 if (SPIRVFlags & SPIRVDebug::FlagBitField)
765 Flags |= DINode::FlagBitField;
766
767 if (Flags & DINode::FlagStaticMember && Ops.size() > MinOperandCount) {
768 SPIRVValue *ConstVal = BM->get<SPIRVValue>(Ops[ValueIdx]);
769 assert(isConstantOpCode(ConstVal->getOpCode()) &&
770 "Static member must be a constant");
771 llvm::Value *Val = SPIRVReader->transValue(ConstVal, nullptr, nullptr);
772 return getDIBuilder(DebugInst).createStaticMemberType(
773 Scope, Name, File, LineNo, BaseType, Flags, cast<llvm::Constant>(Val));
774 }
775 const uint64_t Size = BM->get<SPIRVConstant>(Ops[SizeIdx])->getZExtIntValue();
776 const uint64_t Alignment = 0;
777
778 return getDIBuilder(ParentInst)
779 .createMemberType(Scope, Name, File, LineNo, Size, Alignment,
780 OffsetInBits, Flags, BaseType);
781 }
782
783 DINode *SPIRVToLLVMDbgTran::transTypeEnum(const SPIRVExtInst *DebugInst) {
784 using namespace SPIRVDebug::Operand::TypeEnum;
785 const SPIRVWordVec &Ops = DebugInst->getArguments();
786 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
787
788 StringRef Name = getString(Ops[NameIdx]);
789 DIFile *File = getFile(Ops[SourceIdx]);
790 SPIRVWord LineNo =
791 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
792 DIScope *Scope = getScope(BM->getEntry(Ops[ParentIdx]));
793 uint64_t SizeInBits = BM->get<SPIRVConstant>(Ops[SizeIdx])->getZExtIntValue();
794 SPIRVWord AlignInBits = 0;
795 SPIRVWord Flags =
796 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
797 if (Flags & SPIRVDebug::FlagIsFwdDecl) {
798 return getDIBuilder(DebugInst).createForwardDecl(
799 dwarf::DW_TAG_enumeration_type, Name, Scope, File, LineNo, AlignInBits,
800 SizeInBits);
801 } else {
802 SmallVector<llvm::Metadata *, 16> Elts;
803 for (size_t I = FirstEnumeratorIdx, E = Ops.size(); I < E; I += 2) {
804 uint64_t Val = BM->get<SPIRVConstant>(Ops[I])->getZExtIntValue();
805 StringRef Name = getString(Ops[I + 1]);
806 Elts.push_back(getDIBuilder(DebugInst).createEnumerator(Name, Val));
807 }
808 DINodeArray Enumerators = getDIBuilder(DebugInst).getOrCreateArray(Elts);
809 DIType *UnderlyingType = nullptr;
810 SPIRVEntry *E = BM->getEntry(Ops[UnderlyingTypeIdx]);
811 if (!isa<OpTypeVoid>(E))
812 UnderlyingType = transDebugInst<DIType>(static_cast<SPIRVExtInst *>(E));
813 return getDIBuilder(DebugInst).createEnumerationType(
814 Scope, Name, File, LineNo, SizeInBits, AlignInBits, Enumerators,
815 UnderlyingType, "", Flags & SPIRVDebug::FlagIsEnumClass);
816 }
817 }
818
819 DINode *SPIRVToLLVMDbgTran::transTypeFunction(const SPIRVExtInst *DebugInst) {
820 using namespace SPIRVDebug::Operand::TypeFunction;
821 const SPIRVWordVec &Ops = DebugInst->getArguments();
822 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
823
824 SPIRVWord SPIRVFlags =
825 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
826 DINode::DIFlags Flags = DINode::FlagZero;
827 if (SPIRVFlags & SPIRVDebug::FlagIsLValueReference)
828 Flags |= llvm::DINode::FlagLValueReference;
829 if (SPIRVFlags & SPIRVDebug::FlagIsRValueReference)
830 Flags |= llvm::DINode::FlagRValueReference;
831
832 SPIRVEntry *E = BM->getEntry(Ops[ReturnTypeIdx]);
833 MDNode *RT = isa<OpTypeVoid>(E)
834 ? nullptr
835 : transDebugInst(BM->get<SPIRVExtInst>(Ops[ReturnTypeIdx]));
836 SmallVector<llvm::Metadata *, 16> Elements{RT};
837 for (size_t I = FirstParameterIdx, E = Ops.size(); I < E; ++I) {
838 SPIRVEntry *P = BM->getEntry(Ops[I]);
839 MDNode *Param = isa<OpTypeVoid>(P)
840 ? nullptr
841 : transDebugInst(BM->get<SPIRVExtInst>(Ops[I]));
842
843 Elements.push_back(Param);
844 }
845 DITypeRefArray ArgTypes =
846 getDIBuilder(DebugInst).getOrCreateTypeArray(Elements);
847 return getDIBuilder(DebugInst).createSubroutineType(ArgTypes, Flags);
848 }
849
850 DINode *
851 SPIRVToLLVMDbgTran::transTypePtrToMember(const SPIRVExtInst *DebugInst) {
852 using namespace SPIRVDebug::Operand::TypePtrToMember;
853 const SPIRVWordVec &Ops = DebugInst->getArguments();
854 assert(Ops.size() >= OperandCount && "Invalid number of operands");
855 SPIRVExtInst *Member = BM->get<SPIRVExtInst>(Ops[MemberTypeIdx]);
856 DIType *PointeeTy = transNonNullDebugType(Member);
857 SPIRVExtInst *ContainingTy = BM->get<SPIRVExtInst>(Ops[ParentIdx]);
858 DIType *BaseTy = transNonNullDebugType(ContainingTy);
859 return getDIBuilder(DebugInst).createMemberPointerType(PointeeTy, BaseTy, 0);
860 }
861
862 DINode *SPIRVToLLVMDbgTran::transLexicalBlock(const SPIRVExtInst *DebugInst) {
863 using namespace SPIRVDebug::Operand::LexicalBlock;
864 const SPIRVWordVec &Ops = DebugInst->getArguments();
865 DIScope *ParentScope = getScope(BM->getEntry(Ops[ParentIdx]));
866 DIFile *File = getFile(Ops[SourceIdx]);
867 SPIRVWord LineNo =
868 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
869 if (Ops.size() > MinOperandCount) {
870 StringRef Name = getString(Ops[NameIdx]);
871 bool InlinedNamespace = false;
872 if (DebugInst->getExtSetKind() ==
873 SPIRVEIS_NonSemantic_Shader_DebugInfo_200) {
874 SPIRVValue *V = BM->get<SPIRVValue>(Ops[InlineNamespaceIdx]);
875 Value *Var = SPIRVReader->transValue(V, nullptr, nullptr);
876 InlinedNamespace = cast<ConstantInt>(Var)->isOne();
877 }
878 return getDIBuilder(DebugInst).createNameSpace(ParentScope, Name,
879 InlinedNamespace);
880 }
881 unsigned Column = Ops[ColumnIdx];
882 return getDIBuilder(DebugInst).createLexicalBlock(ParentScope, File, LineNo,
883 Column);
884 }
885
886 DINode *SPIRVToLLVMDbgTran::transLexicalBlockDiscriminator(
887 const SPIRVExtInst *DebugInst) {
888 using namespace SPIRVDebug::Operand::LexicalBlockDiscriminator;
889 const SPIRVWordVec &Ops = DebugInst->getArguments();
890 DIFile *File = getFile(Ops[SourceIdx]);
891 SPIRVWord Disc = getConstantValueOrLiteral(Ops, DiscriminatorIdx,
892 DebugInst->getExtSetKind());
893 DIScope *ParentScope = getScope(BM->getEntry(Ops[ParentIdx]));
894 return getDIBuilder(DebugInst).createLexicalBlockFile(ParentScope, File,
895 Disc);
896 }
897
898 DINode *SPIRVToLLVMDbgTran::transFunction(const SPIRVExtInst *DebugInst,
899 bool IsMainSubprogram) {
900 using namespace SPIRVDebug::Operand::Function;
901 const SPIRVWordVec &Ops = DebugInst->getArguments();
902 assert(Ops.size() >= MinOperandCountNonSem && "Invalid number of operands");
903 if (!isNonSemanticDebugInfo(DebugInst->getExtSetKind()))
904 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
905
906 StringRef Name = getString(Ops[NameIdx]);
907 DISubroutineType *Ty =
908 transDebugInst<DISubroutineType>(BM->get<SPIRVExtInst>(Ops[TypeIdx]));
909 DIFile *File = getFile(Ops[SourceIdx]);
910 SPIRVWord LineNo =
911 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
912 DIScope *Scope = getScope(BM->getEntry(Ops[ParentIdx]));
913 StringRef LinkageName = getString(Ops[LinkageNameIdx]);
914
915 SPIRVWord SPIRVDebugFlags =
916 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
917 DINode::DIFlags Flags = DINode::FlagZero;
918 if (SPIRVDebugFlags & SPIRVDebug::FlagIsArtificial)
919 Flags |= llvm::DINode::FlagArtificial;
920 if (SPIRVDebugFlags & SPIRVDebug::FlagIsExplicit)
921 Flags |= llvm::DINode::FlagExplicit;
922 if (SPIRVDebugFlags & SPIRVDebug::FlagIsPrototyped)
923 Flags |= llvm::DINode::FlagPrototyped;
924 if (SPIRVDebugFlags & SPIRVDebug::FlagIsLValueReference)
925 Flags |= llvm::DINode::FlagLValueReference;
926 if (SPIRVDebugFlags & SPIRVDebug::FlagIsRValueReference)
927 Flags |= llvm::DINode::FlagRValueReference;
928 if ((SPIRVDebugFlags & SPIRVDebug::FlagAccess) == SPIRVDebug::FlagIsPublic)
929 Flags |= llvm::DINode::FlagPublic;
930 if (SPIRVDebugFlags & SPIRVDebug::FlagIsProtected)
931 Flags |= llvm::DINode::FlagProtected;
932 if (SPIRVDebugFlags & SPIRVDebug::FlagIsPrivate)
933 Flags |= llvm::DINode::FlagPrivate;
934
935 bool IsDefinition = SPIRVDebugFlags & SPIRVDebug::FlagIsDefinition;
936 bool IsOptimized = SPIRVDebugFlags & SPIRVDebug::FlagIsOptimized;
937 bool IsLocal = SPIRVDebugFlags & SPIRVDebug::FlagIsLocal;
938 bool IsMainSubprogramFlag =
939 IsMainSubprogram ||
940 (!isNonSemanticDebugInfo(DebugInst->getExtSetKind()) &&
941 BM->isEntryPoint(spv::ExecutionModelKernel, Ops[FunctionIdIdx]));
942
943 DISubprogram::DISPFlags SPFlags = DISubprogram::toSPFlags(
944 IsLocal, IsDefinition, IsOptimized, DISubprogram::SPFlagNonvirtual,
945 IsMainSubprogramFlag);
946
947 SPIRVWord ScopeLine =
948 getConstantValueOrLiteral(Ops, ScopeLineIdx, DebugInst->getExtSetKind());
949
950 // Function declaration descriptor
951 DISubprogram *FD = nullptr;
952 if (isNonSemanticDebugInfo(DebugInst->getExtSetKind()) &&
953 Ops.size() > DeclarationNonSemIdx) {
954 FD = transDebugInst<DISubprogram>(
955 BM->get<SPIRVExtInst>(Ops[DeclarationNonSemIdx]));
956 } else if (Ops.size() > DeclarationIdx) {
957 FD = transDebugInst<DISubprogram>(
958 BM->get<SPIRVExtInst>(Ops[DeclarationIdx]));
959 }
960
961 // Here we create fake array of template parameters. If it was plain nullptr,
962 // the template parameter operand would be removed in DISubprogram::getImpl.
963 // But we want it to be there, because if there is DebugTypeTemplate
964 // instruction refering to this function, transTypeTemplate method must be
965 // able to replace the template parameter operand, thus it must be in the
966 // operands list.
967 SmallVector<llvm::Metadata *, 8> Elts;
968 DINodeArray TParams = getDIBuilder(DebugInst).getOrCreateArray(Elts);
969 llvm::DITemplateParameterArray TParamsArray = TParams.get();
970
971 DISubprogram *DIS = nullptr;
972 if (Scope && (isa<DICompositeType>(Scope) || isa<DINamespace>(Scope)) &&
973 !IsDefinition)
974 DIS = getDIBuilder(DebugInst).createMethod(Scope, Name, LinkageName, File,
975 LineNo, Ty, 0, 0, nullptr, Flags,
976 SPFlags, TParamsArray);
977 else {
978 // Create targetFuncName mostly for Fortran trampoline function if it is
979 // the case
980 StringRef TargetFunction = "";
981 if (DebugInst->getExtSetKind() ==
982 SPIRVEIS_NonSemantic_Shader_DebugInfo_200 &&
983 Ops.size() > TargetFunctionNameIdx) {
984 TargetFunction = getString(Ops[TargetFunctionNameIdx]);
985 }
986 DIS = getDIBuilder(DebugInst).createFunction(
987 Scope, Name, LinkageName, File, LineNo, Ty, ScopeLine, Flags, SPFlags,
988 TParamsArray, FD,
989 /*ThrownTypes*/ nullptr,
990 /*Annotations*/ nullptr, TargetFunction);
991 }
992 DebugInstCache[DebugInst] = DIS;
993
994 // At this point, we don't have info about the function definition for
995 // NonSemantic.Shader debug info. If function definition is present, it'll be
996 // translated later within the function scope.
997 // For "default" debug info we do translate function body here.
998 if (!isNonSemanticDebugInfo(DebugInst->getExtSetKind()))
999 transFunctionBody(DIS, Ops[FunctionIdIdx]);
1000
1001 return DIS;
1002 }
1003
1004 void SPIRVToLLVMDbgTran::transFunctionBody(DISubprogram *DIS, SPIRVId FuncId) {
1005 FuncMap[FuncId] = DIS;
1006
1007 SPIRVEntry *E = BM->getEntry(FuncId);
1008 if (E->getOpCode() == OpFunction) {
1009 SPIRVFunction *BF = static_cast<SPIRVFunction *>(E);
1010 llvm::Function *F = SPIRVReader->transFunction(BF);
1011 assert(F && "Translation of function failed!");
1012 if (!F->hasMetadata("dbg"))
1013 F->setMetadata("dbg", DIS);
1014 }
1015 }
1016
1017 DINode *
1018 SPIRVToLLVMDbgTran::transFunctionDefinition(const SPIRVExtInst *DebugInst) {
1019 using namespace SPIRVDebug::Operand::FunctionDefinition;
1020 const SPIRVWordVec &Ops = DebugInst->getArguments();
1021
1022 SPIRVExtInst *Func = BM->get<SPIRVExtInst>(Ops[FunctionIdx]);
1023 DISubprogram *LLVMFunc = cast<DISubprogram>(DebugInstCache[Func]);
1024
1025 transFunctionBody(LLVMFunc, Ops[DefinitionIdx]);
1026 return nullptr;
1027 }
1028
1029 DINode *SPIRVToLLVMDbgTran::transFunctionDecl(const SPIRVExtInst *DebugInst) {
1030 using namespace SPIRVDebug::Operand::FunctionDeclaration;
1031 const SPIRVWordVec &Ops = DebugInst->getArguments();
1032 assert(Ops.size() == OperandCount && "Invalid number of operands");
1033 // Scope
1034 DIScope *Scope = getScope(BM->getEntry(Ops[ParentIdx]));
1035 StringRef Name = getString(Ops[NameIdx]);
1036 StringRef LinkageName = getString(Ops[LinkageNameIdx]);
1037 DIFile *File = getFile(Ops[SourceIdx]);
1038 SPIRVWord LineNo =
1039 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
1040 DISubroutineType *Ty =
1041 transDebugInst<DISubroutineType>(BM->get<SPIRVExtInst>(Ops[TypeIdx]));
1042
1043 SPIRVWord SPIRVDebugFlags =
1044 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
1045 bool IsDefinition = SPIRVDebugFlags & SPIRVDebug::FlagIsDefinition;
1046 bool IsOptimized = SPIRVDebugFlags & SPIRVDebug::FlagIsOptimized;
1047 bool IsLocal = SPIRVDebugFlags & SPIRVDebug::FlagIsLocal;
1048 DINode::DIFlags Flags = DINode::FlagZero;
1049 if (SPIRVDebugFlags & SPIRVDebug::FlagIsArtificial)
1050 Flags |= llvm::DINode::FlagArtificial;
1051 if (SPIRVDebugFlags & SPIRVDebug::FlagIsExplicit)
1052 Flags |= llvm::DINode::FlagExplicit;
1053 if (SPIRVDebugFlags & SPIRVDebug::FlagIsPrototyped)
1054 Flags |= llvm::DINode::FlagPrototyped;
1055 if (SPIRVDebugFlags & SPIRVDebug::FlagIsLValueReference)
1056 Flags |= llvm::DINode::FlagLValueReference;
1057 if (SPIRVDebugFlags & SPIRVDebug::FlagIsRValueReference)
1058 Flags |= llvm::DINode::FlagRValueReference;
1059 if ((SPIRVDebugFlags & SPIRVDebug::FlagAccess) == SPIRVDebug::FlagIsPublic)
1060 Flags |= llvm::DINode::FlagPublic;
1061 if (SPIRVDebugFlags & SPIRVDebug::FlagIsProtected)
1062 Flags |= llvm::DINode::FlagProtected;
1063 if (SPIRVDebugFlags & SPIRVDebug::FlagIsPrivate)
1064 Flags |= llvm::DINode::FlagPrivate;
1065
1066 // Here we create fake array of template parameters. If it was plain nullptr,
1067 // the template parameter operand would be removed in DISubprogram::getImpl.
1068 // But we want it to be there, because if there is DebugTypeTemplate
1069 // instruction refering to this function, transTypeTemplate method must be
1070 // able to replace the template parameter operand, thus it must be in the
1071 // operands list.
1072 SmallVector<llvm::Metadata *, 8> Elts;
1073 DINodeArray TParams = getDIBuilder(DebugInst).getOrCreateArray(Elts);
1074 llvm::DITemplateParameterArray TParamsArray = TParams.get();
1075
1076 DISubprogram *DIS = nullptr;
1077 DISubprogram::DISPFlags SPFlags =
1078 DISubprogram::toSPFlags(IsLocal, IsDefinition, IsOptimized);
1079 if (isa<DICompositeType>(Scope) || isa<DINamespace>(Scope))
1080 DIS = getDIBuilder(DebugInst).createMethod(Scope, Name, LinkageName, File,
1081 LineNo, Ty, 0, 0, nullptr, Flags,
1082 SPFlags, TParamsArray);
1083 else {
1084 // Since a function declaration doesn't have any retained nodes, resolve
1085 // the temporary placeholder for them immediately.
1086 DIS = getDIBuilder(DebugInst).createTempFunctionFwdDecl(
1087 Scope, Name, LinkageName, File, LineNo, Ty, 0, Flags, SPFlags,
1088 TParamsArray);
1089 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(DIS));
1090 DIS = getDIBuilder(DebugInst).replaceTemporary(std::move(FwdDecl), DIS);
1091 }
1092 DebugInstCache[DebugInst] = DIS;
1093
1094 return DIS;
1095 }
1096
1097 MDNode *SPIRVToLLVMDbgTran::transEntryPoint(const SPIRVExtInst *DebugInst) {
1098 using namespace SPIRVDebug::Operand::EntryPoint;
1099 const SPIRVWordVec &Ops = DebugInst->getArguments();
1100 assert(Ops.size() == OperandCount && "Invalid number of operands");
1101
1102 SPIRVExtInst *EP = BM->get<SPIRVExtInst>(Ops[EntryPointIdx]);
1103 SPIRVExtInst *CU = BM->get<SPIRVExtInst>(Ops[CompilationUnitIdx]);
1104 std::string Producer = getString(Ops[CompilerSignatureIdx]);
1105 std::string CLArgs = getString(Ops[CommandLineArgsIdx]);
1106
1107 DICompileUnit *C = transCompilationUnit(CU, Producer, CLArgs); // NOLINT
1108 DebugInstCache[CU] = C;
1109
1110 return transFunction(EP, true /*IsMainSubprogram*/);
1111 }
1112
1113 MDNode *SPIRVToLLVMDbgTran::transGlobalVariable(const SPIRVExtInst *DebugInst) {
1114 using namespace SPIRVDebug::Operand::GlobalVariable;
1115 const SPIRVWordVec &Ops = DebugInst->getArguments();
1116 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
1117
1118 StringRef Name = getString(Ops[NameIdx]);
1119 DIType *Ty = transNonNullDebugType(BM->get<SPIRVExtInst>(Ops[TypeIdx]));
1120 DIFile *File = getFile(Ops[SourceIdx]);
1121 SPIRVWord LineNo =
1122 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
1123 DIScope *Parent = getScope(BM->getEntry(Ops[ParentIdx]));
1124 StringRef LinkageName = getString(Ops[LinkageNameIdx]);
1125
1126 DIDerivedType *StaticMemberDecl = nullptr;
1127 if (Ops.size() > MinOperandCount) {
1128 StaticMemberDecl = transDebugInst<DIDerivedType>(
1129 BM->get<SPIRVExtInst>(Ops[StaticMemberDeclarationIdx]));
1130 }
1131
1132 DIExpression *DIExpr = nullptr;
1133 // Check if Ops[VariableIdx] is not being used to hold a variable operand.
1134 // Instead it is being used to hold an Expression that holds the initial
1135 // value of the GlobalVariable.
1136 if (getDbgInst<SPIRVDebug::Expression>(Ops[VariableIdx]))
1137 DIExpr =
1138 transDebugInst<DIExpression>(BM->get<SPIRVExtInst>(Ops[VariableIdx]));
1139
1140 SPIRVWord Flags =
1141 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
1142 bool IsLocal = Flags & SPIRVDebug::FlagIsLocal;
1143 bool IsDefinition = Flags & SPIRVDebug::FlagIsDefinition;
1144 MDNode *VarDecl = nullptr;
1145 if (IsDefinition) {
1146 VarDecl = getDIBuilder(DebugInst).createGlobalVariableExpression(
1147 Parent, Name, LinkageName, File, LineNo, Ty, IsLocal, IsDefinition,
1148 DIExpr, StaticMemberDecl);
1149 } else {
1150 VarDecl = getDIBuilder(DebugInst).createTempGlobalVariableFwdDecl(
1151 Parent, Name, LinkageName, File, LineNo, Ty, IsLocal, StaticMemberDecl);
1152 // replaceAllUsesWith call makes VarDecl non-temp.
1153 // Otherwise DIBuilder will crash at finalization.
1154 llvm::TempMDNode TMP(VarDecl);
1155 VarDecl = getDIBuilder(DebugInst).replaceTemporary(std::move(TMP), VarDecl);
1156 }
1157
1158 // Ops[VariableIdx] was not used to hold an Expression with the initial value
1159 // for the GlobalVariable
1160 if (!DIExpr) {
1161 // If the variable has no initializer Ops[VariableIdx] is OpDebugInfoNone.
1162 // Otherwise Ops[VariableIdx] may be a global variable or a constant(C++
1163 // static const).
1164 if (VarDecl && !getDbgInst<SPIRVDebug::DebugInfoNone>(Ops[VariableIdx])) {
1165 SPIRVValue *V = BM->get<SPIRVValue>(Ops[VariableIdx]);
1166 Value *Var = SPIRVReader->transValue(V, nullptr, nullptr);
1167 llvm::GlobalVariable *GV = dyn_cast_or_null<llvm::GlobalVariable>(Var);
1168 if (GV && !GV->hasMetadata("dbg"))
1169 GV->addMetadata("dbg", *VarDecl);
1170 }
1171 }
1172 return VarDecl;
1173 }
1174
1175 DINode *SPIRVToLLVMDbgTran::transLocalVariable(const SPIRVExtInst *DebugInst) {
1176 using namespace SPIRVDebug::Operand::LocalVariable;
1177 const SPIRVWordVec &Ops = DebugInst->getArguments();
1178 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
1179
1180 DIScope *Scope = getScope(BM->getEntry(Ops[ParentIdx]));
1181 StringRef Name = getString(Ops[NameIdx]);
1182 DIFile *File = getFile(Ops[SourceIdx]);
1183 SPIRVWord LineNo =
1184 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
1185 DIType *Ty = transNonNullDebugType(BM->get<SPIRVExtInst>(Ops[TypeIdx]));
1186 DINode::DIFlags Flags = DINode::FlagZero;
1187 SPIRVWord SPIRVFlags =
1188 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
1189 if (SPIRVFlags & SPIRVDebug::FlagIsArtificial)
1190 Flags |= DINode::FlagArtificial;
1191 if (SPIRVFlags & SPIRVDebug::FlagIsObjectPointer)
1192 Flags |= DINode::FlagObjectPointer;
1193
1194 if (Ops.size() > ArgNumberIdx)
1195 return getDIBuilder(DebugInst).createParameterVariable(
1196 Scope, Name, Ops[ArgNumberIdx], File, LineNo, Ty, true, Flags);
1197 return getDIBuilder(DebugInst).createAutoVariable(Scope, Name, File, LineNo,
1198 Ty, true, Flags);
1199 }
1200
1201 DINode *SPIRVToLLVMDbgTran::transTypedef(const SPIRVExtInst *DebugInst) {
1202 using namespace SPIRVDebug::Operand::Typedef;
1203 const SPIRVWordVec &Ops = DebugInst->getArguments();
1204 assert(Ops.size() >= OperandCount && "Invalid number of operands");
1205
1206 DIFile *File = getFile(Ops[SourceIdx]);
1207 SPIRVWord LineNo =
1208 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
1209 StringRef Alias = getString(Ops[NameIdx]);
1210 SPIRVEntry *TypeInst = BM->getEntry(Ops[BaseTypeIdx]);
1211 DIType *Ty = transDebugInst<DIType>(static_cast<SPIRVExtInst *>(TypeInst));
1212 DIScope *Scope = getScope(BM->getEntry(Ops[ParentIdx]));
1213 assert(Scope && "Typedef should have a parent scope");
1214 return getDIBuilder(DebugInst).createTypedef(Ty, Alias, File, LineNo, Scope);
1215 }
1216
1217 DINode *SPIRVToLLVMDbgTran::transTypeInheritance(const SPIRVExtInst *DebugInst,
1218 DIType *ChildClass) {
1219 using namespace SPIRVDebug::Operand::TypeInheritance;
1220 // The value is used when assertions are enabled
1221 [[maybe_unused]] unsigned OperandCount;
1222 unsigned ParentIdx, OffsetIdx, FlagsIdx;
1223 if (isNonSemanticDebugInfo(DebugInst->getExtSetKind())) {
1224 if (!ChildClass) {
1225 // Will be translated later when processing TypeMember's parent
1226 return nullptr;
1227 }
1228 OperandCount = NonSemantic::OperandCount;
1229 ParentIdx = NonSemantic::ParentIdx;
1230 OffsetIdx = NonSemantic::OffsetIdx;
1231 FlagsIdx = NonSemantic::FlagsIdx;
1232 } else {
1233 OperandCount = NonSemantic::OperandCount;
1234 ParentIdx = OpenCL::ParentIdx;
1235 OffsetIdx = OpenCL::OffsetIdx;
1236 FlagsIdx = OpenCL::FlagsIdx;
1237 }
1238 const SPIRVWordVec &Ops = DebugInst->getArguments();
1239 assert(Ops.size() >= OperandCount && "Invalid number of operands");
1240 DIType *Parent =
1241 transDebugInst<DIType>(BM->get<SPIRVExtInst>(Ops[ParentIdx]));
1242 DINode::DIFlags Flags = DINode::FlagZero;
1243 SPIRVWord SPIRVFlags =
1244 getConstantValueOrLiteral(Ops, FlagsIdx, DebugInst->getExtSetKind());
1245 if ((SPIRVFlags & SPIRVDebug::FlagAccess) == SPIRVDebug::FlagIsPublic)
1246 Flags |= llvm::DINode::FlagPublic;
1247 if ((SPIRVFlags & SPIRVDebug::FlagAccess) == SPIRVDebug::FlagIsProtected)
1248 Flags |= llvm::DINode::FlagProtected;
1249 if ((SPIRVFlags & SPIRVDebug::FlagAccess) == SPIRVDebug::FlagIsPrivate)
1250 Flags |= llvm::DINode::FlagPrivate;
1251 uint64_t OffsetVal =
1252 BM->get<SPIRVConstant>(Ops[OffsetIdx])->getZExtIntValue();
1253 DIType *Child;
1254 if (isNonSemanticDebugInfo(DebugInst->getExtSetKind())) {
1255 Child = ChildClass;
1256 } else {
1257 Child =
1258 transDebugInst<DIType>(BM->get<SPIRVExtInst>(Ops[OpenCL::ChildIdx]));
1259 }
1260 return getDIBuilder(DebugInst).createInheritance(Child, Parent, OffsetVal, 0,
1261 Flags);
1262 }
1263
1264 DINode *
1265 SPIRVToLLVMDbgTran::transTypeTemplateParameter(const SPIRVExtInst *DebugInst) {
1266 using namespace SPIRVDebug::Operand::TypeTemplateParameter;
1267 const SPIRVWordVec &Ops = DebugInst->getArguments();
1268 assert(Ops.size() >= OperandCount && "Invalid number of operands");
1269 StringRef Name = getString(Ops[NameIdx]);
1270 SPIRVEntry *ActualType = BM->getEntry(Ops[TypeIdx]);
1271 DIType *Ty = nullptr;
1272 if (!isa<OpTypeVoid>(ActualType))
1273 Ty = transDebugInst<DIType>(static_cast<SPIRVExtInst *>(ActualType));
1274 DIScope *Context = nullptr;
1275 if (!getDbgInst<SPIRVDebug::DebugInfoNone>(Ops[ValueIdx])) {
1276 SPIRVValue *Val = BM->get<SPIRVValue>(Ops[ValueIdx]);
1277 Value *V = SPIRVReader->transValue(Val, nullptr, nullptr);
1278 return getDIBuilder(DebugInst).createTemplateValueParameter(
1279 Context, Name, Ty, false, cast<Constant>(V));
1280 }
1281 return getDIBuilder(DebugInst).createTemplateTypeParameter(Context, Name, Ty,
1282 false);
1283 }
1284
1285 DINode *SPIRVToLLVMDbgTran::transTypeTemplateTemplateParameter(
1286 const SPIRVExtInst *DebugInst) {
1287 using namespace SPIRVDebug::Operand::TypeTemplateTemplateParameter;
1288 const SPIRVWordVec &Ops = DebugInst->getArguments();
1289 assert(Ops.size() >= OperandCount && "Invalid number of operands");
1290 StringRef Name = getString(Ops[NameIdx]);
1291 StringRef TemplName = getString(Ops[TemplateNameIdx]);
1292 DIScope *Context = nullptr;
1293 return getDIBuilder(DebugInst).createTemplateTemplateParameter(
1294 Context, Name, nullptr, TemplName);
1295 }
1296
1297 DINode *SPIRVToLLVMDbgTran::transTypeTemplateParameterPack(
1298 const SPIRVExtInst *DebugInst) {
1299 using namespace SPIRVDebug::Operand::TypeTemplateParameterPack;
1300 const SPIRVWordVec &Ops = DebugInst->getArguments();
1301 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
1302 StringRef Name = getString(Ops[NameIdx]);
1303 SmallVector<llvm::Metadata *, 8> Elts;
1304 for (size_t I = FirstParameterIdx, E = Ops.size(); I < E; ++I) {
1305 Elts.push_back(transDebugInst(BM->get<SPIRVExtInst>(Ops[I])));
1306 }
1307 DINodeArray Pack = getDIBuilder(DebugInst).getOrCreateArray(Elts);
1308 DIScope *Context = nullptr;
1309 return getDIBuilder(DebugInst).createTemplateParameterPack(Context, Name,
1310 nullptr, Pack);
1311 }
1312
1313 MDNode *SPIRVToLLVMDbgTran::transTypeTemplate(const SPIRVExtInst *DebugInst) {
1314 using namespace SPIRVDebug::Operand::TypeTemplate;
1315 const SPIRVWordVec &Ops = DebugInst->getArguments();
1316 const size_t NumOps = Ops.size();
1317 assert(NumOps >= MinOperandCount && "Invalid number of operands");
1318
1319 auto *Templ = BM->get<SPIRVExtInst>(Ops[TargetIdx]);
1320 MDNode *D = transDebugInst(Templ);
1321
1322 SmallVector<llvm::Metadata *, 8> Elts;
1323 for (size_t I = FirstParameterIdx; I < NumOps; ++I) {
1324 Elts.push_back(transDebugInst(BM->get<SPIRVExtInst>(Ops[I])));
1325 }
1326 DINodeArray TParams = getDIBuilder(DebugInst).getOrCreateArray(Elts);
1327
1328 if (DICompositeType *Comp = dyn_cast<DICompositeType>(D)) {
1329 getDIBuilder(DebugInst).replaceArrays(Comp, Comp->getElements(), TParams);
1330 return Comp;
1331 }
1332 if (isa<DISubprogram>(D)) {
1333 // This constant matches with one used in
1334 // DISubprogram::getRawTemplateParams()
1335 const unsigned TemplateParamsIndex = 9;
1336 D->replaceOperandWith(TemplateParamsIndex, TParams.get());
1337 return D;
1338 }
1339 llvm_unreachable("Invalid template");
1340 }
1341
1342 DINode *SPIRVToLLVMDbgTran::transImportedEntry(const SPIRVExtInst *DebugInst) {
1343 using namespace SPIRVDebug::Operand::ImportedEntity;
1344 const SPIRVWordVec &Ops = DebugInst->getArguments();
1345 // FIXME: 'OpenCL/bugged' version is kept because it's hard to remove it
1346 // It's W/A for missing 2nd index in OpenCL's implementation
1347 const SPIRVWord OffsetIdx =
1348 static_cast<int>(isNonSemanticDebugInfo(DebugInst->getExtSetKind()));
1349
1350 assert(Ops.size() == (OpenCL::OperandCount - OffsetIdx) &&
1351 "Invalid number of operands");
1352 DIScope *Scope = getScope(BM->getEntry(Ops[OpenCL::ParentIdx - OffsetIdx]));
1353 const SPIRVWord Line = getConstantValueOrLiteral(
1354 Ops, OpenCL::LineIdx - OffsetIdx, DebugInst->getExtSetKind());
1355 DIFile *File = getFile(Ops[OpenCL::SourceIdx - OffsetIdx]);
1356 auto *Entity = transDebugInst<DINode>(
1357 BM->get<SPIRVExtInst>(Ops[OpenCL::EntityIdx - OffsetIdx]));
1358 const SPIRVWord Tag = getConstantValueOrLiteral(Ops, OpenCL::TagIdx,
1359 DebugInst->getExtSetKind());
1360 if (Tag == SPIRVDebug::ImportedModule) {
1361 if (!Entity)
1362 return getDIBuilder(DebugInst).createImportedModule(
1363 Scope, static_cast<DIImportedEntity *>(nullptr), File, Line);
1364 if (DIModule *DM = dyn_cast<DIModule>(Entity))
1365 return getDIBuilder(DebugInst).createImportedModule(Scope, DM, File,
1366 Line);
1367 if (DIImportedEntity *IE = dyn_cast<DIImportedEntity>(Entity))
1368 return getDIBuilder(DebugInst).createImportedModule(Scope, IE, File,
1369 Line);
1370 if (DINamespace *NS = dyn_cast<DINamespace>(Entity))
1371 return getDIBuilder(DebugInst).createImportedModule(Scope, NS, File,
1372 Line);
1373 }
1374 if (Tag == SPIRVDebug::ImportedDeclaration) {
1375 const StringRef Name = getString(Ops[OpenCL::NameIdx]);
1376 if (DIGlobalVariableExpression *GVE =
1377 dyn_cast<DIGlobalVariableExpression>(Entity))
1378 return getDIBuilder(DebugInst).createImportedDeclaration(
1379 Scope, GVE->getVariable(), File, Line, Name);
1380 return getDIBuilder(DebugInst).createImportedDeclaration(Scope, Entity,
1381 File, Line, Name);
1382 }
1383 llvm_unreachable("Unexpected kind of imported entity!");
1384 }
1385
1386 DINode *SPIRVToLLVMDbgTran::transModule(const SPIRVExtInst *DebugInst) {
1387 using namespace SPIRVDebug::Operand::ModuleINTEL;
1388 const SPIRVWordVec &Ops = DebugInst->getArguments();
1389 assert(Ops.size() >= OperandCount && "Invalid number of operands");
1390 DIScope *Scope = getScope(BM->getEntry(Ops[ParentIdx]));
1391 SPIRVWord Line =
1392 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
1393 DIFile *File = getFile(Ops[SourceIdx]);
1394 StringRef Name = getString(Ops[NameIdx]);
1395 StringRef ConfigMacros = getString(Ops[ConfigMacrosIdx]);
1396 StringRef IncludePath = getString(Ops[IncludePathIdx]);
1397 StringRef ApiNotes = getString(Ops[ApiNotesIdx]);
1398 bool IsDecl =
1399 getConstantValueOrLiteral(Ops, IsDeclIdx, DebugInst->getExtSetKind());
1400 return getDIBuilder(DebugInst).createModule(
1401 Scope, Name, ConfigMacros, IncludePath, ApiNotes, File, Line, IsDecl);
1402 }
1403
1404 MDNode *SPIRVToLLVMDbgTran::transExpression(const SPIRVExtInst *DebugInst) {
1405 const SPIRVWordVec &Args = DebugInst->getArguments();
1406 std::vector<uint64_t> Ops;
1407 for (SPIRVId A : Args) {
1408 using namespace SPIRVDebug::Operand::Operation;
1409 SPIRVExtInst *O = BM->get<SPIRVExtInst>(A);
1410 const SPIRVWordVec &Operands = O->getArguments();
1411 auto OpCode =
1412 static_cast<SPIRVDebug::ExpressionOpCode>(getConstantValueOrLiteral(
1413 Operands, OpCodeIdx, DebugInst->getExtSetKind()));
1414 Ops.push_back(SPIRV::DbgExpressionOpCodeMap::rmap(OpCode));
1415 for (unsigned I = 1, E = Operands.size(); I < E; ++I) {
1416 Ops.push_back(
1417 getConstantValueOrLiteral(Operands, I, DebugInst->getExtSetKind()));
1418 }
1419 }
1420 ArrayRef<uint64_t> Addr(Ops.data(), Ops.size());
1421 return getDIBuilder(DebugInst).createExpression(Addr);
1422 }
1423
1424 DIType *
1425 SPIRVToLLVMDbgTran::transNonNullDebugType(const SPIRVExtInst *DebugInst) {
1426 if (DebugInst->getExtOp() != SPIRVDebug::DebugInfoNone)
1427 return transDebugInst<DIType>(DebugInst);
1428 return getDIBuilder(DebugInst).createUnspecifiedType("SPIRV unknown type");
1429 }
1430
1431 MDNode *SPIRVToLLVMDbgTran::transDebugInstImpl(const SPIRVExtInst *DebugInst) {
1432 switch (DebugInst->getExtOp()) {
1433 case SPIRVDebug::DebugInfoNone:
1434 return nullptr;
1435
1436 case SPIRVDebug::CompilationUnit:
1437 return transCompilationUnit(DebugInst);
1438
1439 case SPIRVDebug::TypeBasic:
1440 return transTypeBasic(DebugInst);
1441
1442 case SPIRVDebug::TypeQualifier:
1443 return transTypeQualifier(DebugInst);
1444
1445 case SPIRVDebug::TypePointer:
1446 return transTypePointer(DebugInst);
1447
1448 case SPIRVDebug::TypeArray:
1449 return transTypeArray(DebugInst);
1450
1451 case SPIRVDebug::TypeSubrange:
1452 return transTypeSubrange(DebugInst);
1453
1454 case SPIRVDebug::TypeString:
1455 return transTypeString(DebugInst);
1456
1457 case SPIRVDebug::TypeVector:
1458 return transTypeVector(DebugInst);
1459
1460 case SPIRVDebug::TypeComposite:
1461 return transTypeComposite(DebugInst);
1462
1463 case SPIRVDebug::TypeMember:
1464 return transTypeMember(DebugInst);
1465
1466 case SPIRVDebug::TypePtrToMember:
1467 return transTypePtrToMember(DebugInst);
1468
1469 case SPIRVDebug::TypeEnum:
1470 return transTypeEnum(DebugInst);
1471
1472 case SPIRVDebug::TypeFunction:
1473 return transTypeFunction(DebugInst);
1474
1475 case SPIRVDebug::LexicalBlock:
1476 return transLexicalBlock(DebugInst);
1477
1478 case SPIRVDebug::LexicalBlockDiscriminator:
1479 return transLexicalBlockDiscriminator(DebugInst);
1480
1481 case SPIRVDebug::Function:
1482 return transFunction(DebugInst);
1483
1484 case SPIRVDebug::FunctionDeclaration:
1485 return transFunctionDecl(DebugInst);
1486
1487 case SPIRVDebug::FunctionDefinition:
1488 return transFunctionDefinition(DebugInst);
1489
1490 case SPIRVDebug::EntryPoint:
1491 return transEntryPoint(DebugInst);
1492
1493 case SPIRVDebug::GlobalVariable:
1494 return transGlobalVariable(DebugInst);
1495
1496 case SPIRVDebug::LocalVariable:
1497 return transLocalVariable(DebugInst);
1498
1499 case SPIRVDebug::Typedef:
1500 return transTypedef(DebugInst);
1501
1502 case SPIRVDebug::InlinedAt:
1503 return transDebugInlined(DebugInst);
1504
1505 case SPIRVDebug::TypeInheritance:
1506 return transTypeInheritance(DebugInst);
1507
1508 case SPIRVDebug::TypeTemplateParameter:
1509 return transTypeTemplateParameter(DebugInst);
1510
1511 case SPIRVDebug::TypeTemplateTemplateParameter:
1512 return transTypeTemplateTemplateParameter(DebugInst);
1513
1514 case SPIRVDebug::TypeTemplateParameterPack:
1515 return transTypeTemplateParameterPack(DebugInst);
1516
1517 case SPIRVDebug::TypeTemplate:
1518 return transTypeTemplate(DebugInst);
1519
1520 case SPIRVDebug::ImportedEntity:
1521 return transImportedEntry(DebugInst);
1522
1523 case SPIRVDebug::Module:
1524 case SPIRVDebug::ModuleINTEL:
1525 return transModule(DebugInst);
1526
1527 case SPIRVDebug::Operation: // To be translated with transExpression
1528 case SPIRVDebug::Source: // To be used by other instructions
1529 case SPIRVDebug::SourceContinued:
1530 case SPIRVDebug::BuildIdentifier: // To be used by transCompilationUnit
1531 case SPIRVDebug::StoragePath: // To be used by transCompilationUnit
1532 return nullptr;
1533
1534 case SPIRVDebug::Expression:
1535 return transExpression(DebugInst);
1536
1537 case SPIRVDebug::TypeArrayDynamic:
1538 return transTypeArrayDynamic(DebugInst);
1539
1540 default:
1541 llvm_unreachable("Not implemented SPIR-V debug instruction!");
1542 }
1543 }
1544
1545 Instruction *
1546 SPIRVToLLVMDbgTran::transDebugIntrinsic(const SPIRVExtInst *DebugInst,
1547 BasicBlock *BB) {
1548 auto GetLocalVar = [&](SPIRVId Id) -> std::pair<DILocalVariable *, DebugLoc> {
1549 auto *LV = transDebugInst<DILocalVariable>(BM->get<SPIRVExtInst>(Id));
1550 DebugLoc DL = DILocation::get(M->getContext(), LV->getLine(),
1551 /*Column=*/0, LV->getScope());
1552 return std::make_pair(LV, DL);
1553 };
1554 auto GetValue = [&](SPIRVId Id) -> Value * {
1555 auto *V = BM->get<SPIRVValue>(Id);
1556 return SPIRVReader->transValue(V, BB->getParent(), BB);
1557 };
1558 auto GetExpression = [&](SPIRVId Id) -> DIExpression * {
1559 return transDebugInst<DIExpression>(BM->get<SPIRVExtInst>(Id));
1560 };
1561 SPIRVWordVec Ops = DebugInst->getArguments();
1562 switch (DebugInst->getExtOp()) {
1563 case SPIRVDebug::Scope:
1564 case SPIRVDebug::NoScope:
1565 case SPIRVDebug::FunctionDefinition:
1566 return nullptr;
1567 case SPIRVDebug::Declare: {
1568 using namespace SPIRVDebug::Operand::DebugDeclare;
1569 auto LocalVar = GetLocalVar(Ops[DebugLocalVarIdx]);
1570 if (getDbgInst<SPIRVDebug::DebugInfoNone>(Ops[VariableIdx])) {
1571 // If we don't have the variable(e.g. alloca might be promoted by mem2reg)
1572 // we should generate the following IR:
1573 // call void @llvm.dbg.declare(metadata !4, metadata !14, metadata !5)
1574 // !4 = !{}
1575 // DIBuilder::insertDeclare doesn't allow to pass nullptr for the Storage
1576 // parameter. To work around this limitation we create a dummy temp
1577 // alloca, use it to create llvm.dbg.declare, and then remove the alloca.
1578 auto *AI = new AllocaInst(Type::getInt8Ty(M->getContext()), 0, "tmp", BB);
1579 auto *DbgDeclare = getDIBuilder(DebugInst).insertDeclare(
1580 AI, LocalVar.first, GetExpression(Ops[ExpressionIdx]),
1581 LocalVar.second, BB);
1582 AI->eraseFromParent();
1583 return DbgDeclare;
1584 }
1585 return getDIBuilder(DebugInst).insertDeclare(
1586 GetValue(Ops[VariableIdx]), LocalVar.first,
1587 GetExpression(Ops[ExpressionIdx]), LocalVar.second, BB);
1588 }
1589 case SPIRVDebug::Value: {
1590 using namespace SPIRVDebug::Operand::DebugValue;
1591 auto LocalVar = GetLocalVar(Ops[DebugLocalVarIdx]);
1592 Value *Val = GetValue(Ops[ValueIdx]);
1593 DIExpression *Expr = GetExpression(Ops[ExpressionIdx]);
1594 auto *DbgValIntr = getDIBuilder(DebugInst).insertDbgValueIntrinsic(
1595 Val, LocalVar.first, Expr, LocalVar.second, BB);
1596 if (Expr->getNumLocationOperands() == 1) {
1597 SmallVector<ValueAsMetadata *, 1> MDs = {ValueAsMetadata::get(Val)};
1598 DIArgList *AL = DIArgList::get(M->getContext(), MDs);
1599 cast<DbgVariableIntrinsic>(DbgValIntr)->setRawLocation(AL);
1600 }
1601 return DbgValIntr;
1602 }
1603 default:
1604 llvm_unreachable("Unknown debug intrinsic!");
1605 }
1606 }
1607
1608 DebugLoc SPIRVToLLVMDbgTran::transDebugScope(const SPIRVInstruction *Inst) {
1609 unsigned Line = 0;
1610 unsigned Col = 0;
1611 MDNode *Scope = nullptr;
1612 MDNode *InlinedAt = nullptr;
1613
1614 // If DebugLine and OpLine are both active give DebugLine priority
1615 if (auto DL = Inst->getDebugLine()) {
1616 using namespace SPIRVDebug::Operand::DebugLine;
1617 const SPIRVWordVec DebugLineArgs = DL->getArguments();
1618 Line =
1619 getConstantValueOrLiteral(DebugLineArgs, StartIdx, DL->getExtSetKind());
1620 Col = getConstantValueOrLiteral(DebugLineArgs, ColumnStartIdx,
1621 DL->getExtSetKind());
1622 } else if (auto L = Inst->getLine()) {
1623 Line = L->getLine();
1624 Col = L->getColumn();
1625 }
1626 if (SPIRVEntry *S = Inst->getDebugScope()) {
1627 using namespace SPIRVDebug::Operand::Scope;
1628 SPIRVExtInst *DbgScope = static_cast<SPIRVExtInst *>(S);
1629 SPIRVWordVec Ops = DbgScope->getArguments();
1630 Scope = getScope(BM->getEntry(Ops[ScopeIdx]));
1631 if (Ops.size() > InlinedAtIdx)
1632 InlinedAt = transDebugInst(BM->get<SPIRVExtInst>(Ops[InlinedAtIdx]));
1633 return DILocation::get(M->getContext(), Line, Col, Scope, InlinedAt);
1634 }
1635 return DebugLoc();
1636 }
1637
1638 MDNode *SPIRVToLLVMDbgTran::transDebugInlined(const SPIRVExtInst *DebugInst) {
1639 // There is a Column operand in NonSemantic.Shader.200 spec
1640 if (DebugInst->getExtSetKind() ==
1641 SPIRV::SPIRVEIS_NonSemantic_Shader_DebugInfo_200)
1642 return transDebugInlinedNonSemanticShader200(DebugInst);
1643
1644 using namespace SPIRVDebug::Operand::InlinedAt::OpenCL;
1645 SPIRVWordVec Ops = DebugInst->getArguments();
1646 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
1647 SPIRVWord Line =
1648 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
1649 unsigned Col = 0; // DebugInlinedAt instruction has no column operand
1650 DILocalScope *Scope =
1651 cast<DILocalScope>(getScope(BM->getEntry(Ops[ScopeIdx])));
1652 DILocation *InlinedAt = nullptr;
1653 if (Ops.size() > InlinedIdx) {
1654 InlinedAt =
1655 transDebugInst<DILocation>(BM->get<SPIRVExtInst>(Ops[InlinedIdx]));
1656 }
1657 return DILocation::getDistinct(M->getContext(), Line, Col, Scope, InlinedAt);
1658 }
1659
1660 MDNode *SPIRVToLLVMDbgTran::transDebugInlinedNonSemanticShader200(
1661 const SPIRVExtInst *DebugInst) {
1662 using namespace SPIRVDebug::Operand::InlinedAt::NonSemantic;
1663 SPIRVWordVec Ops = DebugInst->getArguments();
1664 assert(Ops.size() >= MinOperandCount && "Invalid number of operands");
1665 const SPIRVWord Line =
1666 getConstantValueOrLiteral(Ops, LineIdx, DebugInst->getExtSetKind());
1667 const unsigned Col =
1668 getConstantValueOrLiteral(Ops, ColumnIdx, DebugInst->getExtSetKind());
1669 DILocalScope *Scope =
1670 cast<DILocalScope>(getScope(BM->getEntry(Ops[ScopeIdx])));
1671 DILocation *InlinedAt = nullptr;
1672 if (Ops.size() > InlinedIdx) {
1673 InlinedAt =
1674 transDebugInst<DILocation>(BM->get<SPIRVExtInst>(Ops[InlinedIdx]));
1675 }
1676 return DILocation::getDistinct(M->getContext(), Line, Col, Scope, InlinedAt);
1677 }
1678
1679 void SPIRVToLLVMDbgTran::finalize() {
1680 if (!Enable)
1681 return;
1682 for (const auto &Builder : BuilderMap)
1683 Builder.second->finalize();
1684 }
1685
1686 DIFile *SPIRVToLLVMDbgTran::getFile(const SPIRVId SourceId) {
1687 using namespace SPIRVDebug::Operand::Source;
1688 SPIRVExtInst *Source = BM->get<SPIRVExtInst>(SourceId);
1689 assert(Source->getExtOp() == SPIRVDebug::Source &&
1690 "DebugSource instruction is expected");
1691 SPIRVWordVec SourceArgs = Source->getArguments();
1692 assert(SourceArgs.size() >= MinOperandCount && "Invalid number of operands");
1693 if (SourceArgs.size() == MinOperandCount)
1694 return getDIFile(getString(SourceArgs[FileIdx]));
1695
1696 if (!isNonSemanticDebugInfo(Source->getExtSetKind())) {
1697 const std::string ChecksumStr =
1698 getDbgInst<SPIRVDebug::DebugInfoNone>(SourceArgs[TextIdx])
1699 ? ""
1700 : getString(SourceArgs[TextIdx]);
1701 return getDIFile(getString(SourceArgs[FileIdx]),
1702 ParseChecksum(ChecksumStr));
1703 }
1704
1705
1706 std::optional<DIFile::ChecksumInfo<StringRef>> CS;
1707 SPIRVWord StrIdx = SourceArgs[TextIdx];
1708 if (Source->getExtSetKind() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200) {
1709 if (SourceArgs.size() >= MaxOperandCount - 1) {
1710 // 2 optional parameters are ChecksumKind and ChecksumValue - they should
1711 // go together
1712 if (!getDbgInst<SPIRVDebug::DebugInfoNone>(SourceArgs[ChecksumKind]) &&
1713 !getDbgInst<SPIRVDebug::DebugInfoNone>(SourceArgs[ChecksumValue])) {
1714 const llvm::DIFile::ChecksumKind Kind = SPIRV::DbgChecksumKindMap::rmap(
1715 static_cast<SPIRVDebug::FileChecksumKind>(
1716 BM->get<SPIRVConstant>(SourceArgs[ChecksumKind])
1717 ->getZExtIntValue()));
1718 const StringRef Checksum = getString(SourceArgs[ChecksumValue]);
1719 const size_t ChecksumEndPos = Checksum.find_if_not(llvm::isHexDigit);
1720 CS.emplace(Kind, Checksum.substr(0, ChecksumEndPos));
1721 }
1722 }
1723
1724 // Among optional parameters - text is always the last one (either 1st or
1725 // 3rd)
1726 if (SourceArgs.size() == MaxOperandCount ||
1727 SourceArgs.size() == MaxOperandCount - 2)
1728 StrIdx = SourceArgs[TextNonSemIdx];
1729 else
1730 StrIdx = SPIRVID_INVALID;
1731 }
1732
1733 return getDIFile(getString(SourceArgs[FileIdx]), CS,
1734 getStringSourceContinued(StrIdx, Source));
1735 }
1736
1737 void SPIRVToLLVMDbgTran::setBuildIdentifierAndStoragePath() {
1738 #ifndef NDEBUG
1739 bool FoundBuildIdentifier{false};
1740 bool FoundStoragePath{false};
1741 #endif
1742
1743 for (SPIRVExtInst *EI : BM->getDebugInstVec()) {
1744 if (EI->getExtOp() == SPIRVDebug::BuildIdentifier) {
1745 using namespace SPIRVDebug::Operand::BuildIdentifier;
1746 SPIRVWordVec BuildIdentifierArgs = EI->getArguments();
1747 assert(BuildIdentifierArgs.size() == OperandCount &&
1748 "Invalid number of operands");
1749 assert(!FoundBuildIdentifier &&
1750 "More than one BuildIdentifier instruction not allowed");
1751 BuildIdentifier = strtoull(
1752 getString(BuildIdentifierArgs[IdentifierIdx]).c_str(), NULL, 10);
1753 #ifndef NDEBUG
1754 FoundBuildIdentifier = true;
1755 #endif
1756 } else if (EI->getExtOp() == SPIRVDebug::StoragePath) {
1757 using namespace SPIRVDebug::Operand::StoragePath;
1758 SPIRVWordVec StoragePathArgs = EI->getArguments();
1759 assert(StoragePathArgs.size() == OperandCount &&
1760 "Invalid number of operands");
1761 assert(!FoundStoragePath &&
1762 "More than one StoragePath instruction not allowed");
1763 StoragePath = getString(StoragePathArgs[PathIdx]);
1764 #ifndef NDEBUG
1765 FoundStoragePath = true;
1766 #endif
1767 }
1768 }
1769 assert(((FoundBuildIdentifier && FoundStoragePath) ||
1770 (!FoundBuildIdentifier && !FoundStoragePath)) &&
1771 "BuildIdentifier and StoragePath must both be set or both unset");
1772 }
1773
1774 DIBuilder &SPIRVToLLVMDbgTran::getDIBuilder(const SPIRVExtInst *DebugInst) {
1775 assert(BuilderMap.size() != 0 && "No debug compile units");
1776 if (BuilderMap.size() == 1)
1777 return *BuilderMap.begin()->second;
1778 while (DebugInst->getExtOp() != SPIRVDebug::CompilationUnit) {
1779 if (DebugInst->getExtOp() == SPIRVDebug::DebugInfoNone)
1780 return *BuilderMap.begin()->second;
1781 const SPIRVWordVec &Ops = DebugInst->getArguments();
1782 SPIRVWord ParentScopeIdx = 0;
1783 if (!hasDbgInstParentScopeIdx(DebugInst->getExtOp(), ParentScopeIdx,
1784 DebugInst->getExtSetKind()))
1785 return *BuilderMap.begin()->second;
1786 if (SPIRVEntry *Scope = BM->getEntry(Ops[ParentScopeIdx])) {
1787 DebugInst = static_cast<SPIRVExtInst *>(Scope);
1788 continue;
1789 }
1790 return *BuilderMap.begin()->second;
1791 }
1792 return *BuilderMap[DebugInst->getId()];
1793 }
1794
1795 SPIRVToLLVMDbgTran::SplitFileName::SplitFileName(const string &FileName) {
1796 auto Loc = FileName.find_last_of("/\\");
1797 if (Loc != std::string::npos) {
1798 BaseName = FileName.substr(Loc + 1);
1799 Path = FileName.substr(0, Loc);
1800 } else {
1801 BaseName = FileName;
1802 Path = ".";
1803 }
1804 }
1805
1806 std::string SPIRVToLLVMDbgTran::findModuleProducer() {
1807 for (const auto &I : BM->getModuleProcessedVec()) {
1808 if (I->getProcessStr().find(SPIRVDebug::ProducerPrefix) !=
1809 std::string::npos) {
1810 return I->getProcessStr().substr(SPIRVDebug::ProducerPrefix.size());
1811 }
1812 }
1813 return "spirv";
1814 }
1815
1816 std::optional<DIFile::ChecksumInfo<StringRef>>
1817 SPIRVToLLVMDbgTran::ParseChecksum(StringRef Text) {
1818 // Example of "Text" variable:
1819 // "SomeInfo//__CSK_MD5:7bb56387968a9caa6e9e35fff94eaf7b:OtherInfo"
1820 std::optional<DIFile::ChecksumInfo<StringRef>> CS;
1821 auto KindPos = Text.find(SPIRVDebug::ChecksumKindPrefx);
1822 if (KindPos != StringRef::npos) {
1823 auto ColonPos = Text.find(":", KindPos);
1824 KindPos += string("//__").size();
1825 auto KindStr = Text.substr(KindPos, ColonPos - KindPos);
1826 auto Checksum = Text.substr(ColonPos).ltrim(':');
1827 if (auto Kind = DIFile::getChecksumKind(KindStr)) {
1828 size_t ChecksumEndPos = Checksum.find_if_not(llvm::isHexDigit);
1829 CS.emplace(Kind.value(), Checksum.substr(0, ChecksumEndPos));
1830 }
1831 }
1832 return CS;
1833 }
1834
1835 } // namespace SPIRV