MLIR 23.0.0git
DebugTranslation.cpp
Go to the documentation of this file.
1//===- DebugTranslation.cpp - MLIR to LLVM Debug conversion ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "DebugTranslation.h"
11#include "llvm/ADT/SmallVectorExtras.h"
12#include "llvm/ADT/TypeSwitch.h"
13#include "llvm/IR/Metadata.h"
14#include "llvm/IR/Module.h"
15#include "llvm/Support/FileSystem.h"
16#include "llvm/Support/Path.h"
17
18using namespace mlir;
19using namespace mlir::LLVM;
20using namespace mlir::LLVM::detail;
21
22/// A utility walker that interrupts if the operation has valid debug
23/// information.
25 return isa<UnknownLoc>(op->getLoc()) ? WalkResult::advance()
27}
28
29DebugTranslation::DebugTranslation(Operation *module, llvm::Module &llvmModule)
30 : debugEmissionIsEnabled(false), llvmModule(llvmModule),
31 llvmCtx(llvmModule.getContext()) {
32 // If the module has no location information, there is nothing to do.
33 if (!module->walk(interruptIfValidLocation).wasInterrupted())
34 return;
35 debugEmissionIsEnabled = true;
36}
37
38static constexpr StringRef kDebugVersionKey = "Debug Info Version";
39static constexpr StringRef kCodeViewKey = "CodeView";
40
42 // TODO: The version information should be encoded on the LLVM module itself,
43 // not implicitly set here.
44
45 // Mark this module as having debug information.
46 if (!llvmModule.getModuleFlag(kDebugVersionKey))
47 llvmModule.addModuleFlag(llvm::Module::Warning, kDebugVersionKey,
48 llvm::DEBUG_METADATA_VERSION);
49
50 const llvm::Triple &targetTriple = llvmModule.getTargetTriple();
51 if (targetTriple.isKnownWindowsMSVCEnvironment()) {
52 // Dwarf debugging files will be generated by default, unless "CodeView"
53 // is set explicitly. Windows/MSVC should use CodeView instead.
54 if (!llvmModule.getModuleFlag(kCodeViewKey))
55 llvmModule.addModuleFlag(llvm::Module::Warning, kCodeViewKey, 1);
56 }
57}
58
59/// Translate the debug information for the given function.
60void DebugTranslation::translate(LLVMFuncOp func, llvm::Function &llvmFunc) {
61 if (!debugEmissionIsEnabled)
62 return;
63
64 // Look for a sub program attached to the function.
65 auto spLoc =
66 func.getLoc()->findInstanceOf<FusedLocWith<LLVM::DISubprogramAttr>>();
67 if (!spLoc)
68 return;
69 llvmFunc.setSubprogram(translate(spLoc.getMetadata()));
70}
71
72//===----------------------------------------------------------------------===//
73// Attributes
74//===----------------------------------------------------------------------===//
75
76llvm::DIType *DebugTranslation::translateImpl(DINullTypeAttr attr) {
77 // A DINullTypeAttr at the beginning of the subroutine types list models
78 // a void result type. If it is at the end, it models a variadic function.
79 // Translate the explicit DINullTypeAttr to a nullptr since LLVM IR metadata
80 // does not have an explicit void result type nor a variadic type
81 // representation.
82 return nullptr;
83}
84
85llvm::DIExpression *
86DebugTranslation::getExpressionAttrOrNull(DIExpressionAttr attr) {
87 if (!attr)
88 return nullptr;
89 return translateExpression(attr);
90}
91
92llvm::MDString *DebugTranslation::getMDStringOrNull(StringAttr stringAttr) {
93 if (!stringAttr || stringAttr.empty())
94 return nullptr;
95 return llvm::MDString::get(llvmCtx, stringAttr);
96}
97
98llvm::MDTuple *
99DebugTranslation::getMDTupleOrNull(ArrayRef<DINodeAttr> elements) {
100 if (elements.empty())
101 return nullptr;
102 SmallVector<llvm::Metadata *> llvmElements =
103 llvm::map_to_vector(elements, [&](DINodeAttr attr) -> llvm::Metadata * {
104 if (DIAnnotationAttr annAttr = dyn_cast<DIAnnotationAttr>(attr)) {
105 llvm::Metadata *ops[2] = {
106 llvm::MDString::get(llvmCtx, annAttr.getName()),
107 llvm::MDString::get(llvmCtx, annAttr.getValue())};
108 return llvm::MDNode::get(llvmCtx, ops);
109 }
110 return translate(attr);
111 });
112 return llvm::MDNode::get(llvmCtx, llvmElements);
113}
114
115llvm::DIBasicType *DebugTranslation::translateImpl(DIBasicTypeAttr attr) {
116 return llvm::DIBasicType::get(
117 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
118 attr.getSizeInBits(),
119 /*AlignInBits=*/0, attr.getEncoding(), llvm::DINode::FlagZero);
120}
121
122llvm::DICompileUnit *DebugTranslation::translateImpl(DICompileUnitAttr attr) {
123 llvm::DIBuilder builder(llvmModule);
124 llvm::DICompileUnit *cu = builder.createCompileUnit(
125 attr.getSourceLanguage(), translate(attr.getFile()),
126 attr.getProducer() ? attr.getProducer().getValue() : "",
127 attr.getIsOptimized(),
128 /*Flags=*/"", /*RV=*/0,
129 attr.getSplitDebugFilename() ? attr.getSplitDebugFilename().getValue()
130 : "",
131 static_cast<llvm::DICompileUnit::DebugEmissionKind>(
132 attr.getEmissionKind()),
133 0, true, attr.getIsDebugInfoForProfiling(),
134 static_cast<llvm::DICompileUnit::DebugNameTableKind>(
135 attr.getNameTableKind()));
136
137 llvm::SmallVector<llvm::Metadata *> importNodes;
138 for (DINodeAttr importNode : attr.getImportedEntities())
139 importNodes.push_back(translate(importNode));
140 if (!importNodes.empty())
141 cu->replaceImportedEntities(llvm::MDTuple::get(llvmCtx, importNodes));
142
143 return cu;
144}
145
146/// Returns a new `DINodeT` that is either distinct or not, depending on
147/// `isDistinct`.
148template <class DINodeT, class... Ts>
149static DINodeT *getDistinctOrUnique(bool isDistinct, Ts &&...args) {
150 if (isDistinct)
151 return DINodeT::getDistinct(std::forward<Ts>(args)...);
152 return DINodeT::get(std::forward<Ts>(args)...);
153}
154
155llvm::TempDICompositeType
156DebugTranslation::translateTemporaryImpl(DICompositeTypeAttr attr) {
157 return llvm::DICompositeType::getTemporary(
158 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()), nullptr,
159 attr.getLine(), nullptr, nullptr, attr.getSizeInBits(),
160 attr.getAlignInBits(),
161 /*OffsetInBits=*/0,
162 /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
163 /*Elements=*/nullptr, /*RuntimeLang=*/0, /*EnumKind=*/std::nullopt,
164 /*VTableHolder=*/nullptr);
165}
166
167llvm::TempDISubprogram
168DebugTranslation::translateTemporaryImpl(DISubprogramAttr attr) {
169 return llvm::DISubprogram::getTemporary(
170 llvmCtx, /*Scope=*/nullptr, /*Name=*/{}, /*LinkageName=*/{},
171 /*File=*/nullptr, attr.getLine(), /*Type=*/nullptr,
172 /*ScopeLine=*/0, /*ContainingType=*/nullptr, /*VirtualIndex=*/0,
173 /*ThisAdjustment=*/0, llvm::DINode::FlagZero,
174 static_cast<llvm::DISubprogram::DISPFlags>(attr.getSubprogramFlags()),
175 /*Unit=*/nullptr);
176}
177
178llvm::DICompositeType *
179DebugTranslation::translateImpl(DICompositeTypeAttr attr) {
180 // TODO: Use distinct attributes to model this, once they have landed.
181 // Depending on the tag, composite types must be distinct.
182 bool isDistinct = false;
183 switch (attr.getTag()) {
184 case llvm::dwarf::DW_TAG_class_type:
185 case llvm::dwarf::DW_TAG_enumeration_type:
186 case llvm::dwarf::DW_TAG_structure_type:
187 case llvm::dwarf::DW_TAG_union_type:
188 isDistinct = true;
189 }
190
192 isDistinct, llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
193 translate(attr.getFile()), attr.getLine(), translate(attr.getScope()),
194 translate(attr.getBaseType()), attr.getSizeInBits(),
195 attr.getAlignInBits(),
196 /*OffsetInBits=*/0,
197 /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
198 getMDTupleOrNull(attr.getElements()),
199 /*RuntimeLang=*/0, /*EnumKind*/ std::nullopt, /*VTableHolder=*/nullptr,
200 /*TemplateParams=*/nullptr, /*Identifier=*/nullptr,
201 /*Discriminator=*/nullptr,
202 getExpressionAttrOrNull(attr.getDataLocation()),
203 getExpressionAttrOrNull(attr.getAssociated()),
204 getExpressionAttrOrNull(attr.getAllocated()),
205 getExpressionAttrOrNull(attr.getRank()));
206}
207
208llvm::DIDerivedType *DebugTranslation::translateImpl(DIDerivedTypeAttr attr) {
209 return llvm::DIDerivedType::get(
210 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
211 translate(attr.getFile()), attr.getLine(), translate(attr.getScope()),
212 translate(attr.getBaseType()), attr.getSizeInBits(),
213 attr.getAlignInBits(), attr.getOffsetInBits(),
214 attr.getDwarfAddressSpace(), /*PtrAuthData=*/std::nullopt,
215 /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
216 translate(attr.getExtraData()));
217}
218
219llvm::DIStringType *DebugTranslation::translateImpl(DIStringTypeAttr attr) {
220 return llvm::DIStringType::get(
221 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
222 translate(attr.getStringLength()),
223 getExpressionAttrOrNull(attr.getStringLengthExp()),
224 getExpressionAttrOrNull(attr.getStringLocationExp()),
225 attr.getSizeInBits(), attr.getAlignInBits(), attr.getEncoding());
226}
227
228llvm::DIFile *DebugTranslation::translateImpl(DIFileAttr attr) {
229 return llvm::DIFile::get(llvmCtx, getMDStringOrNull(attr.getName()),
230 getMDStringOrNull(attr.getDirectory()));
231}
232
233llvm::DILabel *DebugTranslation::translateImpl(DILabelAttr attr) {
234 return llvm::DILabel::get(llvmCtx, translate(attr.getScope()),
235 getMDStringOrNull(attr.getName()),
236 translate(attr.getFile()), attr.getLine(),
237 /*Column=*/0, /*IsArtificial=*/false,
238 /*CoroSuspendIdx=*/std::nullopt);
239}
240
241llvm::DILexicalBlock *DebugTranslation::translateImpl(DILexicalBlockAttr attr) {
242 return llvm::DILexicalBlock::getDistinct(llvmCtx, translate(attr.getScope()),
243 translate(attr.getFile()),
244 attr.getLine(), attr.getColumn());
245}
246
247llvm::DILexicalBlockFile *
248DebugTranslation::translateImpl(DILexicalBlockFileAttr attr) {
249 return llvm::DILexicalBlockFile::getDistinct(
250 llvmCtx, translate(attr.getScope()), translate(attr.getFile()),
251 attr.getDiscriminator());
252}
253
254llvm::DILocalScope *DebugTranslation::translateImpl(DILocalScopeAttr attr) {
255 return cast<llvm::DILocalScope>(translate(DINodeAttr(attr)));
256}
257
258llvm::DIVariable *DebugTranslation::translateImpl(DIVariableAttr attr) {
259 return cast<llvm::DIVariable>(translate(DINodeAttr(attr)));
260}
261
262llvm::DILocalVariable *
263DebugTranslation::translateImpl(DILocalVariableAttr attr) {
264 return llvm::DILocalVariable::get(
265 llvmCtx, translate(attr.getScope()), getMDStringOrNull(attr.getName()),
266 translate(attr.getFile()), attr.getLine(), translate(attr.getType()),
267 attr.getArg(), static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
268 attr.getAlignInBits(),
269 /*Annotations=*/nullptr);
270}
271
272llvm::DIGlobalVariable *
273DebugTranslation::translateImpl(DIGlobalVariableAttr attr) {
274 return llvm::DIGlobalVariable::getDistinct(
275 llvmCtx, translate(attr.getScope()), getMDStringOrNull(attr.getName()),
276 getMDStringOrNull(attr.getLinkageName()), translate(attr.getFile()),
277 attr.getLine(), translate(attr.getType()), attr.getIsLocalToUnit(),
278 attr.getIsDefined(), nullptr, nullptr, attr.getAlignInBits(), nullptr);
279}
280
281llvm::DINode *
282DebugTranslation::translateRecursive(DIRecursiveTypeAttrInterface attr) {
283 DistinctAttr recursiveId = attr.getRecId();
284 if (auto *iter = recursiveNodeMap.find(recursiveId);
285 iter != recursiveNodeMap.end()) {
286 return iter->second;
287 }
288 assert(!attr.getIsRecSelf() && "unbound DI recursive self reference");
289
290 auto setRecursivePlaceholder = [&](llvm::DINode *placeholder) {
291 recursiveNodeMap.try_emplace(recursiveId, placeholder);
292 };
293
294 llvm::DINode *result =
296 .Case([&](DICompositeTypeAttr attr) {
297 auto temporary = translateTemporaryImpl(attr);
298 setRecursivePlaceholder(temporary.get());
299 // Must call `translateImpl` directly instead of `translate` to
300 // avoid handling the recursive interface again.
301 auto *concrete = translateImpl(attr);
302 temporary->replaceAllUsesWith(concrete);
303 return concrete;
304 })
305 .Case([&](DISubprogramAttr attr) {
306 auto temporary = translateTemporaryImpl(attr);
307 setRecursivePlaceholder(temporary.get());
308 // Must call `translateImpl` directly instead of `translate` to
309 // avoid handling the recursive interface again.
310 auto *concrete = translateImpl(attr);
311 temporary->replaceAllUsesWith(concrete);
312 return concrete;
313 });
314
315 assert(recursiveNodeMap.back().first == recursiveId &&
316 "internal inconsistency: unexpected recursive translation stack");
317 recursiveNodeMap.pop_back();
318
319 return result;
320}
321
322llvm::DIScope *DebugTranslation::translateImpl(DIScopeAttr attr) {
323 return cast<llvm::DIScope>(translate(DINodeAttr(attr)));
324}
325
326llvm::DISubprogram *DebugTranslation::translateImpl(DISubprogramAttr attr) {
327 if (auto iter = distinctAttrToNode.find(attr.getId());
328 iter != distinctAttrToNode.end())
329 return cast<llvm::DISubprogram>(iter->second);
330
331 llvm::DIScope *scope = translate(attr.getScope());
332 llvm::DIFile *file = translate(attr.getFile());
333 llvm::DIType *type = translate(attr.getType());
334 llvm::DICompileUnit *compileUnit = translate(attr.getCompileUnit());
335
336 // Check again after recursive calls in case this distinct node recurses back
337 // to itself.
338 if (auto iter = distinctAttrToNode.find(attr.getId());
339 iter != distinctAttrToNode.end())
340 return cast<llvm::DISubprogram>(iter->second);
341
342 bool isDefinition = static_cast<bool>(attr.getSubprogramFlags() &
343 LLVM::DISubprogramFlags::Definition);
344
345 llvm::DISubprogram *node = getDistinctOrUnique<llvm::DISubprogram>(
346 isDefinition, llvmCtx, scope, getMDStringOrNull(attr.getName()),
347 getMDStringOrNull(attr.getLinkageName()), file, attr.getLine(), type,
348 attr.getScopeLine(),
349 /*ContainingType=*/nullptr, /*VirtualIndex=*/0,
350 /*ThisAdjustment=*/0, llvm::DINode::FlagZero,
351 static_cast<llvm::DISubprogram::DISPFlags>(attr.getSubprogramFlags()),
352 compileUnit, /*TemplateParams=*/nullptr, /*Declaration=*/nullptr,
353 getMDTupleOrNull(attr.getRetainedNodes()), nullptr,
354 getMDTupleOrNull(attr.getAnnotations()));
355 if (attr.getId())
356 distinctAttrToNode.try_emplace(attr.getId(), node);
357 return node;
358}
359
360llvm::DIModule *DebugTranslation::translateImpl(DIModuleAttr attr) {
361 return llvm::DIModule::get(
362 llvmCtx, translate(attr.getFile()), translate(attr.getScope()),
363 getMDStringOrNull(attr.getName()),
364 getMDStringOrNull(attr.getConfigMacros()),
365 getMDStringOrNull(attr.getIncludePath()),
366 getMDStringOrNull(attr.getApinotes()), attr.getLine(), attr.getIsDecl());
367}
368
369llvm::DINamespace *DebugTranslation::translateImpl(DINamespaceAttr attr) {
370 return llvm::DINamespace::get(llvmCtx, translate(attr.getScope()),
371 getMDStringOrNull(attr.getName()),
372 attr.getExportSymbols());
373}
374
375llvm::DIImportedEntity *
376DebugTranslation::translateImpl(DIImportedEntityAttr attr) {
377 return llvm::DIImportedEntity::get(
378 llvmCtx, attr.getTag(), translate(attr.getScope()),
379 translate(attr.getEntity()), translate(attr.getFile()), attr.getLine(),
380 getMDStringOrNull(attr.getName()), getMDTupleOrNull(attr.getElements()));
381}
382
383llvm::DISubrange *DebugTranslation::translateImpl(DISubrangeAttr attr) {
384 auto getMetadataOrNull = [&](Attribute attr) -> llvm::Metadata * {
385 if (!attr)
386 return nullptr;
387
388 llvm::Metadata *metadata =
389 llvm::TypeSwitch<Attribute, llvm::Metadata *>(attr)
390 .Case([&](IntegerAttr intAttr) {
391 return llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
392 llvm::Type::getInt64Ty(llvmCtx), intAttr.getInt()));
393 })
394 .Case([&](LLVM::DIExpressionAttr expr) {
395 return translateExpression(expr);
396 })
397 .Case([&](LLVM::DILocalVariableAttr local) {
398 return translate(local);
399 })
400 .Case<>([&](LLVM::DIGlobalVariableAttr global) {
401 return translate(global);
402 })
403 .Default(nullptr);
404 return metadata;
405 };
406 return llvm::DISubrange::get(llvmCtx, getMetadataOrNull(attr.getCount()),
407 getMetadataOrNull(attr.getLowerBound()),
408 getMetadataOrNull(attr.getUpperBound()),
409 getMetadataOrNull(attr.getStride()));
410}
411
412llvm::DICommonBlock *DebugTranslation::translateImpl(DICommonBlockAttr attr) {
413 return llvm::DICommonBlock::get(llvmCtx, translate(attr.getScope()),
414 translate(attr.getDecl()),
415 getMDStringOrNull(attr.getName()),
416 translate(attr.getFile()), attr.getLine());
417}
418
419llvm::DIGenericSubrange *
420DebugTranslation::translateImpl(DIGenericSubrangeAttr attr) {
421 auto getMetadataOrNull = [&](Attribute attr) -> llvm::Metadata * {
422 if (!attr)
423 return nullptr;
424
425 llvm::Metadata *metadata =
426 llvm::TypeSwitch<Attribute, llvm::Metadata *>(attr)
427 .Case([&](LLVM::DIExpressionAttr expr) {
428 return translateExpression(expr);
429 })
430 .Case([&](LLVM::DILocalVariableAttr local) {
431 return translate(local);
432 })
433 .Case([&](LLVM::DIGlobalVariableAttr global) {
434 return translate(global);
435 })
436 .Default(nullptr);
437 return metadata;
438 };
439 return llvm::DIGenericSubrange::get(llvmCtx,
440 getMetadataOrNull(attr.getCount()),
441 getMetadataOrNull(attr.getLowerBound()),
442 getMetadataOrNull(attr.getUpperBound()),
443 getMetadataOrNull(attr.getStride()));
444}
445
446llvm::DISubroutineType *
447DebugTranslation::translateImpl(DISubroutineTypeAttr attr) {
448 // Concatenate the result and argument types into a single array.
449 SmallVector<llvm::Metadata *> types;
450 for (DITypeAttr type : attr.getTypes())
451 types.push_back(translate(type));
452 return llvm::DISubroutineType::get(
453 llvmCtx, llvm::DINode::FlagZero, attr.getCallingConvention(),
454 llvm::DITypeArray(llvm::MDNode::get(llvmCtx, types)));
455}
456
457llvm::DIType *DebugTranslation::translateImpl(DITypeAttr attr) {
458 return cast<llvm::DIType>(translate(DINodeAttr(attr)));
459}
460
462 if (!attr)
463 return nullptr;
464 // Check for a cached instance.
465 if (llvm::DINode *node = attrToNode.lookup(attr))
466 return node;
467
468 llvm::DINode *node = nullptr;
469 // Recursive types go through a dedicated handler. All other types are
470 // dispatched directly to their specific handlers.
471 if (auto recTypeAttr = dyn_cast<DIRecursiveTypeAttrInterface>(attr))
472 if (recTypeAttr.getRecId())
473 node = translateRecursive(recTypeAttr);
474
475 if (!node)
477 .Case<DIBasicTypeAttr, DICommonBlockAttr, DICompileUnitAttr,
478 DICompositeTypeAttr, DIDerivedTypeAttr, DIFileAttr,
479 DIGenericSubrangeAttr, DIGlobalVariableAttr,
480 DIImportedEntityAttr, DILabelAttr, DILexicalBlockAttr,
481 DILexicalBlockFileAttr, DILocalVariableAttr, DIModuleAttr,
482 DINamespaceAttr, DINullTypeAttr, DIStringTypeAttr,
483 DISubprogramAttr, DISubrangeAttr, DISubroutineTypeAttr>(
484 [&](auto attr) { return translateImpl(attr); });
485
486 if (node && !node->isTemporary())
487 attrToNode.insert({attr, node});
488 return node;
489}
490
491//===----------------------------------------------------------------------===//
492// Locations
493//===----------------------------------------------------------------------===//
494
495/// Translate the given location to an llvm debug location.
497 llvm::DILocalScope *scope) {
498 if (!debugEmissionIsEnabled)
499 return nullptr;
500 return translateLoc(loc, scope, /*inlinedAt=*/nullptr);
501}
502
503llvm::DIExpression *
504DebugTranslation::translateExpression(LLVM::DIExpressionAttr attr) {
506 if (attr) {
507 // Append operations their operands to the list.
508 for (const DIExpressionElemAttr &op : attr.getOperations()) {
509 ops.push_back(op.getOpcode());
510 append_range(ops, op.getArguments());
511 }
512 }
513 return llvm::DIExpression::get(llvmCtx, ops);
514}
515
516llvm::DIGlobalVariableExpression *
518 LLVM::DIGlobalVariableExpressionAttr attr) {
519 return llvm::DIGlobalVariableExpression::get(
520 llvmCtx, translate(attr.getVar()), translateExpression(attr.getExpr()));
521}
522
523/// Translate the given location to an llvm DebugLoc.
524llvm::DILocation *DebugTranslation::translateLoc(Location loc,
525 llvm::DILocalScope *scope,
526 llvm::DILocation *inlinedAt) {
527 // LLVM doesn't have a representation for unknown.
528 if (isa<UnknownLoc>(loc))
529 return nullptr;
530
531 // Check for a cached instance.
532 auto existingIt = locationToLoc.find(std::make_tuple(loc, scope, inlinedAt));
533 if (existingIt != locationToLoc.end())
534 return existingIt->second;
535
536 llvm::DILocation *llvmLoc = nullptr;
537 if (auto callLoc = dyn_cast<CallSiteLoc>(loc)) {
538 // For callsites, the caller is fed as the inlinedAt for the callee.
539 auto *callerLoc = translateLoc(callLoc.getCaller(), scope, inlinedAt);
540 // If the caller scope is not translatable, the overall callsite cannot be
541 // represented in LLVM (the callee scope may not match the parent function).
542 if (!callerLoc) {
543 // If there is an inlinedAt scope (an outer caller), skip to that
544 // directly. Otherwise, cannot translate.
545 if (!inlinedAt)
546 return nullptr;
547 callerLoc = inlinedAt;
548 }
549 llvmLoc = translateLoc(callLoc.getCallee(), nullptr, callerLoc);
550 // Fallback: Ignore callee if it has no debug scope.
551 if (!llvmLoc)
552 llvmLoc = callerLoc;
553
554 } else if (auto fileLoc = dyn_cast<FileLineColLoc>(loc)) {
555 // A scope of a DILocation cannot be null.
556 if (!scope)
557 return nullptr;
558 llvmLoc =
559 llvm::DILocation::get(llvmCtx, fileLoc.getLine(), fileLoc.getColumn(),
560 scope, const_cast<llvm::DILocation *>(inlinedAt));
561
562 } else if (auto fusedLoc = dyn_cast<FusedLoc>(loc)) {
563 ArrayRef<Location> locations = fusedLoc.getLocations();
564
565 // Check for a scope encoded with the location.
566 if (auto scopedAttr =
567 dyn_cast_or_null<LLVM::DILocalScopeAttr>(fusedLoc.getMetadata()))
568 scope = translate(scopedAttr);
569
570 // For fused locations, merge each of the nodes.
571 llvmLoc = translateLoc(locations.front(), scope, inlinedAt);
572 for (Location locIt : locations.drop_front()) {
573 llvmLoc = llvm::DILocation::getMergedLocation(
574 llvmLoc, translateLoc(locIt, scope, inlinedAt));
575 }
576
577 } else if (auto nameLoc = dyn_cast<NameLoc>(loc)) {
578 llvmLoc = translateLoc(nameLoc.getChildLoc(), scope, inlinedAt);
579
580 } else if (auto opaqueLoc = dyn_cast<OpaqueLoc>(loc)) {
581 llvmLoc = translateLoc(opaqueLoc.getFallbackLocation(), scope, inlinedAt);
582 } else {
583 llvm_unreachable("unknown location kind");
584 }
585
586 locationToLoc.try_emplace(std::make_tuple(loc, scope, inlinedAt), llvmLoc);
587 return llvmLoc;
588}
589
590/// Create an llvm debug file for the given file path.
591llvm::DIFile *DebugTranslation::translateFile(StringRef fileName) {
592 auto *&file = fileMap[fileName];
593 if (file)
594 return file;
595
596 // Make sure the current working directory is up-to-date.
597 if (currentWorkingDir.empty())
598 llvm::sys::fs::current_path(currentWorkingDir);
599
600 StringRef directory = currentWorkingDir;
601 SmallString<128> dirBuf;
602 SmallString<128> fileBuf;
603 if (llvm::sys::path::is_absolute(fileName)) {
604 // Strip the common prefix (if it is more than just "/") from current
605 // directory and FileName for a more space-efficient encoding.
606 auto fileIt = llvm::sys::path::begin(fileName);
607 auto fileE = llvm::sys::path::end(fileName);
608 auto curDirIt = llvm::sys::path::begin(directory);
609 auto curDirE = llvm::sys::path::end(directory);
610 for (; curDirIt != curDirE && *curDirIt == *fileIt; ++curDirIt, ++fileIt)
611 llvm::sys::path::append(dirBuf, *curDirIt);
612 if (std::distance(llvm::sys::path::begin(directory), curDirIt) == 1) {
613 // Don't strip the common prefix if it is only the root "/" since that
614 // would make LLVM diagnostic locations confusing.
615 directory = StringRef();
616 } else {
617 for (; fileIt != fileE; ++fileIt)
618 llvm::sys::path::append(fileBuf, *fileIt);
619 directory = dirBuf;
620 fileName = fileBuf;
621 }
622 }
623 return (file = llvm::DIFile::get(llvmCtx, fileName, directory));
624}
static constexpr StringRef kDebugVersionKey
static WalkResult interruptIfValidLocation(Operation *op)
A utility walker that interrupts if the operation has valid debug information.
static constexpr StringRef kCodeViewKey
static DINodeT * getDistinctOrUnique(bool isDistinct, Ts &&...args)
Returns a new DINodeT that is either distinct or not, depending on isDistinct.
b getContext())
false
Parses a map_entries map type from a string format back into its numeric value.
This class represents a fused location whose metadata is known to be an instance of the given type.
Definition Location.h:149
This class represents the base attribute for all debug info attributes.
Definition LLVMAttrs.h:29
void translate(LLVMFuncOp func, llvm::Function &llvmFunc)
Translate the debug information for the given function.
llvm::DIExpression * translateExpression(LLVM::DIExpressionAttr attr)
Translates the given DWARF expression metadata to to LLVM.
void addModuleFlagsIfNotPresent()
Adds the necessary module flags to the module, if not yet present.
DebugTranslation(Operation *module, llvm::Module &llvmModule)
llvm::DILocation * translateLoc(Location loc, llvm::DILocalScope *scope)
Translate the given location to an llvm debug location.
llvm::DIGlobalVariableExpression * translateGlobalVariableExpression(LLVM::DIGlobalVariableExpressionAttr attr)
Translates the given DWARF global variable expression to LLVM.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:241
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:823
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
Include the generated interface declarations.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:139