11 #include "llvm/ADT/TypeSwitch.h"
12 #include "llvm/IR/Metadata.h"
13 #include "llvm/IR/Module.h"
14 #include "llvm/Support/FileSystem.h"
15 #include "llvm/Support/Path.h"
29 : debugEmissionIsEnabled(false), llvmModule(llvmModule),
34 debugEmissionIsEnabled =
true;
40 StringRef debugVersionKey =
"Debug Info Version";
41 if (!llvmModule.getModuleFlag(debugVersionKey))
42 llvmModule.addModuleFlag(llvm::Module::Warning, debugVersionKey,
43 llvm::DEBUG_METADATA_VERSION);
46 LLVM::LLVMDialect::getTargetTripleAttrName())) {
48 llvm::Triple(cast<StringAttr>(targetTripleAttr).getValue());
49 if (targetTriple.isKnownWindowsMSVCEnvironment()) {
52 llvmModule.addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
62 if (!debugEmissionIsEnabled)
70 llvmFunc.setSubprogram(
translate(spLoc.getMetadata()));
77 llvm::DIType *DebugTranslation::translateImpl(DINullTypeAttr attr) {
86 llvm::MDString *DebugTranslation::getMDStringOrNull(StringAttr stringAttr) {
87 if (!stringAttr || stringAttr.empty())
92 llvm::DIBasicType *DebugTranslation::translateImpl(DIBasicTypeAttr attr) {
94 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
96 0, attr.getEncoding(), llvm::DINode::FlagZero);
99 llvm::DICompileUnit *DebugTranslation::translateImpl(DICompileUnitAttr attr) {
100 llvm::DIBuilder builder(llvmModule);
101 return builder.createCompileUnit(
102 attr.getSourceLanguage(),
translate(attr.getFile()),
103 attr.getProducer() ? attr.getProducer().getValue() :
"",
104 attr.getIsOptimized(),
106 static_cast<llvm::DICompileUnit::DebugEmissionKind
>(
107 attr.getEmissionKind()),
109 static_cast<llvm::DICompileUnit::DebugNameTableKind
>(
110 attr.getNameTableKind()));
115 template <
class DINodeT,
class... Ts>
118 return DINodeT::getDistinct(std::forward<Ts>(args)...);
122 llvm::TempDICompositeType
123 DebugTranslation::translateTemporaryImpl(DICompositeTypeAttr attr) {
124 return llvm::DICompositeType::getTemporary(
125 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
nullptr,
126 attr.getLine(),
nullptr,
nullptr, attr.getSizeInBits(),
127 attr.getAlignInBits(),
129 static_cast<llvm::DINode::DIFlags
>(attr.getFlags()),
134 llvm::DICompositeType *
135 DebugTranslation::translateImpl(DICompositeTypeAttr attr) {
138 bool isDistinct =
false;
139 switch (attr.getTag()) {
140 case llvm::dwarf::DW_TAG_class_type:
141 case llvm::dwarf::DW_TAG_enumeration_type:
142 case llvm::dwarf::DW_TAG_structure_type:
143 case llvm::dwarf::DW_TAG_union_type:
151 return getDistinctOrUnique<llvm::DICompositeType>(
152 isDistinct, llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
154 translate(attr.getBaseType()), attr.getSizeInBits(),
155 attr.getAlignInBits(),
157 static_cast<llvm::DINode::DIFlags
>(attr.getFlags()),
162 llvm::DIDerivedType *DebugTranslation::translateImpl(DIDerivedTypeAttr attr) {
164 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
166 nullptr,
translate(attr.getBaseType()), attr.getSizeInBits(),
167 attr.getAlignInBits(), attr.getOffsetInBits(),
168 std::nullopt, std::nullopt,
169 llvm::DINode::FlagZero,
translate(attr.getExtraData()));
172 llvm::DIFile *DebugTranslation::translateImpl(DIFileAttr attr) {
174 getMDStringOrNull(attr.getDirectory()));
177 llvm::DILabel *DebugTranslation::translateImpl(DILabelAttr attr) {
179 getMDStringOrNull(attr.getName()),
180 translate(attr.getFile()), attr.getLine());
183 llvm::DILexicalBlock *DebugTranslation::translateImpl(DILexicalBlockAttr attr) {
184 return llvm::DILexicalBlock::getDistinct(llvmCtx,
translate(attr.getScope()),
186 attr.getLine(), attr.getColumn());
189 llvm::DILexicalBlockFile *
190 DebugTranslation::translateImpl(DILexicalBlockFileAttr attr) {
191 return llvm::DILexicalBlockFile::getDistinct(
193 attr.getDiscriminator());
196 llvm::DILocalScope *DebugTranslation::translateImpl(
DILocalScopeAttr attr) {
200 llvm::DILocalVariable *
201 DebugTranslation::translateImpl(DILocalVariableAttr attr) {
203 llvmCtx,
translate(attr.getScope()), getMDStringOrNull(attr.getName()),
206 llvm::DINode::FlagZero, attr.getAlignInBits(),
210 llvm::DIGlobalVariable *
211 DebugTranslation::translateImpl(DIGlobalVariableAttr attr) {
212 return llvm::DIGlobalVariable::getDistinct(
213 llvmCtx,
translate(attr.getScope()), getMDStringOrNull(attr.getName()),
214 getMDStringOrNull(attr.getLinkageName()),
translate(attr.getFile()),
215 attr.getLine(),
translate(attr.getType()), attr.getIsLocalToUnit(),
216 attr.getIsDefined(),
nullptr,
nullptr, attr.getAlignInBits(),
nullptr);
220 DebugTranslation::translateRecursive(DIRecursiveTypeAttrInterface attr) {
222 if (
auto *iter = recursiveTypeMap.find(recursiveId);
223 iter != recursiveTypeMap.end()) {
226 assert(!attr.isRecSelf() &&
"unbound DI recursive self type");
229 auto setRecursivePlaceholder = [&](llvm::DIType *placeholder) {
230 recursiveTypeMap.try_emplace(recursiveId, placeholder);
233 llvm::DIType *result =
235 .Case<DICompositeTypeAttr>([&](
auto attr) {
236 auto temporary = translateTemporaryImpl(attr);
237 setRecursivePlaceholder(temporary.get());
240 auto *concrete = translateImpl(attr);
241 temporary->replaceAllUsesWith(concrete);
245 assert(recursiveTypeMap.back().first == recursiveId &&
246 "internal inconsistency: unexpected recursive translation stack");
247 recursiveTypeMap.pop_back();
252 llvm::DIScope *DebugTranslation::translateImpl(
DIScopeAttr attr) {
256 llvm::DISubprogram *DebugTranslation::translateImpl(DISubprogramAttr attr) {
257 if (
auto iter = distinctAttrToNode.find(attr.getId());
258 iter != distinctAttrToNode.end())
259 return cast<llvm::DISubprogram>(iter->second);
261 llvm::DIScope *scope =
translate(attr.getScope());
262 llvm::DIFile *file =
translate(attr.getFile());
263 llvm::DIType *type =
translate(attr.getType());
264 llvm::DICompileUnit *compileUnit =
translate(attr.getCompileUnit());
268 if (
auto iter = distinctAttrToNode.find(attr.getId());
269 iter != distinctAttrToNode.end())
270 return cast<llvm::DISubprogram>(iter->second);
272 bool isDefinition =
static_cast<bool>(attr.getSubprogramFlags() &
273 LLVM::DISubprogramFlags::Definition);
274 llvm::DISubprogram *node = getDistinctOrUnique<llvm::DISubprogram>(
275 isDefinition, llvmCtx, scope, getMDStringOrNull(attr.getName()),
276 getMDStringOrNull(attr.getLinkageName()), file, attr.getLine(), type,
279 0, llvm::DINode::FlagZero,
280 static_cast<llvm::DISubprogram::DISPFlags
>(attr.getSubprogramFlags()),
284 distinctAttrToNode.try_emplace(attr.getId(), node);
288 llvm::DIModule *DebugTranslation::translateImpl(DIModuleAttr attr) {
291 getMDStringOrNull(attr.getName()),
292 getMDStringOrNull(attr.getConfigMacros()),
293 getMDStringOrNull(attr.getIncludePath()),
294 getMDStringOrNull(attr.getApinotes()), attr.getLine(), attr.getIsDecl());
297 llvm::DINamespace *DebugTranslation::translateImpl(DINamespaceAttr attr) {
299 getMDStringOrNull(attr.getName()),
300 attr.getExportSymbols());
303 llvm::DISubrange *DebugTranslation::translateImpl(DISubrangeAttr attr) {
304 auto getMetadataOrNull = [&](IntegerAttr attr) -> llvm::Metadata * {
308 llvm::Type::getInt64Ty(llvmCtx), attr.getInt()));
311 getMetadataOrNull(attr.getLowerBound()),
312 getMetadataOrNull(attr.getUpperBound()),
313 getMetadataOrNull(attr.getStride()));
316 llvm::DISubroutineType *
317 DebugTranslation::translateImpl(DISubroutineTypeAttr attr) {
323 llvmCtx, llvm::DINode::FlagZero, attr.getCallingConvention(),
327 llvm::DIType *DebugTranslation::translateImpl(
DITypeAttr attr) {
335 if (llvm::DINode *node = attrToNode.lookup(attr))
338 llvm::DINode *node =
nullptr;
341 if (
auto recTypeAttr = dyn_cast<DIRecursiveTypeAttrInterface>(attr))
342 if (recTypeAttr.getRecId())
343 node = translateRecursive(recTypeAttr);
347 .Case<DIBasicTypeAttr, DICompileUnitAttr, DICompositeTypeAttr,
348 DIDerivedTypeAttr, DIFileAttr, DIGlobalVariableAttr,
349 DILabelAttr, DILexicalBlockAttr, DILexicalBlockFileAttr,
350 DILocalVariableAttr, DIModuleAttr, DINamespaceAttr,
351 DINullTypeAttr, DISubprogramAttr, DISubrangeAttr,
352 DISubroutineTypeAttr>(
353 [&](
auto attr) {
return translateImpl(attr); });
355 if (node && !node->isTemporary())
356 attrToNode.insert({attr, node});
365 llvm::DILocation *DebugTranslation::translateLoc(
Location loc,
366 llvm::DILocalScope *scope) {
367 if (!debugEmissionIsEnabled)
369 return translateLoc(loc, scope,
nullptr);
373 DebugTranslation::translateExpression(LLVM::DIExpressionAttr attr) {
377 for (
const DIExpressionElemAttr &op : attr.getOperations()) {
378 ops.push_back(op.getOpcode());
379 append_range(ops, op.getArguments());
385 llvm::DIGlobalVariableExpression *
386 DebugTranslation::translateGlobalVariableExpression(
387 LLVM::DIGlobalVariableExpressionAttr attr) {
389 llvmCtx, translate(attr.getVar()), translateExpression(attr.getExpr()));
393 llvm::DILocation *DebugTranslation::translateLoc(
Location loc,
394 llvm::DILocalScope *scope,
395 llvm::DILocation *inlinedAt) {
397 if (isa<UnknownLoc>(loc))
401 auto existingIt = locationToLoc.find(std::make_tuple(loc, scope, inlinedAt));
402 if (existingIt != locationToLoc.end())
403 return existingIt->second;
405 llvm::DILocation *llvmLoc =
nullptr;
406 if (
auto callLoc = dyn_cast<CallSiteLoc>(loc)) {
408 auto *callerLoc = translateLoc(callLoc.getCaller(), scope, inlinedAt);
409 llvmLoc = translateLoc(callLoc.getCallee(),
nullptr, callerLoc);
414 }
else if (
auto fileLoc = dyn_cast<FileLineColLoc>(loc)) {
420 scope,
const_cast<llvm::DILocation *
>(inlinedAt));
422 }
else if (
auto fusedLoc = dyn_cast<FusedLoc>(loc)) {
426 if (
auto scopedAttr =
427 dyn_cast_or_null<LLVM::DILocalScopeAttr>(fusedLoc.getMetadata()))
428 scope = translate(scopedAttr);
431 llvmLoc = translateLoc(locations.front(), scope, inlinedAt);
432 for (
Location locIt : locations.drop_front()) {
433 llvmLoc = llvm::DILocation::getMergedLocation(
434 llvmLoc, translateLoc(locIt, scope, inlinedAt));
437 }
else if (
auto nameLoc = dyn_cast<NameLoc>(loc)) {
438 llvmLoc = translateLoc(nameLoc.getChildLoc(), scope, inlinedAt);
440 }
else if (
auto opaqueLoc = dyn_cast<OpaqueLoc>(loc)) {
441 llvmLoc = translateLoc(opaqueLoc.getFallbackLocation(), scope, inlinedAt);
443 llvm_unreachable(
"unknown location kind");
446 locationToLoc.try_emplace(std::make_tuple(loc, scope, inlinedAt), llvmLoc);
451 llvm::DIFile *DebugTranslation::translateFile(StringRef fileName) {
452 auto *&file = fileMap[fileName];
457 if (currentWorkingDir.empty())
458 llvm::sys::fs::current_path(currentWorkingDir);
460 StringRef directory = currentWorkingDir;
463 if (llvm::sys::path::is_absolute(fileName)) {
466 auto fileIt = llvm::sys::path::begin(fileName);
467 auto fileE = llvm::sys::path::end(fileName);
468 auto curDirIt = llvm::sys::path::begin(directory);
469 auto curDirE = llvm::sys::path::end(directory);
470 for (; curDirIt != curDirE && *curDirIt == *fileIt; ++curDirIt, ++fileIt)
471 llvm::sys::path::append(dirBuf, *curDirIt);
472 if (std::distance(llvm::sys::path::begin(directory), curDirIt) == 1) {
475 directory = StringRef();
477 for (; fileIt != fileE; ++fileIt)
478 llvm::sys::path::append(fileBuf, *fileIt);
static DINodeT * getDistinctOrUnique(bool isDistinct, Ts &&...args)
Returns a new DINodeT that is either distinct or not, depending on isDistinct.
static WalkResult interruptIfValidLocation(Operation *op)
A utility walker that interrupts if the operation has valid debug information.
static MLIRContext * getContext(OpFoldResult val)
An attribute that associates a referenced attribute with a unique identifier.
This class represents a fused location whose metadata is known to be an instance of the given type.
This class represents a LLVM attribute that describes a local debug info scope.
This class represents the base attribute for all debug info attributes.
This class represents a LLVM attribute that describes a debug info scope.
This class represents a LLVM attribute that describes a debug info type.
void finalize()
Finalize the translation of debug information.
void translate(LLVMFuncOp func, llvm::Function &llvmFunc)
Translate the debug information for the given function.
DebugTranslation(Operation *module, llvm::Module &llvmModule)
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Operation is the basic unit of execution within MLIR.
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns an null Attribute if the discardable attribute does n...
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),...
Location getLoc()
The source location the operation was defined or derived from.
A utility result that is used to signal how to proceed with an ongoing walk:
static WalkResult advance()
static WalkResult interrupt()
Include the generated interface declarations.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...