Debian Codegraph @

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

raw
1 //===- LLVMToSPIRVDbgTran.cpp - Converts debug info to SPIR-V ---*- 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 LLVM metadata to SPIR-V
36 //
37 //===----------------------------------------------------------------------===//
38 #include "LLVMToSPIRVDbgTran.h"
39 #include "SPIRV.debug.h"
40 #include "SPIRVWriter.h"
41
42 #include "llvm/IR/DebugInfo.h"
43 #include "llvm/IR/DebugInfoMetadata.h"
44
45 using namespace SPIRV;
46
47 // Public interface
48
49 /// This function is looking for debug information in the LLVM module
50 /// and translates it to SPIRV
51 void LLVMToSPIRVDbgTran::transDebugMetadata() {
52 DIF.processModule(*M);
53 if (DIF.compile_unit_count() == 0)
54 return;
55
56 if (isNonSemanticDebugInfo()) {
57 if (!BM->isAllowedToUseVersion(VersionNumber::SPIRV_1_6))
58 BM->addExtension(SPIRV::ExtensionID::SPV_KHR_non_semantic_info);
59 else
60 BM->setMinSPIRVVersion(VersionNumber::SPIRV_1_6);
61 }
62
63 for (DICompileUnit *CU : DIF.compile_units()) {
64 transDbgEntry(CU);
65 for (DIImportedEntity *IE : CU->getImportedEntities())
66 transDbgEntry(IE);
67 }
68
69 for (const DIType *T : DIF.types())
70 transDbgEntry(T);
71
72 // When translating a debug lexical block, we expect the translation of its
73 // parent scope (say it's a subprogram) already been created in MDMap.
74 // Otherwise, we have to dive into the details of subprogram translation
75 // first. During this process, we will try to resolve all retainedNodes
76 // (aka, variables) owned by this subprogram.
77 // And local variable's scope could be the original lexical block that we
78 // haven't finish translating yet. In other words, the block hasn't been
79 // inserted into MDMap cache yet.
80 // So we try to invoke transDbgEntryImpl on the same lexical block again,
81 // then we get a duplicated lexical block messing up the debug info.
82 //
83 // Scheduling the translation of subprograms ahead of scopes (lexical blocks)
84 // solves this dependency cycle issue.
85 for (const DISubprogram *F : DIF.subprograms())
86 transDbgEntry(F);
87
88 for (const DIScope *S : DIF.scopes())
89 transDbgEntry(S);
90
91 for (const DIGlobalVariableExpression *G : DIF.global_variables()) {
92 transDbgEntry(G->getVariable());
93 }
94
95 for (const DbgVariableIntrinsic *DDI : DbgDeclareIntrinsics)
96 finalizeDebugDeclare(DDI);
97
98 for (const DbgVariableIntrinsic *DVI : DbgValueIntrinsics)
99 finalizeDebugValue(DVI);
100
101 transLocationInfo();
102 }
103
104 // llvm.dbg.declare intrinsic.
105
106 SPIRVValue *LLVMToSPIRVDbgTran::createDebugDeclarePlaceholder(
107 const DbgVariableIntrinsic *DbgDecl, SPIRVBasicBlock *BB) {
108 DbgDeclareIntrinsics.push_back(DbgDecl);
109 using namespace SPIRVDebug::Operand::DebugDeclare;
110 SPIRVWordVec Ops(OperandCount, getDebugInfoNoneId());
111 SPIRVId ExtSetId = BM->getExtInstSetId(BM->getDebugInfoEIS());
112 return BM->addExtInst(getVoidTy(), ExtSetId, SPIRVDebug::Declare, Ops, BB);
113 }
114
115 void LLVMToSPIRVDbgTran::finalizeDebugDeclare(
116 const DbgVariableIntrinsic *DbgDecl) {
117 SPIRVValue *V = SPIRVWriter->getTranslatedValue(DbgDecl);
118 assert(V && "llvm.dbg.declare intrinsic isn't mapped to a SPIRV instruction");
119 assert(V->isExtInst(BM->getDebugInfoEIS(), SPIRVDebug::Declare) &&
120 "llvm.dbg.declare intrinsic has been translated wrong!");
121 if (!V || !V->isExtInst(BM->getDebugInfoEIS(), SPIRVDebug::Declare))
122 return;
123 SPIRVExtInst *DD = static_cast<SPIRVExtInst *>(V);
124 SPIRVBasicBlock *BB = DD->getBasicBlock();
125 llvm::Value *Alloca = DbgDecl->getVariableLocationOp(0);
126
127 using namespace SPIRVDebug::Operand::DebugDeclare;
128 SPIRVWordVec Ops(OperandCount);
129 Ops[DebugLocalVarIdx] = transDbgEntry(DbgDecl->getVariable())->getId();
130 Ops[VariableIdx] = Alloca ? SPIRVWriter->transValue(Alloca, BB)->getId()
131 : getDebugInfoNoneId();
132 Ops[ExpressionIdx] = transDbgEntry(DbgDecl->getExpression())->getId();
133 DD->setArguments(Ops);
134 }
135
136 // llvm.dbg.value intrinsic.
137
138 SPIRVValue *LLVMToSPIRVDbgTran::createDebugValuePlaceholder(
139 const DbgVariableIntrinsic *DbgValue, SPIRVBasicBlock *BB) {
140 if (!DbgValue->getVariableLocationOp(0))
141 return nullptr; // It is pointless without new value
142
143 DbgValueIntrinsics.push_back(DbgValue);
144 using namespace SPIRVDebug::Operand::DebugValue;
145 SPIRVWordVec Ops(MinOperandCount, getDebugInfoNone()->getId());
146 SPIRVId ExtSetId = BM->getExtInstSetId(BM->getDebugInfoEIS());
147 return BM->addExtInst(getVoidTy(), ExtSetId, SPIRVDebug::Value, Ops, BB);
148 }
149
150 void LLVMToSPIRVDbgTran::finalizeDebugValue(
151 const DbgVariableIntrinsic *DbgValue) {
152 SPIRVValue *V = SPIRVWriter->getTranslatedValue(DbgValue);
153 assert(V && "llvm.dbg.value intrinsic isn't mapped to a SPIRV instruction");
154 assert(V->isExtInst(BM->getDebugInfoEIS(), SPIRVDebug::Value) &&
155 "llvm.dbg.value intrinsic has been translated wrong!");
156 if (!V || !V->isExtInst(BM->getDebugInfoEIS(), SPIRVDebug::Value))
157 return;
158 SPIRVExtInst *DV = static_cast<SPIRVExtInst *>(V);
159 SPIRVBasicBlock *BB = DV->getBasicBlock();
160 Value *Val = DbgValue->getVariableLocationOp(0);
161 DIExpression *Expr = DbgValue->getExpression();
162 if (DbgValue->getNumVariableLocationOps() > 1) {
163 Val = UndefValue::get(Val->getType());
164 Expr = DIExpression::get(M->getContext(), {});
165 }
166 using namespace SPIRVDebug::Operand::DebugValue;
167 SPIRVWordVec Ops(MinOperandCount);
168 Ops[DebugLocalVarIdx] = transDbgEntry(DbgValue->getVariable())->getId();
169 Ops[ValueIdx] = SPIRVWriter->transValue(Val, BB)->getId();
170 Ops[ExpressionIdx] = transDbgEntry(Expr)->getId();
171 DV->setArguments(Ops);
172 }
173
174 // Emitting DebugScope and OpLine instructions
175
176 void LLVMToSPIRVDbgTran::transLocationInfo() {
177 for (const Function &F : *M) {
178 for (const BasicBlock &BB : F) {
179 SPIRVValue *V = SPIRVWriter->getTranslatedValue(&BB);
180 assert(V && V->isBasicBlock() &&
181 "Basic block is expected to be translated");
182 SPIRVBasicBlock *SBB = static_cast<SPIRVBasicBlock *>(V);
183 MDNode *DbgScope = nullptr;
184 MDNode *InlinedAt = nullptr;
185 SPIRVString *File = nullptr;
186 unsigned LineNo = 0;
187 unsigned Col = 0;
188 for (const Instruction &I : BB) {
189 if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
190 if (II->getIntrinsicID() == Intrinsic::dbg_label) {
191 // SPIR-V doesn't support llvm.dbg.label intrinsic translation
192 continue;
193 }
194 if (II->getIntrinsicID() == Intrinsic::annotation ||
195 II->getIntrinsicID() == Intrinsic::var_annotation ||
196 II->getIntrinsicID() == Intrinsic::ptr_annotation) {
197 // llvm call instruction for llvm .*annotation intrinsics
198 // is translated into SPIR-V instruction only if it represents
199 // call of __builtin_intel_fpga_reg() builtin. In other cases this
200 // instruction is dropped. In these cases debug info for this call
201 // should be skipped too.
202 // TODO: Remove skipping of debug info when *.annotation call will
203 // be handled in a better way during SPIR-V translation.
204 V = SPIRVWriter->getTranslatedValue(&I);
205 if (!V || V->getOpCode() != OpFPGARegINTEL)
206 continue;
207 }
208 }
209 V = SPIRVWriter->getTranslatedValue(&I);
210 if (!V || isConstantOpCode(V->getOpCode()))
211 continue;
212 const DebugLoc &DL = I.getDebugLoc();
213 if (!DL.get()) {
214 if (DbgScope || InlinedAt) { // Emit DebugNoScope
215 DbgScope = nullptr;
216 InlinedAt = nullptr;
217 transDebugLoc(DL, SBB, static_cast<SPIRVInstruction *>(V));
218 }
219 continue;
220 }
221 // Once scope or inlining has changed emit another DebugScope
222 if (DL.getScope() != DbgScope || DL.getInlinedAt() != InlinedAt) {
223 DbgScope = DL.getScope();
224 InlinedAt = DL.getInlinedAt();
225 transDebugLoc(DL, SBB, static_cast<SPIRVInstruction *>(V));
226 }
227 // If any component of OpLine has changed emit another OpLine
228 SPIRVString *DirAndFile = BM->getString(getFullPath(DL.get()));
229 if (File != DirAndFile || LineNo != DL.getLine() ||
230 Col != DL.getCol()) {
231 File = DirAndFile;
232 LineNo = DL.getLine();
233 Col = DL.getCol();
234 // According to the spec, OpLine for an OpBranch/OpBranchConditional
235 // must precede the merge instruction and not the branch instruction
236 if (V->getOpCode() == OpBranch ||
237 V->getOpCode() == OpBranchConditional) {
238 auto *VPrev = static_cast<SPIRVInstruction *>(V)->getPrevious();
239 if (VPrev && (VPrev->getOpCode() == OpLoopMerge ||
240 VPrev->getOpCode() == OpLoopControlINTEL)) {
241 V = VPrev;
242 }
243 }
244 if (BM->getDebugInfoEIS() ==
245 SPIRVEIS_NonSemantic_Shader_DebugInfo_100 ||
246 BM->getDebugInfoEIS() ==
247 SPIRVEIS_NonSemantic_Shader_DebugInfo_200)
248 BM->addDebugLine(V, getVoidTy(),
249 File ? File->getId() : getDebugInfoNoneId(),
250 LineNo, LineNo, Col, Col + 1);
251 else
252 BM->addLine(V, File ? File->getId() : getDebugInfoNoneId(), LineNo,
253 Col);
254 }
255 } // Instructions
256 } // Basic Blocks
257 } // Functions
258 }
259
260 // Translation of single debug entry
261
262 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgEntry(const MDNode *DIEntry) {
263 // Caching
264 auto It = MDMap.find(DIEntry);
265 if (It != MDMap.end()) {
266 assert(It->second && "Invalid SPIRVEntry is cached!");
267 return It->second;
268 }
269 SPIRVEntry *Res = transDbgEntryImpl(DIEntry);
270 assert(Res && "Translation failure");
271 // We might end up having a recursive debug info generation like the
272 // following:
273 // translation of DIDerivedType (member) calls DICompositeType translation
274 // as its parent scope;
275 // translation of DICompositeType calls translation of its members
276 // (DIDerivedType with member tag).
277 // Here we make only the latest of these instructions be cached and hence
278 // reused
279 // FIXME: find a way to not create dead instruction
280 if (MDMap[DIEntry])
281 return MDMap[DIEntry];
282 MDMap[DIEntry] = Res;
283 return Res;
284 }
285
286 // Dispatcher implementation
287
288 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgEntryImpl(const MDNode *MDN) {
289 if (!MDN)
290 return BM->addDebugInfo(SPIRVDebug::DebugInfoNone, getVoidTy(),
291 SPIRVWordVec());
292 if (const DINode *DIEntry = dyn_cast<DINode>(MDN)) {
293 switch (DIEntry->getTag()) {
294 // Types
295 case dwarf::DW_TAG_base_type:
296 case dwarf::DW_TAG_unspecified_type:
297 return transDbgBaseType(cast<DIBasicType>(DIEntry));
298
299 case dwarf::DW_TAG_reference_type:
300 case dwarf::DW_TAG_rvalue_reference_type:
301 case dwarf::DW_TAG_pointer_type:
302 return transDbgPointerType(cast<DIDerivedType>(DIEntry));
303
304 case dwarf::DW_TAG_array_type:
305 return transDbgArrayType(cast<DICompositeType>(DIEntry));
306
307 case dwarf::DW_TAG_subrange_type:
308 if (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200)
309 return transDbgSubrangeType(cast<DISubrange>(DIEntry));
310 else
311 return getDebugInfoNone();
312
313 case dwarf::DW_TAG_string_type: {
314 if (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200)
315 return transDbgStringType(cast<DIStringType>(DIEntry));
316 return getDebugInfoNone();
317 }
318
319 case dwarf::DW_TAG_const_type:
320 case dwarf::DW_TAG_restrict_type:
321 case dwarf::DW_TAG_volatile_type:
322 case dwarf::DW_TAG_atomic_type:
323 return transDbgQualifiedType(cast<DIDerivedType>(DIEntry));
324
325 case dwarf::DW_TAG_subroutine_type:
326 return transDbgSubroutineType(cast<DISubroutineType>(DIEntry));
327
328 case dwarf::DW_TAG_class_type:
329 case dwarf::DW_TAG_structure_type:
330 case dwarf::DW_TAG_union_type:
331 return transDbgCompositeType(cast<DICompositeType>(DIEntry));
332
333 case dwarf::DW_TAG_member:
334 return transDbgMemberType(cast<DIDerivedType>(DIEntry));
335
336 case dwarf::DW_TAG_inheritance:
337 return transDbgInheritance(cast<DIDerivedType>(DIEntry));
338
339 case dwarf::DW_TAG_enumeration_type:
340 return transDbgEnumType(cast<DICompositeType>(DIEntry));
341
342 case dwarf::DW_TAG_file_type:
343 return transDbgFileType(cast<DIFile>(DIEntry));
344
345 case dwarf::DW_TAG_typedef:
346 return transDbgTypeDef(cast<DIDerivedType>(DIEntry));
347
348 case dwarf::DW_TAG_ptr_to_member_type:
349 return transDbgPtrToMember(cast<DIDerivedType>(DIEntry));
350
351 // Scope
352 case dwarf::DW_TAG_namespace:
353 case dwarf::DW_TAG_lexical_block:
354 return transDbgScope(cast<DIScope>(DIEntry));
355
356 // Function
357 case dwarf::DW_TAG_subprogram:
358 return transDbgFunction(cast<DISubprogram>(DIEntry));
359
360 // Variables
361 case dwarf::DW_TAG_variable:
362 if (const DILocalVariable *LV = dyn_cast<DILocalVariable>(DIEntry))
363 return transDbgLocalVariable(LV);
364 if (const DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(DIEntry))
365 return transDbgGlobalVariable(GV);
366 llvm_unreachable("Unxpected debug info type for variable");
367 case dwarf::DW_TAG_formal_parameter:
368 return transDbgLocalVariable(cast<DILocalVariable>(DIEntry));
369
370 // Compilation unit
371 case dwarf::DW_TAG_compile_unit:
372 return transDbgCompileUnit(cast<DICompileUnit>(DIEntry));
373
374 // Templates
375 case dwarf::DW_TAG_template_type_parameter:
376 case dwarf::DW_TAG_template_value_parameter:
377 return transDbgTemplateParameter(cast<DITemplateParameter>(DIEntry));
378 case dwarf::DW_TAG_GNU_template_template_param:
379 return transDbgTemplateTemplateParameter(
380 cast<DITemplateValueParameter>(DIEntry));
381 case dwarf::DW_TAG_GNU_template_parameter_pack:
382 return transDbgTemplateParameterPack(
383 cast<DITemplateValueParameter>(DIEntry));
384
385 case dwarf::DW_TAG_imported_module:
386 case dwarf::DW_TAG_imported_declaration:
387 return transDbgImportedEntry(cast<DIImportedEntity>(DIEntry));
388
389 case dwarf::DW_TAG_module: {
390 if (BM->isAllowedToUseExtension(ExtensionID::SPV_INTEL_debug_module) ||
391 BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200)
392 return transDbgModule(cast<DIModule>(DIEntry));
393 return getDebugInfoNone();
394 }
395
396 default:
397 return getDebugInfoNone();
398 }
399 }
400 if (const DIExpression *Expr = dyn_cast<DIExpression>(MDN))
401 return transDbgExpression(Expr);
402
403 if (const DILocation *Loc = dyn_cast<DILocation>(MDN)) {
404 return transDbgInlinedAt(Loc);
405 }
406 llvm_unreachable("Not implemented debug info entry!");
407 }
408
409 // Helper methods
410
411 SPIRVType *LLVMToSPIRVDbgTran::getVoidTy() {
412 if (!VoidT) {
413 assert(M && "Pointer to LLVM Module is expected to be initialized!");
414 // Cache void type in a member.
415 VoidT = SPIRVWriter->transType(Type::getVoidTy(M->getContext()));
416 }
417 return VoidT;
418 }
419
420 SPIRVType *LLVMToSPIRVDbgTran::getInt32Ty() {
421 if (!Int32T) {
422 assert(M && "Pointer to LLVM Module is expected to be initialized!");
423 // Cache int32 type in a member.
424 Int32T = SPIRVWriter->transType(Type::getInt32Ty(M->getContext()));
425 }
426 return Int32T;
427 }
428
429 SPIRVEntry *LLVMToSPIRVDbgTran::getScope(DIScope *S) {
430 if (S)
431 return transDbgEntry(S);
432 assert(!SPIRVCUMap.empty() &&
433 "Compile units are expected to be already translated");
434 return SPIRVCUMap.begin()->second;
435 }
436
437 SPIRVEntry *LLVMToSPIRVDbgTran::getGlobalVariable(const DIGlobalVariable *GV) {
438 for (GlobalVariable &V : M->globals()) {
439 SmallVector<DIGlobalVariableExpression *, 4> GVs;
440 V.getDebugInfo(GVs);
441 for (DIGlobalVariableExpression *GVE : GVs) {
442 if (GVE->getVariable() == GV)
443 return SPIRVWriter->transValue(&V, nullptr);
444 }
445 }
446 return getDebugInfoNone();
447 }
448
449 inline bool LLVMToSPIRVDbgTran::isNonSemanticDebugInfo() {
450 return (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_100 ||
451 BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200);
452 }
453
454 void LLVMToSPIRVDbgTran::transformToConstant(std::vector<SPIRVWord> &Ops,
455 std::vector<SPIRVWord> Idxs) {
456 for (const auto Idx : Idxs) {
457 SPIRVValue *Const = BM->addIntegerConstant(
458 static_cast<SPIRVTypeInt *>(getInt32Ty()), Ops[Idx]);
459 Ops[Idx] = Const->getId();
460 }
461 }
462
463 SPIRVWord LLVMToSPIRVDbgTran::mapDebugFlags(DINode::DIFlags DFlags) {
464 SPIRVWord Flags = 0;
465 if ((DFlags & DINode::FlagAccessibility) == DINode::FlagPublic)
466 Flags |= SPIRVDebug::FlagIsPublic;
467 if ((DFlags & DINode::FlagAccessibility) == DINode::FlagProtected)
468 Flags |= SPIRVDebug::FlagIsProtected;
469 if ((DFlags & DINode::FlagAccessibility) == DINode::FlagPrivate)
470 Flags |= SPIRVDebug::FlagIsPrivate;
471
472 if (DFlags & DINode::FlagFwdDecl)
473 Flags |= SPIRVDebug::FlagIsFwdDecl;
474 if (DFlags & DINode::FlagArtificial)
475 Flags |= SPIRVDebug::FlagIsArtificial;
476 if (DFlags & DINode::FlagExplicit)
477 Flags |= SPIRVDebug::FlagIsExplicit;
478 if (DFlags & DINode::FlagPrototyped)
479 Flags |= SPIRVDebug::FlagIsPrototyped;
480 if (DFlags & DINode::FlagObjectPointer)
481 Flags |= SPIRVDebug::FlagIsObjectPointer;
482 if (DFlags & DINode::FlagStaticMember)
483 Flags |= SPIRVDebug::FlagIsStaticMember;
484 // inderect variable flag ?
485 if (DFlags & DINode::FlagLValueReference)
486 Flags |= SPIRVDebug::FlagIsLValueReference;
487 if (DFlags & DINode::FlagRValueReference)
488 Flags |= SPIRVDebug::FlagIsRValueReference;
489 if (DFlags & DINode::FlagTypePassByValue)
490 Flags |= SPIRVDebug::FlagTypePassByValue;
491 if (DFlags & DINode::FlagTypePassByReference)
492 Flags |= SPIRVDebug::FlagTypePassByReference;
493 if (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200)
494 if (DFlags & DINode::FlagBitField)
495 Flags |= SPIRVDebug::FlagBitField;
496 if (DFlags & DINode::FlagEnumClass)
497 Flags |= SPIRVDebug::FlagIsEnumClass;
498 return Flags;
499 }
500
501 SPIRVWord LLVMToSPIRVDbgTran::transDebugFlags(const DINode *DN) {
502 SPIRVWord Flags = 0;
503 if (const DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(DN)) {
504 if (GV->isLocalToUnit())
505 Flags |= SPIRVDebug::FlagIsLocal;
506 if (GV->isDefinition())
507 Flags |= SPIRVDebug::FlagIsDefinition;
508 }
509 if (const DISubprogram *DS = dyn_cast<DISubprogram>(DN)) {
510 if (DS->isLocalToUnit())
511 Flags |= SPIRVDebug::FlagIsLocal;
512 if (DS->isOptimized())
513 Flags |= SPIRVDebug::FlagIsOptimized;
514 if (DS->isDefinition())
515 Flags |= SPIRVDebug::FlagIsDefinition;
516 Flags |= mapDebugFlags(DS->getFlags());
517 }
518 if (DN->getTag() == dwarf::DW_TAG_reference_type)
519 Flags |= SPIRVDebug::FlagIsLValueReference;
520 if (DN->getTag() == dwarf::DW_TAG_rvalue_reference_type)
521 Flags |= SPIRVDebug::FlagIsRValueReference;
522 if (const DIType *DT = dyn_cast<DIType>(DN))
523 Flags |= mapDebugFlags(DT->getFlags());
524 if (const DILocalVariable *DLocVar = dyn_cast<DILocalVariable>(DN))
525 Flags |= mapDebugFlags(DLocVar->getFlags());
526
527 return Flags;
528 }
529
530 /// Clang doesn't emit access flags for members with default access specifier
531 /// See clang/lib/CodeGen/CGDebugInfo.cpp: getAccessFlag()
532 /// In SPIR-V we set the flags even for members with default access specifier
533 SPIRVWord adjustAccessFlags(DIScope *Scope, SPIRVWord Flags) {
534 if (Scope && (Flags & SPIRVDebug::FlagAccess) == 0) {
535 unsigned Tag = Scope->getTag();
536 if (Tag == dwarf::DW_TAG_class_type)
537 Flags |= SPIRVDebug::FlagIsPrivate;
538 else if (Tag == dwarf::DW_TAG_structure_type ||
539 Tag == dwarf::DW_TAG_union_type)
540 Flags |= SPIRVDebug::FlagIsPublic;
541 }
542 return Flags;
543 }
544
545 // Fortran dynamic arrays can have following 'dataLocation', 'associated'
546 // 'allocated' and 'rank' debug metadata. Such arrays are being mapped on
547 // DebugTypeArrayDynamic from NonSemantic.Shader.200 debug spec
548 inline bool isFortranArrayDynamic(const DICompositeType *AT) {
549 return (AT->getRawDataLocation() || AT->getRawAssociated() ||
550 AT->getRawAllocated() || AT->getRawRank());
551 }
552
553 /// The following methods (till the end of the file) implement translation of
554 /// debug instrtuctions described in the spec.
555
556 // Absent Debug Info
557
558 SPIRVEntry *LLVMToSPIRVDbgTran::getDebugInfoNone() {
559 if (!DebugInfoNone) {
560 DebugInfoNone = transDbgEntry(nullptr);
561 }
562 return DebugInfoNone;
563 }
564
565 SPIRVId LLVMToSPIRVDbgTran::getDebugInfoNoneId() {
566 return getDebugInfoNone()->getId();
567 }
568
569 // Compilation unit
570
571 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgCompileUnit(const DICompileUnit *CU) {
572 using namespace SPIRVDebug::Operand::CompilationUnit;
573 SPIRVWordVec Ops(MinOperandCount);
574 Ops[SPIRVDebugInfoVersionIdx] = SPIRVDebug::DebugInfoVersion;
575 Ops[DWARFVersionIdx] = M->getDwarfVersion();
576 Ops[SourceIdx] = getSource(CU)->getId();
577
578 if (isNonSemanticDebugInfo())
579 generateBuildIdentifierAndStoragePath(CU);
580
581 auto DwarfLang =
582 static_cast<llvm::dwarf::SourceLanguage>(CU->getSourceLanguage());
583 Ops[LanguageIdx] =
584 BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200
585 ? convertDWARFSourceLangToSPIRVNonSemanticDbgInfo(DwarfLang)
586 : convertDWARFSourceLangToSPIRV(DwarfLang);
587 if (isNonSemanticDebugInfo())
588 transformToConstant(
589 Ops, {SPIRVDebugInfoVersionIdx, DWARFVersionIdx, LanguageIdx});
590
591 if (isNonSemanticDebugInfo()) {
592 if (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200) {
593 Ops.push_back(BM->getString(CU->getProducer().str())->getId());
594 }
595 } else {
596 // TODO: Remove this workaround once we switch to NonSemantic.Shader.* debug
597 // info by default
598 BM->addModuleProcessed(SPIRVDebug::ProducerPrefix +
599 CU->getProducer().str());
600 }
601 // Cache CU in a member.
602 SPIRVCUMap[CU] = static_cast<SPIRVExtInst *>(
603 BM->addDebugInfo(SPIRVDebug::CompilationUnit, getVoidTy(), Ops));
604 return SPIRVCUMap[CU];
605 }
606
607 // Types
608
609 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgBaseType(const DIBasicType *BT) {
610 using namespace SPIRVDebug::Operand::TypeBasic;
611 SPIRVWordVec Ops(OperandCountOCL);
612 Ops[NameIdx] = BM->getString(BT->getName().str())->getId();
613 ConstantInt *Size = getUInt(M, BT->getSizeInBits());
614 Ops[SizeIdx] = SPIRVWriter->transValue(Size, nullptr)->getId();
615 auto Encoding = static_cast<dwarf::TypeKind>(BT->getEncoding());
616 SPIRVDebug::EncodingTag EncTag = SPIRVDebug::Unspecified;
617 SPIRV::DbgEncodingMap::find(Encoding, &EncTag);
618 // Unset encoding if it's complex and NonSemantic.Shader.DebugInfo.200 is not
619 // enabled
620 if (EncTag == SPIRVDebug::Complex &&
621 BM->getDebugInfoEIS() != SPIRVEIS_NonSemantic_Shader_DebugInfo_200)
622 EncTag = SPIRVDebug::Unspecified;
623 Ops[EncodingIdx] = EncTag;
624 if (isNonSemanticDebugInfo()) {
625 transformToConstant(Ops, {EncodingIdx});
626 // Flags value could not be generated by clang or by LLVM environment.
627 Ops.push_back(getDebugInfoNoneId());
628 }
629 return BM->addDebugInfo(SPIRVDebug::TypeBasic, getVoidTy(), Ops);
630 }
631
632 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgPointerType(const DIDerivedType *PT) {
633 using namespace SPIRVDebug::Operand::TypePointer;
634 SPIRVWordVec Ops(OperandCount);
635 SPIRVEntry *Base = transDbgEntry(PT->getBaseType());
636 Ops[BaseTypeIdx] = Base->getId();
637 Ops[StorageClassIdx] = ~0U; // all ones denote no address space
638 std::optional<unsigned> AS = PT->getDWARFAddressSpace();
639 if (AS.has_value()) {
640 SPIRAddressSpace SPIRAS = static_cast<SPIRAddressSpace>(AS.value());
641 Ops[StorageClassIdx] = SPIRSPIRVAddrSpaceMap::map(SPIRAS);
642 }
643 Ops[FlagsIdx] = transDebugFlags(PT);
644 if (isNonSemanticDebugInfo())
645 transformToConstant(Ops, {StorageClassIdx, FlagsIdx});
646 SPIRVEntry *Res = BM->addDebugInfo(SPIRVDebug::TypePointer, getVoidTy(), Ops);
647 return Res;
648 }
649
650 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgQualifiedType(const DIDerivedType *QT) {
651 using namespace SPIRVDebug::Operand::TypeQualifier;
652 SPIRVWordVec Ops(OperandCount);
653 SPIRVEntry *Base = transDbgEntry(QT->getBaseType());
654 Ops[BaseTypeIdx] = Base->getId();
655 Ops[QualifierIdx] = SPIRV::DbgTypeQulifierMap::map(
656 static_cast<llvm::dwarf::Tag>(QT->getTag()));
657 if (isNonSemanticDebugInfo())
658 transformToConstant(Ops, {QualifierIdx});
659 return BM->addDebugInfo(SPIRVDebug::TypeQualifier, getVoidTy(), Ops);
660 }
661
662 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgArrayType(const DICompositeType *AT) {
663 if (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200) {
664 if (isFortranArrayDynamic(AT))
665 return transDbgArrayTypeDynamic(AT);
666 return transDbgArrayTypeNonSemantic(AT);
667 }
668
669 return transDbgArrayTypeOpenCL(AT);
670 }
671
672 SPIRVEntry *
673 LLVMToSPIRVDbgTran::transDbgArrayTypeOpenCL(const DICompositeType *AT) {
674 using namespace SPIRVDebug::Operand::TypeArray;
675 SPIRVWordVec Ops(MinOperandCount);
676 Ops[BaseTypeIdx] = transDbgEntry(AT->getBaseType())->getId();
677
678 DINodeArray AR(AT->getElements());
679 // For N-dimensianal arrays AR.getNumElements() == N
680 const unsigned N = AR.size();
681 Ops.resize(ComponentCountIdx + N);
682 SPIRVWordVec LowerBounds(N);
683 for (unsigned I = 0; I < N; ++I) {
684 DISubrange *SR = cast<DISubrange>(AR[I]);
685 ConstantInt *Count = SR->getCount().get<ConstantInt *>();
686 if (AT->isVector()) {
687 assert(N == 1 && "Multidimensional vector is not expected!");
688 Ops[ComponentCountIdx] = static_cast<SPIRVWord>(Count->getZExtValue());
689 if (isNonSemanticDebugInfo())
690 transformToConstant(Ops, {ComponentCountIdx});
691 return BM->addDebugInfo(SPIRVDebug::TypeVector, getVoidTy(), Ops);
692 }
693 if (Count) {
694 Ops[ComponentCountIdx + I] =
695 SPIRVWriter->transValue(Count, nullptr)->getId();
696 } else {
697 if (auto *UpperBound = dyn_cast<MDNode>(SR->getRawUpperBound()))
698 Ops[ComponentCountIdx + I] = transDbgEntry(UpperBound)->getId();
699 else
700 Ops[ComponentCountIdx + I] = getDebugInfoNoneId();
701 }
702 if (auto *RawLB = SR->getRawLowerBound()) {
703 if (auto *DIExprLB = dyn_cast<MDNode>(RawLB))
704 LowerBounds[I] = transDbgEntry(DIExprLB)->getId();
705 else {
706 ConstantInt *ConstIntLB = SR->getLowerBound().get<ConstantInt *>();
707 LowerBounds[I] = SPIRVWriter->transValue(ConstIntLB, nullptr)->getId();
708 }
709 } else {
710 LowerBounds[I] = getDebugInfoNoneId();
711 }
712 }
713 Ops.insert(Ops.end(), LowerBounds.begin(), LowerBounds.end());
714 return BM->addDebugInfo(SPIRVDebug::TypeArray, getVoidTy(), Ops);
715 }
716
717 SPIRVEntry *
718 LLVMToSPIRVDbgTran::transDbgArrayTypeNonSemantic(const DICompositeType *AT) {
719 using namespace SPIRVDebug::Operand::TypeArray;
720 SPIRVWordVec Ops(MinOperandCount);
721 Ops[BaseTypeIdx] = transDbgEntry(AT->getBaseType())->getId();
722
723 DINodeArray AR(AT->getElements());
724 // For N-dimensianal arrays AR.getNumElements() == N
725 const unsigned N = AR.size();
726 Ops.resize(SubrangesIdx + N);
727 for (unsigned I = 0; I < N; ++I) {
728 DISubrange *SR = cast<DISubrange>(AR[I]);
729 ConstantInt *Count = SR->getCount().get<ConstantInt *>();
730 if (AT->isVector()) {
731 assert(N == 1 && "Multidimensional vector is not expected!");
732 Ops[ComponentCountIdx] = static_cast<SPIRVWord>(Count->getZExtValue());
733 if (isNonSemanticDebugInfo())
734 transformToConstant(Ops, {ComponentCountIdx});
735 return BM->addDebugInfo(SPIRVDebug::TypeVector, getVoidTy(), Ops);
736 }
737 Ops[SubrangesIdx + I] = transDbgEntry(SR)->getId();
738 }
739 return BM->addDebugInfo(SPIRVDebug::TypeArray, getVoidTy(), Ops);
740 }
741
742 // The function is used to translate Fortran's dynamic arrays
743 SPIRVEntry *
744 LLVMToSPIRVDbgTran::transDbgArrayTypeDynamic(const DICompositeType *AT) {
745 using namespace SPIRVDebug::Operand::TypeArrayDynamic;
746 SPIRVWordVec Ops(MinOperandCount);
747 Ops[BaseTypeIdx] = transDbgEntry(AT->getBaseType())->getId();
748
749 // DataLocation, Associated, Allocated and Rank can be either DIExpression
750 // metadata or DIVariable
751 auto TransOperand = [&](llvm::Metadata *DIMD) -> SPIRVWord {
752 if (auto *DIExpr = dyn_cast_or_null<DIExpression>(DIMD))
753 return transDbgExpression(DIExpr)->getId();
754 if (auto *DIVar = dyn_cast_or_null<DIVariable>(DIMD)) {
755 if (const DILocalVariable *LV = dyn_cast<DILocalVariable>(DIVar))
756 return transDbgLocalVariable(LV)->getId();
757 if (const DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(DIVar))
758 return transDbgGlobalVariable(GV)->getId();
759 }
760 return getDebugInfoNoneId();
761 };
762
763 Ops[DataLocationIdx] = TransOperand(AT->getRawDataLocation());
764 Ops[AssociatedIdx] = TransOperand(AT->getRawAssociated());
765 Ops[AllocatedIdx] = TransOperand(AT->getRawAllocated());
766 Ops[RankIdx] = TransOperand(AT->getRawRank());
767
768 DINodeArray AR(AT->getElements());
769 // For N-dimensianal arrays AR.getNumElements() == N
770 const unsigned N = AR.size();
771 Ops.resize(SubrangesIdx + N);
772 for (unsigned I = 0; I < N; ++I) {
773 DISubrange *SR = cast<DISubrange>(AR[I]);
774 Ops[SubrangesIdx + I] = transDbgEntry(SR)->getId();
775 }
776 return BM->addDebugInfo(SPIRVDebug::TypeArrayDynamic, getVoidTy(), Ops);
777 }
778
779 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgSubrangeType(const DISubrange *ST) {
780 using namespace SPIRVDebug::Operand::TypeSubrange;
781 SPIRVWordVec Ops(MinOperandCount);
782 auto TransOperand = [&Ops, this, ST](int Idx) -> void {
783 Metadata *RawNode = nullptr;
784 switch (Idx) {
785 case LowerBoundIdx:
786 RawNode = ST->getRawLowerBound();
787 break;
788 case UpperBoundIdx:
789 RawNode = ST->getRawUpperBound();
790 break;
791 case CountIdx:
792 RawNode = ST->getRawCountNode();
793 break;
794 }
795 if (!RawNode) {
796 Ops[Idx] = getDebugInfoNoneId();
797 return;
798 }
799 if (auto *Node = dyn_cast<MDNode>(RawNode)) {
800 Ops[Idx] = transDbgEntry(Node)->getId();
801 } else {
802 ConstantInt *IntNode = nullptr;
803 switch (Idx) {
804 case LowerBoundIdx:
805 IntNode = ST->getLowerBound().get<ConstantInt *>();
806 break;
807 case UpperBoundIdx:
808 IntNode = ST->getUpperBound().get<ConstantInt *>();
809 break;
810 case CountIdx:
811 IntNode = ST->getCount().get<ConstantInt *>();
812 break;
813 case StrideIdx:
814 IntNode = ST->getStride().get<ConstantInt *>();
815 break;
816 }
817 Ops[Idx] = IntNode ? SPIRVWriter->transValue(IntNode, nullptr)->getId()
818 : getDebugInfoNoneId();
819 }
820 };
821 for (int Idx = 0; Idx < MinOperandCount; ++Idx)
822 TransOperand(Idx);
823 if (auto *RawNode = ST->getRawStride()) {
824 Ops.resize(MaxOperandCount);
825 if (auto *Node = dyn_cast<MDNode>(RawNode))
826 Ops[StrideIdx] = transDbgEntry(Node)->getId();
827 else
828 Ops[StrideIdx] =
829 SPIRVWriter->transValue(ST->getStride().get<ConstantInt *>(), nullptr)
830 ->getId();
831 }
832 return BM->addDebugInfo(SPIRVDebug::TypeSubrange, getVoidTy(), Ops);
833 }
834
835 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgStringType(const DIStringType *ST) {
836 using namespace SPIRVDebug::Operand::TypeString;
837 SPIRVWordVec Ops(MinOperandCount);
838 Ops[NameIdx] = BM->getString(ST->getName().str())->getId();
839
840 Ops[BaseTypeIdx] = ST->getEncoding()
841 ? getDebugInfoNoneId() /*TODO: replace with basetype*/
842 : getDebugInfoNoneId();
843
844 auto TransOperand = [&](llvm::Metadata *DIMD) -> SPIRVWord {
845 if (auto *DIExpr = dyn_cast_or_null<DIExpression>(DIMD))
846 return transDbgExpression(DIExpr)->getId();
847 if (auto *DIVar = dyn_cast_or_null<DIVariable>(DIMD)) {
848 if (const DILocalVariable *LV = dyn_cast<DILocalVariable>(DIVar))
849 return transDbgLocalVariable(LV)->getId();
850 if (const DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(DIVar))
851 return transDbgGlobalVariable(GV)->getId();
852 }
853 return getDebugInfoNoneId();
854 };
855
856 Ops[DataLocationIdx] = TransOperand(ST->getRawStringLocationExp());
857
858 ConstantInt *Size = getUInt(M, ST->getSizeInBits());
859 Ops[SizeIdx] = SPIRVWriter->transValue(Size, nullptr)->getId();
860
861 if (auto *StrLengthExp = ST->getRawStringLengthExp()) {
862 Ops[LengthAddrIdx] = TransOperand(StrLengthExp);
863 } else if (auto *StrLengthVar = ST->getRawStringLength()) {
864 Ops[LengthAddrIdx] = TransOperand(StrLengthVar);
865 } else {
866 Ops[LengthAddrIdx] = getDebugInfoNoneId();
867 }
868
869 return BM->addDebugInfo(SPIRVDebug::TypeString, getVoidTy(), Ops);
870 }
871
872 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgTypeDef(const DIDerivedType *DT) {
873 using namespace SPIRVDebug::Operand::Typedef;
874 SPIRVWordVec Ops(OperandCount);
875 Ops[NameIdx] = BM->getString(DT->getName().str())->getId();
876 SPIRVEntry *BaseTy = transDbgEntry(DT->getBaseType());
877 assert(BaseTy && "Couldn't translate base type!");
878 Ops[BaseTypeIdx] = BaseTy->getId();
879 Ops[SourceIdx] = getSource(DT)->getId();
880 Ops[LineIdx] = 0; // This version of DIDerivedType has no line number
881 Ops[ColumnIdx] = 0; // This version of DIDerivedType has no column number
882 SPIRVEntry *Scope = getScope(DT->getScope());
883 assert(Scope && "Couldn't translate scope!");
884 Ops[ParentIdx] = Scope->getId();
885 if (isNonSemanticDebugInfo())
886 transformToConstant(Ops, {LineIdx, ColumnIdx});
887 return BM->addDebugInfo(SPIRVDebug::Typedef, getVoidTy(), Ops);
888 }
889
890 SPIRVEntry *
891 LLVMToSPIRVDbgTran::transDbgSubroutineType(const DISubroutineType *FT) {
892 using namespace SPIRVDebug::Operand::TypeFunction;
893 SPIRVWordVec Ops(MinOperandCount);
894 Ops[FlagsIdx] = transDebugFlags(FT);
895
896 DITypeRefArray Types = FT->getTypeArray();
897 const size_t NumElements = Types.size();
898 if (NumElements) {
899 Ops.resize(1 + NumElements);
900 // First element of the TypeArray is the type of the return value,
901 // followed by types of the function arguments' types.
902 // The same order is preserved in SPIRV.
903 for (unsigned I = 0; I < NumElements; ++I)
904 Ops[ReturnTypeIdx + I] = transDbgEntry(Types[I])->getId();
905 } else { // void foo();
906 Ops[ReturnTypeIdx] = getVoidTy()->getId();
907 }
908
909 if (isNonSemanticDebugInfo())
910 transformToConstant(Ops, {FlagsIdx});
911 return BM->addDebugInfo(SPIRVDebug::TypeFunction, getVoidTy(), Ops);
912 }
913
914 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgEnumType(const DICompositeType *ET) {
915 using namespace SPIRVDebug::Operand::TypeEnum;
916 SPIRVWordVec Ops(MinOperandCount);
917
918 SPIRVEntry *UnderlyingType = getVoidTy();
919 if (DIType *DerivedFrom = ET->getBaseType())
920 UnderlyingType = transDbgEntry(DerivedFrom);
921 ConstantInt *Size = getUInt(M, ET->getSizeInBits());
922
923 Ops[NameIdx] = BM->getString(ET->getName().str())->getId();
924 Ops[UnderlyingTypeIdx] = UnderlyingType->getId();
925 Ops[SourceIdx] = getSource(ET)->getId();
926 Ops[LineIdx] = ET->getLine();
927 Ops[ColumnIdx] = 0; // This version of DICompositeType has no column number
928 Ops[ParentIdx] = getScope(ET->getScope())->getId();
929 Ops[SizeIdx] = SPIRVWriter->transValue(Size, nullptr)->getId();
930 Ops[FlagsIdx] = transDebugFlags(ET);
931
932 DINodeArray Elements = ET->getElements();
933 size_t ElemCount = Elements.size();
934 for (unsigned I = 0; I < ElemCount; ++I) {
935 DIEnumerator *E = cast<DIEnumerator>(Elements[I]);
936 ConstantInt *EnumValue = getInt(M, E->getValue().getSExtValue());
937 SPIRVValue *Val = SPIRVWriter->transValue(EnumValue, nullptr);
938 assert(Val->getOpCode() == OpConstant &&
939 "LLVM constant must be translated to SPIRV constant");
940 Ops.push_back(Val->getId());
941 SPIRVString *Name = BM->getString(E->getName().str());
942 Ops.push_back(Name->getId());
943 }
944 if (isNonSemanticDebugInfo())
945 transformToConstant(Ops, {LineIdx, ColumnIdx, FlagsIdx});
946 return BM->addDebugInfo(SPIRVDebug::TypeEnum, getVoidTy(), Ops);
947 }
948
949 SPIRVEntry *
950 LLVMToSPIRVDbgTran::transDbgCompositeType(const DICompositeType *CT) {
951 using namespace SPIRVDebug::Operand::TypeComposite;
952 SPIRVWordVec Ops(MinOperandCount);
953
954 SPIRVForward *Tmp = BM->addForward(nullptr);
955 MDMap.insert(std::make_pair(CT, Tmp));
956
957 auto Tag = static_cast<dwarf::Tag>(CT->getTag());
958 SPIRVId UniqId = getDebugInfoNoneId();
959 StringRef Identifier = CT->getIdentifier();
960 if (!Identifier.empty())
961 UniqId = BM->getString(Identifier.str())->getId();
962 ConstantInt *Size = getUInt(M, CT->getSizeInBits());
963
964 Ops[NameIdx] = BM->getString(CT->getName().str())->getId();
965 Ops[TagIdx] = SPIRV::DbgCompositeTypeMap::map(Tag);
966 Ops[SourceIdx] = getSource(CT)->getId();
967 Ops[LineIdx] = CT->getLine();
968 Ops[ColumnIdx] = 0; // This version of DICompositeType has no column number
969 Ops[ParentIdx] = getScope(CT->getScope())->getId();
970 Ops[LinkageNameIdx] = UniqId;
971 Ops[SizeIdx] = SPIRVWriter->transValue(Size, nullptr)->getId();
972 Ops[FlagsIdx] = transDebugFlags(CT);
973
974 for (DINode *N : CT->getElements()) {
975 Ops.push_back(transDbgEntry(N)->getId());
976 }
977
978 if (isNonSemanticDebugInfo())
979 transformToConstant(Ops, {TagIdx, LineIdx, ColumnIdx, FlagsIdx});
980 SPIRVEntry *Res =
981 BM->addDebugInfo(SPIRVDebug::TypeComposite, getVoidTy(), Ops);
982
983 // Translate template parameters.
984 if (DITemplateParameterArray TP = CT->getTemplateParams()) {
985 const unsigned int NumTParams = TP.size();
986 SPIRVWordVec Args(1 + NumTParams);
987 Args[0] = Res->getId();
988 for (unsigned int I = 0; I < NumTParams; ++I) {
989 Args[I + 1] = transDbgEntry(TP[I])->getId();
990 }
991 Res = BM->addDebugInfo(SPIRVDebug::TypeTemplate, getVoidTy(), Args);
992 }
993 BM->replaceForward(Tmp, Res);
994 MDMap[CT] = Res;
995 return Res;
996 }
997
998 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgMemberType(const DIDerivedType *MT) {
999 if (isNonSemanticDebugInfo())
1000 return transDbgMemberTypeNonSemantic(MT);
1001 return transDbgMemberTypeOpenCL(MT);
1002 }
1003
1004 SPIRVEntry *
1005 LLVMToSPIRVDbgTran::transDbgMemberTypeOpenCL(const DIDerivedType *MT) {
1006 using namespace SPIRVDebug::Operand::TypeMember::OpenCL;
1007 SPIRVWordVec Ops(MinOperandCount);
1008
1009 Ops[NameIdx] = BM->getString(MT->getName().str())->getId();
1010 Ops[TypeIdx] = transDbgEntry(MT->getBaseType())->getId();
1011 Ops[SourceIdx] = getSource(MT)->getId();
1012 Ops[LineIdx] = MT->getLine();
1013 Ops[ColumnIdx] = 0; // This version of DIDerivedType has no column number
1014 Ops[ParentIdx] = transDbgEntry(MT->getScope())->getId();
1015 ConstantInt *Offset = getUInt(M, MT->getOffsetInBits());
1016 Ops[OffsetIdx] = SPIRVWriter->transValue(Offset, nullptr)->getId();
1017 ConstantInt *Size = getUInt(M, MT->getSizeInBits());
1018 Ops[SizeIdx] = SPIRVWriter->transValue(Size, nullptr)->getId();
1019 Ops[FlagsIdx] = adjustAccessFlags(MT->getScope(), transDebugFlags(MT));
1020 if (MT->isStaticMember()) {
1021 if (llvm::Constant *C = MT->getConstant()) {
1022 SPIRVValue *Val = SPIRVWriter->transValue(C, nullptr);
1023 assert(isConstantOpCode(Val->getOpCode()) &&
1024 "LLVM constant must be translated to SPIRV constant");
1025 Ops.push_back(Val->getId());
1026 }
1027 }
1028 if (isNonSemanticDebugInfo())
1029 transformToConstant(Ops, {LineIdx, ColumnIdx, FlagsIdx});
1030 return BM->addDebugInfo(SPIRVDebug::TypeMember, getVoidTy(), Ops);
1031 }
1032
1033 SPIRVEntry *
1034 LLVMToSPIRVDbgTran::transDbgMemberTypeNonSemantic(const DIDerivedType *MT) {
1035 using namespace SPIRVDebug::Operand::TypeMember::NonSemantic;
1036 SPIRVWordVec Ops(MinOperandCount);
1037
1038 Ops[NameIdx] = BM->getString(MT->getName().str())->getId();
1039 Ops[TypeIdx] = transDbgEntry(MT->getBaseType())->getId();
1040 Ops[SourceIdx] = getSource(MT)->getId();
1041 Ops[LineIdx] = MT->getLine();
1042 Ops[ColumnIdx] = 0; // This version of DIDerivedType has no column number
1043 ConstantInt *Offset = getUInt(M, MT->getOffsetInBits());
1044 Ops[OffsetIdx] = SPIRVWriter->transValue(Offset, nullptr)->getId();
1045 ConstantInt *Size = getUInt(M, MT->getSizeInBits());
1046 Ops[SizeIdx] = SPIRVWriter->transValue(Size, nullptr)->getId();
1047 Ops[FlagsIdx] = adjustAccessFlags(MT->getScope(), transDebugFlags(MT));
1048 transDbgEntry(MT->getScope())->getId();
1049 if (MT->isStaticMember()) {
1050 if (llvm::Constant *C = MT->getConstant()) {
1051 SPIRVValue *Val = SPIRVWriter->transValue(C, nullptr);
1052 assert(isConstantOpCode(Val->getOpCode()) &&
1053 "LLVM constant must be translated to SPIRV constant");
1054 Ops.push_back(Val->getId());
1055 }
1056 }
1057 transformToConstant(Ops, {LineIdx, ColumnIdx, FlagsIdx});
1058 return BM->addDebugInfo(SPIRVDebug::TypeMember, getVoidTy(), Ops);
1059 }
1060
1061 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgInheritance(const DIDerivedType *DT) {
1062 using namespace SPIRVDebug::Operand::TypeInheritance;
1063 unsigned ParentIdx, OffsetIdx, SizeIdx, FlagsIdx, OperandCount;
1064 if (isNonSemanticDebugInfo()) {
1065 ParentIdx = NonSemantic::ParentIdx;
1066 OffsetIdx = NonSemantic::OffsetIdx;
1067 SizeIdx = NonSemantic::SizeIdx;
1068 FlagsIdx = NonSemantic::FlagsIdx;
1069 OperandCount = NonSemantic::OperandCount;
1070 } else {
1071 ParentIdx = OpenCL::ParentIdx;
1072 OffsetIdx = OpenCL::OffsetIdx;
1073 SizeIdx = OpenCL::SizeIdx;
1074 FlagsIdx = OpenCL::FlagsIdx;
1075 OperandCount = OpenCL::OperandCount;
1076 }
1077 SPIRVWordVec Ops(OperandCount);
1078 Ops[ParentIdx] = transDbgEntry(DT->getBaseType())->getId();
1079 ConstantInt *OffsetInBits = getUInt(M, DT->getOffsetInBits());
1080 Ops[OffsetIdx] = SPIRVWriter->transValue(OffsetInBits, nullptr)->getId();
1081 ConstantInt *Size = getUInt(M, DT->getSizeInBits());
1082 Ops[SizeIdx] = SPIRVWriter->transValue(Size, nullptr)->getId();
1083 Ops[FlagsIdx] = transDebugFlags(DT);
1084 if (isNonSemanticDebugInfo()) {
1085 transformToConstant(Ops, {FlagsIdx});
1086 } else {
1087 Ops[OpenCL::ChildIdx] = transDbgEntry(DT->getScope())->getId();
1088 }
1089 return BM->addDebugInfo(SPIRVDebug::TypeInheritance, getVoidTy(), Ops);
1090 }
1091
1092 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgPtrToMember(const DIDerivedType *DT) {
1093 using namespace SPIRVDebug::Operand::TypePtrToMember;
1094 SPIRVWordVec Ops(OperandCount);
1095 Ops[MemberTypeIdx] = transDbgEntry(DT->getBaseType())->getId();
1096 Ops[ParentIdx] = transDbgEntry(DT->getClassType())->getId();
1097 return BM->addDebugInfo(SPIRVDebug::TypePtrToMember, getVoidTy(), Ops);
1098 }
1099
1100 // Templates
1101 SPIRVEntry *
1102 LLVMToSPIRVDbgTran::transDbgTemplateParams(DITemplateParameterArray TPA,
1103 const SPIRVEntry *Target) {
1104 using namespace SPIRVDebug::Operand::TypeTemplate;
1105 SPIRVWordVec Ops(MinOperandCount);
1106 Ops[TargetIdx] = Target->getId();
1107 for (DITemplateParameter *TP : TPA) {
1108 Ops.push_back(transDbgEntry(TP)->getId());
1109 }
1110 return BM->addDebugInfo(SPIRVDebug::TypeTemplate, getVoidTy(), Ops);
1111 }
1112
1113 SPIRVEntry *
1114 LLVMToSPIRVDbgTran::transDbgTemplateParameter(const DITemplateParameter *TP) {
1115 using namespace SPIRVDebug::Operand::TypeTemplateParameter;
1116 SPIRVWordVec Ops(OperandCount);
1117 Ops[NameIdx] = BM->getString(TP->getName().str())->getId();
1118 Ops[TypeIdx] = transDbgEntry(TP->getType())->getId();
1119 Ops[ValueIdx] = getDebugInfoNoneId();
1120 if (TP->getTag() == dwarf::DW_TAG_template_value_parameter) {
1121 const DITemplateValueParameter *TVP = cast<DITemplateValueParameter>(TP);
1122 if (auto *TVVal = TVP->getValue()) {
1123 Constant *C = cast<ConstantAsMetadata>(TVVal)->getValue();
1124 Ops[ValueIdx] = SPIRVWriter->transValue(C, nullptr)->getId();
1125 } else {
1126 SPIRVType *TyPtr = SPIRVWriter->transType(
1127 PointerType::get(Type::getInt8Ty(M->getContext()), 0));
1128 Ops[ValueIdx] = BM->addNullConstant(TyPtr)->getId();
1129 }
1130 }
1131 Ops[SourceIdx] = getDebugInfoNoneId();
1132 Ops[LineIdx] = 0; // This version of DITemplateParameter has no line number
1133 Ops[ColumnIdx] = 0; // This version of DITemplateParameter has no column info
1134 if (isNonSemanticDebugInfo())
1135 transformToConstant(Ops, {LineIdx, ColumnIdx});
1136 return BM->addDebugInfo(SPIRVDebug::TypeTemplateParameter, getVoidTy(), Ops);
1137 }
1138
1139 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgTemplateTemplateParameter(
1140 const DITemplateValueParameter *TVP) {
1141 using namespace SPIRVDebug::Operand::TypeTemplateTemplateParameter;
1142 SPIRVWordVec Ops(OperandCount);
1143 assert(isa<MDString>(TVP->getValue()));
1144 MDString *Val = cast<MDString>(TVP->getValue());
1145 Ops[NameIdx] = BM->getString(TVP->getName().str())->getId();
1146 Ops[TemplateNameIdx] = BM->getString(Val->getString().str())->getId();
1147 Ops[SourceIdx] = getDebugInfoNoneId();
1148 Ops[LineIdx] = 0; // This version of DITemplateValueParameter has no line info
1149 Ops[ColumnIdx] = 0; // This version of DITemplateValueParameter has no column
1150 if (isNonSemanticDebugInfo())
1151 transformToConstant(Ops, {LineIdx, ColumnIdx});
1152 return BM->addDebugInfo(SPIRVDebug::TypeTemplateTemplateParameter,
1153 getVoidTy(), Ops);
1154 }
1155
1156 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgTemplateParameterPack(
1157 const DITemplateValueParameter *TVP) {
1158 using namespace SPIRVDebug::Operand::TypeTemplateParameterPack;
1159 SPIRVWordVec Ops(MinOperandCount);
1160 assert(isa<MDNode>(TVP->getValue()));
1161 MDNode *Params = cast<MDNode>(TVP->getValue());
1162
1163 Ops[NameIdx] = BM->getString(TVP->getName().str())->getId();
1164 Ops[SourceIdx] = getDebugInfoNoneId();
1165 Ops[LineIdx] = 0; // This version of DITemplateValueParameter has no line info
1166 Ops[ColumnIdx] = 0; // This version of DITemplateValueParameter has no column
1167
1168 for (const MDOperand &Op : Params->operands()) {
1169 SPIRVEntry *P = transDbgEntry(cast<DINode>(Op.get()));
1170 Ops.push_back(P->getId());
1171 }
1172 if (isNonSemanticDebugInfo())
1173 transformToConstant(Ops, {LineIdx, ColumnIdx});
1174 return BM->addDebugInfo(SPIRVDebug::TypeTemplateParameterPack, getVoidTy(),
1175 Ops);
1176 }
1177
1178 // Global objects
1179
1180 SPIRVEntry *
1181 LLVMToSPIRVDbgTran::transDbgGlobalVariable(const DIGlobalVariable *GV) {
1182 using namespace SPIRVDebug::Operand::GlobalVariable;
1183 SPIRVWordVec Ops(MinOperandCount);
1184 Ops[NameIdx] = BM->getString(GV->getName().str())->getId();
1185 Ops[TypeIdx] = transDbgEntry(GV->getType())->getId();
1186 Ops[SourceIdx] = getSource(GV)->getId();
1187 Ops[LineIdx] = GV->getLine();
1188 Ops[ColumnIdx] = 0; // This version of DIGlobalVariable has no column number
1189
1190 // Parent scope
1191 DIScope *Context = GV->getScope();
1192 SPIRVEntry *Parent = SPIRVCUMap.begin()->second;
1193 // Global variable may be declared in scope of a namespace or imported module,
1194 // it may also be a static variable declared in scope of a function.
1195 if (Context && (isa<DINamespace>(Context) || isa<DISubprogram>(Context) ||
1196 isa<DIModule>(Context)))
1197 Parent = transDbgEntry(Context);
1198 Ops[ParentIdx] = Parent->getId();
1199
1200 Ops[LinkageNameIdx] = BM->getString(GV->getLinkageName().str())->getId();
1201 Ops[VariableIdx] = getGlobalVariable(GV)->getId();
1202 Ops[FlagsIdx] = transDebugFlags(GV);
1203
1204 // Check if GV is the definition of previously declared static member
1205 if (DIDerivedType *StaticMember = GV->getStaticDataMemberDeclaration())
1206 Ops.push_back(transDbgEntry(StaticMember)->getId());
1207
1208 if (isNonSemanticDebugInfo())
1209 transformToConstant(Ops, {LineIdx, ColumnIdx, FlagsIdx});
1210 return BM->addDebugInfo(SPIRVDebug::GlobalVariable, getVoidTy(), Ops);
1211 }
1212
1213 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgFunction(const DISubprogram *Func) {
1214 auto It = MDMap.find(Func);
1215 if (It != MDMap.end())
1216 return static_cast<SPIRVValue *>(It->second);
1217
1218 // As long as indexes of FunctionDeclaration operands match with Function
1219 using namespace SPIRVDebug::Operand::FunctionDeclaration;
1220 SPIRVWordVec Ops(OperandCount);
1221 Ops[NameIdx] = BM->getString(Func->getName().str())->getId();
1222 Ops[TypeIdx] = transDbgEntry(Func->getType())->getId();
1223 Ops[SourceIdx] = getSource(Func)->getId();
1224 Ops[LineIdx] = Func->getLine();
1225 Ops[ColumnIdx] = 0; // This version of DISubprogram has no column number
1226 auto Scope = Func->getScope();
1227 if (Scope && !isa<DIFile>(Scope)) {
1228 Ops[ParentIdx] = getScope(Scope)->getId();
1229 } else {
1230 if (auto *Unit = Func->getUnit())
1231 Ops[ParentIdx] = SPIRVCUMap[Unit]->getId();
1232 else
1233 // it might so happen, that DISubprogram is missing Unit parameter
1234 Ops[ParentIdx] = SPIRVCUMap.begin()->second->getId();
1235 }
1236 Ops[LinkageNameIdx] = BM->getString(Func->getLinkageName().str())->getId();
1237 Ops[FlagsIdx] = adjustAccessFlags(Scope, transDebugFlags(Func));
1238 if (isNonSemanticDebugInfo())
1239 transformToConstant(Ops, {LineIdx, ColumnIdx, FlagsIdx});
1240
1241 SPIRVEntry *DebugFunc = nullptr;
1242 SPIRVValue *FuncDef = nullptr;
1243 bool IsEntryPointKernel = false;
1244 if (!Func->isDefinition()) {
1245 DebugFunc =
1246 BM->addDebugInfo(SPIRVDebug::FunctionDeclaration, getVoidTy(), Ops);
1247 } else {
1248 // Here we add operands specific function definition
1249 using namespace SPIRVDebug::Operand::Function;
1250 Ops.resize(MinOperandCount);
1251 Ops[ScopeLineIdx] = Func->getScopeLine();
1252 if (isNonSemanticDebugInfo())
1253 transformToConstant(Ops, {ScopeLineIdx});
1254
1255 Ops[FunctionIdIdx] = getDebugInfoNoneId();
1256 for (const llvm::Function &F : M->functions()) {
1257 if (Func->describes(&F)) {
1258 // Function definition of spir_kernel can have no "spir_kernel" calling
1259 // convention because SPIRVRegularizeLLVMBase::addKernelEntryPoint pass
1260 // could have turned it to spir_func. The "true" entry point is a
1261 // wrapper kernel function, which can be found further in the module.
1262 if (FuncDef) {
1263 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
1264 IsEntryPointKernel = true;
1265 break;
1266 }
1267 continue;
1268 }
1269
1270 SPIRVValue *SPIRVFunc = SPIRVWriter->getTranslatedValue(&F);
1271 assert(SPIRVFunc && "All function must be already translated");
1272 Ops[FunctionIdIdx] = SPIRVFunc->getId();
1273 FuncDef = SPIRVFunc;
1274 if (!isNonSemanticDebugInfo())
1275 break;
1276
1277 // Most likely unreachable because of Regularise LLVM pass
1278 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
1279 IsEntryPointKernel = true;
1280 break;
1281 }
1282 }
1283 }
1284 // For NonSemantic.Shader.DebugInfo we store Function Id index as a
1285 // separate DebugFunctionDefinition instruction.
1286 if (isNonSemanticDebugInfo())
1287 Ops.pop_back();
1288
1289 if (DISubprogram *FuncDecl = Func->getDeclaration())
1290 Ops.push_back(transDbgEntry(FuncDecl)->getId());
1291 else {
1292 Ops.push_back(getDebugInfoNoneId());
1293 if (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200) {
1294 // Translate targetFuncName mostly for Fortran trampoline function if it
1295 // is the case
1296 StringRef TargetFunc = Func->getTargetFuncName();
1297 if (!TargetFunc.empty())
1298 Ops.push_back(BM->getString(TargetFunc.str())->getId());
1299 }
1300 }
1301
1302 DebugFunc = BM->addDebugInfo(SPIRVDebug::Function, getVoidTy(), Ops);
1303 MDMap.insert(std::make_pair(Func, DebugFunc));
1304 // Functions local variable might be not refered to anywhere else, except
1305 // here.
1306 // Just translate them.
1307 for (const DINode *Var : Func->getRetainedNodes())
1308 transDbgEntry(Var);
1309 }
1310 // If the function has template parameters the function *is* a template.
1311 if (DITemplateParameterArray TPA = Func->getTemplateParams()) {
1312 DebugFunc = transDbgTemplateParams(TPA, DebugFunc);
1313 }
1314
1315 if (isNonSemanticDebugInfo() &&
1316 (Func->isMainSubprogram() || IsEntryPointKernel)) [[maybe_unused]]
1317 SPIRVEntry *Inst = transDbgEntryPoint(Func, DebugFunc);
1318
1319 if (isNonSemanticDebugInfo() && FuncDef) [[maybe_unused]]
1320 SPIRVEntry *Inst = transDbgFuncDefinition(FuncDef, DebugFunc);
1321
1322 return DebugFunc;
1323 }
1324
1325 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgFuncDefinition(SPIRVValue *FuncDef,
1326 SPIRVEntry *DbgFunc) {
1327 using namespace SPIRVDebug::Operand::FunctionDefinition;
1328 SPIRVWordVec Ops(OperandCount);
1329 Ops[FunctionIdx] = DbgFunc->getId();
1330 Ops[DefinitionIdx] = FuncDef->getId();
1331 SPIRVFunction *F = static_cast<SPIRVFunction *>(FuncDef);
1332 SPIRVBasicBlock *BB = F->getNumBasicBlock() ? F->getBasicBlock(0) : nullptr;
1333 SPIRVId ExtSetId = BM->getExtInstSetId(BM->getDebugInfoEIS());
1334
1335 return BM->addExtInst(getVoidTy(), ExtSetId, SPIRVDebug::FunctionDefinition,
1336 Ops, BB, BB->getInst(0));
1337 }
1338
1339 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgEntryPoint(const DISubprogram *Func,
1340 SPIRVEntry *DbgFunc) {
1341 using namespace SPIRVDebug::Operand::EntryPoint;
1342 SPIRVWordVec Ops(OperandCount);
1343 Ops[EntryPointIdx] = DbgFunc->getId();
1344
1345 DICompileUnit *CU = Func->getUnit();
1346 if (!CU) {
1347 Ops[CompilationUnitIdx] = SPIRVCUMap.begin()->second->getId();
1348 SPIRVWord EmptyStrIdx = BM->getString("")->getId();
1349 Ops[CompilerSignatureIdx] = EmptyStrIdx;
1350 Ops[CommandLineArgsIdx] = EmptyStrIdx;
1351 return BM->addDebugInfo(SPIRVDebug::EntryPoint, getVoidTy(), Ops);
1352 }
1353
1354 StringRef Producer = CU->getProducer();
1355 StringRef Flags = CU->getFlags();
1356 SPIRVEntry *CUVal = SPIRVCUMap[CU] ? SPIRVCUMap[CU] : getDebugInfoNone();
1357
1358 Ops[CompilationUnitIdx] = CUVal->getId();
1359 Ops[CompilerSignatureIdx] = BM->getString(Producer.str())->getId();
1360 Ops[CommandLineArgsIdx] = BM->getString(Flags.str())->getId();
1361 return BM->addDebugInfo(SPIRVDebug::EntryPoint, getVoidTy(), Ops);
1362 }
1363
1364 // Location information
1365
1366 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgScope(const DIScope *S) {
1367 if (const DILexicalBlockFile *LBF = dyn_cast<DILexicalBlockFile>(S)) {
1368 using namespace SPIRVDebug::Operand::LexicalBlockDiscriminator;
1369 SPIRVWordVec Ops(OperandCount);
1370 Ops[SourceIdx] = getSource(S)->getId();
1371 Ops[DiscriminatorIdx] = LBF->getDiscriminator();
1372 Ops[ParentIdx] = getScope(S->getScope())->getId();
1373 if (isNonSemanticDebugInfo())
1374 transformToConstant(Ops, {DiscriminatorIdx});
1375 return BM->addDebugInfo(SPIRVDebug::LexicalBlockDiscriminator, getVoidTy(),
1376 Ops);
1377 }
1378 using namespace SPIRVDebug::Operand::LexicalBlock;
1379 SPIRVWordVec Ops(MinOperandCount);
1380 Ops[SourceIdx] = getSource(S)->getId();
1381 Ops[ParentIdx] = getScope(S->getScope())->getId();
1382 if (const DILexicalBlock *LB = dyn_cast<DILexicalBlock>(S)) {
1383 Ops[LineIdx] = LB->getLine();
1384 Ops[ColumnIdx] = LB->getColumn();
1385 } else if (const DINamespace *NS = dyn_cast<DINamespace>(S)) {
1386 Ops[LineIdx] = 0; // This version of DINamespace has no line number
1387 Ops[ColumnIdx] = 0; // This version of DINamespace has no column number
1388 Ops.push_back(BM->getString(NS->getName().str())->getId());
1389 if (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200) {
1390 SPIRVValue *ExpConst = BM->addConstant(
1391 SPIRVWriter->transType(Type::getInt1Ty(M->getContext())),
1392 NS->getExportSymbols() /*Is inlined namespace*/);
1393 Ops.push_back(ExpConst->getId());
1394 }
1395 }
1396 if (isNonSemanticDebugInfo())
1397 transformToConstant(Ops, {LineIdx, ColumnIdx});
1398 return BM->addDebugInfo(SPIRVDebug::LexicalBlock, getVoidTy(), Ops);
1399 }
1400
1401 // Generating DebugScope and DebugNoScope instructions. They can interleave with
1402 // core instructions.
1403 SPIRVEntry *LLVMToSPIRVDbgTran::transDebugLoc(const DebugLoc &Loc,
1404 SPIRVBasicBlock *BB,
1405 SPIRVInstruction *InsertBefore) {
1406 SPIRVId ExtSetId = BM->getExtInstSetId(BM->getDebugInfoEIS());
1407 if (!Loc.get())
1408 return BM->addExtInst(getVoidTy(), ExtSetId, SPIRVDebug::NoScope,
1409 std::vector<SPIRVWord>(), BB, InsertBefore);
1410
1411 using namespace SPIRVDebug::Operand::Scope;
1412 SPIRVWordVec Ops(MinOperandCount);
1413 Ops[ScopeIdx] = getScope(static_cast<DIScope *>(Loc.getScope()))->getId();
1414 if (DILocation *IA = Loc.getInlinedAt())
1415 Ops.push_back(transDbgEntry(IA)->getId());
1416 return BM->addExtInst(getVoidTy(), ExtSetId, SPIRVDebug::Scope, Ops, BB,
1417 InsertBefore);
1418 }
1419
1420 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgInlinedAt(const DILocation *Loc) {
1421 // There is a Column operand in NonSemantic.Shader.200 spec
1422 if (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200)
1423 return transDbgInlinedAtNonSemanticShader200(Loc);
1424 using namespace SPIRVDebug::Operand::InlinedAt::OpenCL;
1425 SPIRVWordVec Ops(MinOperandCount);
1426 Ops[LineIdx] = Loc->getLine();
1427 Ops[ScopeIdx] = getScope(Loc->getScope())->getId();
1428 if (DILocation *IA = Loc->getInlinedAt())
1429 Ops.push_back(transDbgEntry(IA)->getId());
1430 if (isNonSemanticDebugInfo())
1431 transformToConstant(Ops, {LineIdx});
1432 return BM->addDebugInfo(SPIRVDebug::InlinedAt, getVoidTy(), Ops);
1433 }
1434
1435 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgInlinedAtNonSemanticShader200(
1436 const DILocation *Loc) {
1437 using namespace SPIRVDebug::Operand::InlinedAt::NonSemantic;
1438 SPIRVWordVec Ops(MinOperandCount);
1439 Ops[LineIdx] = Loc->getLine();
1440 Ops[ColumnIdx] = Loc->getColumn();
1441 transformToConstant(Ops, {LineIdx, ColumnIdx});
1442 Ops[ScopeIdx] = getScope(Loc->getScope())->getId();
1443 if (DILocation *IA = Loc->getInlinedAt())
1444 Ops.push_back(transDbgEntry(IA)->getId());
1445 return BM->addDebugInfo(SPIRVDebug::InlinedAt, getVoidTy(), Ops);
1446 }
1447
1448 template <class T>
1449 SPIRVExtInst *LLVMToSPIRVDbgTran::getSource(const T *DIEntry) {
1450 const std::string FileName = getFullPath(DIEntry);
1451 auto It = FileMap.find(FileName);
1452 if (It != FileMap.end())
1453 return It->second;
1454
1455 using namespace SPIRVDebug::Operand::Source;
1456 SPIRVWordVec Ops(MinOperandCount);
1457 Ops[FileIdx] = BM->getString(FileName)->getId();
1458 DIFile *F = DIEntry ? DIEntry->getFile() : nullptr;
1459
1460 if (F && F->getRawChecksum()) {
1461 auto CheckSum = F->getChecksum().value();
1462
1463 if (!isNonSemanticDebugInfo())
1464 Ops.push_back(BM->getString("//__" + CheckSum.getKindAsString().str() +
1465 ":" + CheckSum.Value.str())
1466 ->getId());
1467 else if (BM->getDebugInfoEIS() ==
1468 SPIRVEIS_NonSemantic_Shader_DebugInfo_200) {
1469 const SPIRVDebug::FileChecksumKind ChecksumKind =
1470 SPIRV::DbgChecksumKindMap::map(CheckSum.Kind);
1471
1472 Ops.push_back(
1473 BM->addIntegerConstant(static_cast<SPIRVTypeInt *>(getInt32Ty()),
1474 ChecksumKind)
1475 ->getId());
1476 Ops.push_back(BM->getString(CheckSum.Value.str())->getId());
1477 }
1478 }
1479
1480 if (F && F->getRawSource() && isNonSemanticDebugInfo()) {
1481 std::string Str = F->getSource().value().str();
1482 constexpr size_t MaxNumWords =
1483 MaxWordCount - 2 /*Fixed WC for SPIRVString*/;
1484 constexpr size_t MaxStrSize = MaxNumWords * 4 - 1;
1485 const size_t NumWords = getSizeInWords(Str);
1486
1487 if (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200 &&
1488 Ops.size() == MinOperandCount) {
1489 Ops.push_back(getDebugInfoNoneId());
1490 Ops.push_back(getDebugInfoNoneId());
1491 }
1492 Ops.push_back(BM->getString(Str.substr(0, MaxStrSize))->getId());
1493 SPIRVExtInst *Source = static_cast<SPIRVExtInst *>(
1494 BM->addDebugInfo(SPIRVDebug::Source, getVoidTy(), Ops));
1495 FileMap[FileName] = Source;
1496 Str.erase(0, MaxStrSize);
1497
1498 // No need to generate source continued instructions
1499 if (NumWords < MaxNumWords)
1500 return Source;
1501
1502 const uint64_t NumOfContinuedInstructions =
1503 NumWords / MaxNumWords - 1 + (NumWords % MaxNumWords ? 1 : 0);
1504 for (uint64_t J = 0; J < NumOfContinuedInstructions; J++) {
1505 const SPIRVWord Op = BM->getString(Str.substr(0, MaxStrSize))->getId();
1506 BM->addDebugInfo(SPIRVDebug::SourceContinued, getVoidTy(), {Op});
1507 Str.erase(0, MaxStrSize);
1508 }
1509 return Source;
1510 }
1511
1512 SPIRVExtInst *Source = static_cast<SPIRVExtInst *>(
1513 BM->addDebugInfo(SPIRVDebug::Source, getVoidTy(), Ops));
1514 FileMap[FileName] = Source;
1515 return Source;
1516 }
1517
1518 void LLVMToSPIRVDbgTran::generateBuildIdentifierAndStoragePath(
1519 const DICompileUnit *DIEntry) {
1520 // get information from LLVM IR
1521 auto BuildIdentifier = DIEntry->getDWOId();
1522 const std::string BuildIdentifierString = std::to_string(BuildIdentifier);
1523 const std::string StoragePath = DIEntry->getSplitDebugFilename().str();
1524
1525 using namespace SPIRVDebug::Operand;
1526
1527 if (BuildIdentifierInsn || StoragePathInsn) {
1528 #ifndef NDEBUG
1529 assert(BuildIdentifierInsn && StoragePathInsn &&
1530 "BuildIdentifier and StoragePath instructions must both be created");
1531
1532 auto PreviousBuildIdentifierString =
1533 BM->get<SPIRVString>(
1534 BuildIdentifierInsn
1535 ->getArguments()[BuildIdentifier::IdentifierIdx])
1536 ->getStr();
1537 assert(PreviousBuildIdentifierString == BuildIdentifierString &&
1538 "New BuildIdentifier should match previous BuildIdentifier");
1539 auto PreviousStoragePath =
1540 BM->get<SPIRVString>(
1541 StoragePathInsn->getArguments()[StoragePath::PathIdx])
1542 ->getStr();
1543 assert(PreviousStoragePath == StoragePath &&
1544 "New StoragePath should match previous StoragePath");
1545 #endif
1546 return;
1547 }
1548
1549 // generate BuildIdentifier inst
1550 SPIRVWordVec BuildIdentifierOps(BuildIdentifier::OperandCount);
1551 BuildIdentifierOps[BuildIdentifier::IdentifierIdx] =
1552 BM->getString(BuildIdentifierString)->getId();
1553 BuildIdentifierOps[BuildIdentifier::FlagsIdx] =
1554 BM->getLiteralAsConstant(1)->getId(); // Placeholder value for now
1555 BuildIdentifierInsn = static_cast<SPIRVExtInst *>(BM->addDebugInfo(
1556 SPIRVDebug::BuildIdentifier, getVoidTy(), BuildIdentifierOps));
1557
1558 // generate StoragePath inst
1559 SPIRVWordVec StoragePathOps(StoragePath::OperandCount);
1560 StoragePathOps[StoragePath::PathIdx] = BM->getString(StoragePath)->getId();
1561 StoragePathInsn = static_cast<SPIRVExtInst *>(
1562 BM->addDebugInfo(SPIRVDebug::StoragePath, getVoidTy(), StoragePathOps));
1563 }
1564
1565 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgFileType(const DIFile *F) {
1566 return BM->getString(getFullPath(F));
1567 }
1568
1569 // Local variables
1570
1571 SPIRVEntry *
1572 LLVMToSPIRVDbgTran::transDbgLocalVariable(const DILocalVariable *Var) {
1573 using namespace SPIRVDebug::Operand::LocalVariable;
1574 SPIRVWordVec Ops(MinOperandCount);
1575
1576 Ops[NameIdx] = BM->getString(Var->getName().str())->getId();
1577 Ops[TypeIdx] = transDbgEntry(Var->getType())->getId();
1578 Ops[SourceIdx] = getSource(Var->getFile())->getId();
1579 Ops[LineIdx] = Var->getLine();
1580 Ops[ColumnIdx] = 0; // This version of DILocalVariable has no column number
1581 Ops[ParentIdx] = getScope(Var->getScope())->getId();
1582 Ops[FlagsIdx] = transDebugFlags(Var);
1583 if (SPIRVWord ArgNumber = Var->getArg())
1584 Ops.push_back(ArgNumber);
1585 if (isNonSemanticDebugInfo())
1586 transformToConstant(Ops, {LineIdx, ColumnIdx, FlagsIdx});
1587 return BM->addDebugInfo(SPIRVDebug::LocalVariable, getVoidTy(), Ops);
1588 }
1589
1590 // DWARF Operations and expressions
1591
1592 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgExpression(const DIExpression *Expr) {
1593 SPIRVWordVec Operations;
1594 for (unsigned I = 0, N = Expr->getNumElements(); I < N; ++I) {
1595 using namespace SPIRVDebug::Operand::Operation;
1596 auto DWARFOpCode = static_cast<dwarf::LocationAtom>(Expr->getElement(I));
1597
1598 SPIRVDebug::ExpressionOpCode OC =
1599 SPIRV::DbgExpressionOpCodeMap::map(DWARFOpCode);
1600 if (OpCountMap.find(OC) == OpCountMap.end())
1601 report_fatal_error(llvm::Twine("unknown opcode found in DIExpression"));
1602 if (OC > SPIRVDebug::Fragment &&
1603 !(BM->allowExtraDIExpressions() ||
1604 BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200))
1605 report_fatal_error(
1606 llvm::Twine("unsupported opcode found in DIExpression"));
1607
1608 unsigned OpCount = OpCountMap[OC];
1609 SPIRVWordVec Op(OpCount);
1610 Op[OpCodeIdx] = OC;
1611 if (isNonSemanticDebugInfo())
1612 transformToConstant(Op, {OpCodeIdx});
1613 for (unsigned J = 1; J < OpCount; ++J) {
1614 Op[J] = Expr->getElement(++I);
1615 if (isNonSemanticDebugInfo())
1616 transformToConstant(Op, {J});
1617 }
1618 auto *Operation = BM->addDebugInfo(SPIRVDebug::Operation, getVoidTy(), Op);
1619 Operations.push_back(Operation->getId());
1620 }
1621 return BM->addDebugInfo(SPIRVDebug::Expression, getVoidTy(), Operations);
1622 }
1623
1624 // Imported entries (C++ using directive)
1625
1626 SPIRVEntry *
1627 LLVMToSPIRVDbgTran::transDbgImportedEntry(const DIImportedEntity *IE) {
1628 using namespace SPIRVDebug::Operand::ImportedEntity;
1629 auto Tag = static_cast<dwarf::Tag>(IE->getTag());
1630 // FIXME: 'OpenCL/bugged' version is kept because it's hard to remove it
1631 // It's W/A for missing 2nd index in OpenCL's implementation
1632 const SPIRVWord OffsetIdx = static_cast<int>(isNonSemanticDebugInfo());
1633 SPIRVWordVec Ops(OpenCL::OperandCount - OffsetIdx);
1634 Ops[OpenCL::NameIdx] = BM->getString(IE->getName().str())->getId();
1635 Ops[OpenCL::TagIdx] = SPIRV::DbgImportedEntityMap::map(Tag);
1636 Ops[OpenCL::SourceIdx - OffsetIdx] = getSource(IE->getFile())->getId();
1637 Ops[OpenCL::EntityIdx - OffsetIdx] = transDbgEntry(IE->getEntity())->getId();
1638 Ops[OpenCL::LineIdx - OffsetIdx] = IE->getLine();
1639 // This version of DIImportedEntity has no column number
1640 Ops[OpenCL::ColumnIdx - OffsetIdx] = 0;
1641 Ops[OpenCL::ParentIdx - OffsetIdx] = getScope(IE->getScope())->getId();
1642 if (isNonSemanticDebugInfo())
1643 transformToConstant(Ops, {OpenCL::TagIdx, OpenCL::LineIdx - OffsetIdx,
1644 OpenCL::ColumnIdx - OffsetIdx});
1645 return BM->addDebugInfo(SPIRVDebug::ImportedEntity, getVoidTy(), Ops);
1646 }
1647
1648 SPIRVEntry *LLVMToSPIRVDbgTran::transDbgModule(const DIModule *Module) {
1649 using namespace SPIRVDebug::Operand::ModuleINTEL;
1650 SPIRVWordVec Ops(OperandCount);
1651 Ops[NameIdx] = BM->getString(Module->getName().str())->getId();
1652 Ops[SourceIdx] = getSource(Module->getFile())->getId();
1653 Ops[LineIdx] = Module->getLineNo();
1654 Ops[ParentIdx] = getScope(Module->getScope())->getId();
1655 Ops[ConfigMacrosIdx] =
1656 BM->getString(Module->getConfigurationMacros().str())->getId();
1657 Ops[IncludePathIdx] = BM->getString(Module->getIncludePath().str())->getId();
1658 Ops[ApiNotesIdx] = BM->getString(Module->getAPINotesFile().str())->getId();
1659 Ops[IsDeclIdx] = Module->getIsDecl();
1660 if (BM->getDebugInfoEIS() == SPIRVEIS_NonSemantic_Shader_DebugInfo_200) {
1661 // The difference in translation of NonSemantic Debug Info and
1662 // SPV_INTEL_debug_module extension is that extension allows Line and IsDecl
1663 // operands to be Literals, when the non-OpenCL Debug Info allows only IDs
1664 // to the constant values.
1665 transformToConstant(Ops, {LineIdx, IsDeclIdx});
1666 return BM->addDebugInfo(SPIRVDebug::Module, getVoidTy(), Ops);
1667 }
1668 BM->addExtension(ExtensionID::SPV_INTEL_debug_module);
1669 BM->addCapability(spv::CapabilityDebugInfoModuleINTEL);
1670 return BM->addDebugInfo(SPIRVDebug::ModuleINTEL, getVoidTy(), Ops);
1671 }