| 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" |
| 10 | #include "mlir/Dialect/LLVMIR/LLVMModuleOps.h" |
| 11 | #include "llvm/ADT/SmallVectorExtras.h" |
| 12 | #include "llvm/ADT/TypeSwitch.h" |
| 13 | #include "llvm/IR/Constants.h" |
| 14 | #include "llvm/IR/Metadata.h" |
| 15 | #include "llvm/IR/Module.h" |
| 16 | #include "llvm/Support/ErrorHandling.h" |
| 17 | #include "llvm/Support/FileSystem.h" |
| 18 | #include "llvm/Support/Path.h" |
| 19 | |
| 20 | using namespace mlir; |
| 21 | using namespace mlir::LLVM; |
| 22 | using namespace mlir::LLVM::detail; |
| 23 | |
| 24 | /// A utility walker that interrupts if the operation has valid debug |
| 25 | /// information. |
| 26 | static WalkResult interruptIfValidLocation(Operation *op) { |
| 27 | return isa<UnknownLoc>(Val: op->getLoc()) ? WalkResult::advance() |
| 28 | : WalkResult::interrupt(); |
| 29 | } |
| 30 | |
| 31 | DebugTranslation::DebugTranslation(Operation *module, llvm::Module &llvmModule) |
| 32 | : debugEmissionIsEnabled(false), llvmModule(llvmModule), |
| 33 | llvmCtx(llvmModule.getContext()) { |
| 34 | // If the module has no location information, there is nothing to do. |
| 35 | if (!module->walk(callback&: interruptIfValidLocation).wasInterrupted()) |
| 36 | return; |
| 37 | debugEmissionIsEnabled = true; |
| 38 | } |
| 39 | |
| 40 | static constexpr StringRef kDebugVersionKey = "Debug Info Version" ; |
| 41 | static constexpr StringRef kCodeViewKey = "CodeView" ; |
| 42 | |
| 43 | void DebugTranslation::addModuleFlagsIfNotPresent() { |
| 44 | // TODO: The version information should be encoded on the LLVM module itself, |
| 45 | // not implicitly set here. |
| 46 | |
| 47 | // Mark this module as having debug information. |
| 48 | if (!llvmModule.getModuleFlag(Key: kDebugVersionKey)) |
| 49 | llvmModule.addModuleFlag(Behavior: llvm::Module::Warning, Key: kDebugVersionKey, |
| 50 | Val: llvm::DEBUG_METADATA_VERSION); |
| 51 | |
| 52 | const llvm::Triple &targetTriple = llvmModule.getTargetTriple(); |
| 53 | if (targetTriple.isKnownWindowsMSVCEnvironment()) { |
| 54 | // Dwarf debugging files will be generated by default, unless "CodeView" |
| 55 | // is set explicitly. Windows/MSVC should use CodeView instead. |
| 56 | if (!llvmModule.getModuleFlag(Key: kCodeViewKey)) |
| 57 | llvmModule.addModuleFlag(Behavior: llvm::Module::Warning, Key: kCodeViewKey, Val: 1); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | /// Translate the debug information for the given function. |
| 62 | void DebugTranslation::translate(LLVMFuncOp func, llvm::Function &llvmFunc) { |
| 63 | if (!debugEmissionIsEnabled) |
| 64 | return; |
| 65 | |
| 66 | // Look for a sub program attached to the function. |
| 67 | auto spLoc = |
| 68 | func.getLoc()->findInstanceOf<FusedLocWith<LLVM::DISubprogramAttr>>(); |
| 69 | if (!spLoc) |
| 70 | return; |
| 71 | llvmFunc.setSubprogram(translate(attr: spLoc.getMetadata())); |
| 72 | } |
| 73 | |
| 74 | //===----------------------------------------------------------------------===// |
| 75 | // Attributes |
| 76 | //===----------------------------------------------------------------------===// |
| 77 | |
| 78 | llvm::DIType *DebugTranslation::translateImpl(DINullTypeAttr attr) { |
| 79 | // A DINullTypeAttr at the beginning of the subroutine types list models |
| 80 | // a void result type. If it is at the end, it models a variadic function. |
| 81 | // Translate the explicit DINullTypeAttr to a nullptr since LLVM IR metadata |
| 82 | // does not have an explicit void result type nor a variadic type |
| 83 | // representation. |
| 84 | return nullptr; |
| 85 | } |
| 86 | |
| 87 | llvm::DIExpression * |
| 88 | DebugTranslation::getExpressionAttrOrNull(DIExpressionAttr attr) { |
| 89 | if (!attr) |
| 90 | return nullptr; |
| 91 | return translateExpression(attr); |
| 92 | } |
| 93 | |
| 94 | llvm::MDString *DebugTranslation::getMDStringOrNull(StringAttr stringAttr) { |
| 95 | if (!stringAttr || stringAttr.empty()) |
| 96 | return nullptr; |
| 97 | return llvm::MDString::get(Context&: llvmCtx, Str: stringAttr); |
| 98 | } |
| 99 | |
| 100 | llvm::MDTuple * |
| 101 | DebugTranslation::getMDTupleOrNull(ArrayRef<DINodeAttr> elements) { |
| 102 | if (elements.empty()) |
| 103 | return nullptr; |
| 104 | SmallVector<llvm::Metadata *> llvmElements = |
| 105 | llvm::map_to_vector(C&: elements, F: [&](DINodeAttr attr) -> llvm::Metadata * { |
| 106 | if (DIAnnotationAttr annAttr = dyn_cast<DIAnnotationAttr>(Val&: attr)) { |
| 107 | llvm::Metadata *ops[2] = { |
| 108 | llvm::MDString::get(Context&: llvmCtx, Str: annAttr.getName()), |
| 109 | llvm::MDString::get(Context&: llvmCtx, Str: annAttr.getValue())}; |
| 110 | return llvm::MDNode::get(Context&: llvmCtx, MDs: ops); |
| 111 | } |
| 112 | return translate(attr); |
| 113 | }); |
| 114 | return llvm::MDNode::get(Context&: llvmCtx, MDs: llvmElements); |
| 115 | } |
| 116 | |
| 117 | llvm::MDTuple * |
| 118 | DebugTranslation::getRetainedNodesOrNull(ArrayRef<Attribute> retainedNodes) { |
| 119 | if (retainedNodes.empty()) |
| 120 | return nullptr; |
| 121 | SmallVector<llvm::Metadata *> llvmElements = llvm::map_to_vector( |
| 122 | C&: retainedNodes, F: [&](Attribute attr) -> llvm::Metadata * { |
| 123 | if (auto GVE = dyn_cast<DIGlobalVariableExpressionAttr>(Val&: attr)) |
| 124 | return translateGlobalVariableExpression(attr: GVE); |
| 125 | |
| 126 | auto diAttr = dyn_cast<DINodeAttr>(Val&: attr); |
| 127 | if (!diAttr) |
| 128 | llvm_unreachable("unknown retained node kind" ); |
| 129 | return translate(attr: diAttr); |
| 130 | }); |
| 131 | return llvm::MDNode::get(Context&: llvmCtx, MDs: llvmElements); |
| 132 | } |
| 133 | |
| 134 | llvm::DIBasicType *DebugTranslation::translateImpl(DIBasicTypeAttr attr) { |
| 135 | return llvm::DIBasicType::get( |
| 136 | Context&: llvmCtx, Tag: attr.getTag(), Name: getMDStringOrNull(stringAttr: attr.getName()), |
| 137 | SizeInBits: attr.getSizeInBits(), |
| 138 | /*AlignInBits=*/0, Encoding: attr.getEncoding(), Flags: llvm::DINode::FlagZero); |
| 139 | } |
| 140 | |
| 141 | static llvm::DISourceLanguageName getSourceLanguage(DICompileUnitAttr attr) { |
| 142 | DISourceLanguageNameAttr sourceLanguage = attr.getSourceLanguage(); |
| 143 | // A DW_LNAME value selects the versioned source-language representation; |
| 144 | // otherwise, the value is an unversioned DW_LANG value. |
| 145 | if (sourceLanguage.getName()) |
| 146 | return llvm::DISourceLanguageName( |
| 147 | static_cast<uint16_t>(sourceLanguage.getName()), |
| 148 | *sourceLanguage.getVersion(), |
| 149 | static_cast<uint16_t>(sourceLanguage.getDialect())); |
| 150 | return llvm::DISourceLanguageName( |
| 151 | static_cast<uint16_t>(sourceLanguage.getLanguage()), |
| 152 | static_cast<uint16_t>(sourceLanguage.getDialect())); |
| 153 | } |
| 154 | |
| 155 | llvm::TempDICompileUnit |
| 156 | DebugTranslation::translateTemporaryImpl(DICompileUnitAttr attr) { |
| 157 | return llvm::DICompileUnit::getTemporary( |
| 158 | Context&: llvmCtx, SourceLanguage: getSourceLanguage(attr), |
| 159 | /*File=*/nullptr, Producer: "" , IsOptimized: attr.getIsOptimized(), |
| 160 | /*Flags=*/"" , /*RuntimeVersion=*/0, |
| 161 | /*splitDebugFileName=*/SplitDebugFilename: "" , |
| 162 | EmissionKind: static_cast<llvm::DICompileUnit::DebugEmissionKind>( |
| 163 | attr.getEmissionKind()), |
| 164 | /*EnumTypes=*/nullptr, /*RetainedTypes=*/nullptr, |
| 165 | /*GlobalVariables=*/nullptr, /*ImportedEntities=*/nullptr, |
| 166 | /*Macros=*/nullptr, |
| 167 | /*DWOId=*/0, /*SplitDebugInlining=*/true, |
| 168 | DebugInfoForProfiling: attr.getIsDebugInfoForProfiling(), |
| 169 | NameTableKind: static_cast<llvm::DICompileUnit::DebugNameTableKind>( |
| 170 | attr.getNameTableKind()), |
| 171 | /*RangesBaseAddress=*/false, /*SysRoot=*/"" , /*SDK=*/"" ); |
| 172 | } |
| 173 | |
| 174 | llvm::DICompileUnit *DebugTranslation::translateImpl(DICompileUnitAttr attr) { |
| 175 | if (attr.getId()) |
| 176 | if (auto iter = distinctAttrToNode.find(Val: attr.getId()); |
| 177 | iter != distinctAttrToNode.end()) |
| 178 | return cast<llvm::DICompileUnit>(Val: iter->second); |
| 179 | |
| 180 | llvm::DIBuilder builder(llvmModule); |
| 181 | llvm::DICompileUnit *cu = builder.createCompileUnit( |
| 182 | Lang: getSourceLanguage(attr), File: translate(attr: attr.getFile()), |
| 183 | Producer: attr.getProducer() ? attr.getProducer().getValue() : "" , |
| 184 | isOptimized: attr.getIsOptimized(), |
| 185 | /*Flags=*/"" , /*RV=*/0, |
| 186 | SplitName: attr.getSplitDebugFilename() ? attr.getSplitDebugFilename().getValue() |
| 187 | : "" , |
| 188 | Kind: static_cast<llvm::DICompileUnit::DebugEmissionKind>( |
| 189 | attr.getEmissionKind()), |
| 190 | DWOId: 0, SplitDebugInlining: true, DebugInfoForProfiling: attr.getIsDebugInfoForProfiling(), |
| 191 | NameTableKind: static_cast<llvm::DICompileUnit::DebugNameTableKind>( |
| 192 | attr.getNameTableKind())); |
| 193 | |
| 194 | llvm::SmallVector<llvm::Metadata *> importNodes; |
| 195 | for (DINodeAttr importNode : attr.getImportedEntities()) |
| 196 | importNodes.push_back(Elt: translate(attr: importNode)); |
| 197 | if (!importNodes.empty()) |
| 198 | cu->replaceImportedEntities(N: llvm::MDTuple::get(Context&: llvmCtx, MDs: importNodes)); |
| 199 | |
| 200 | if (attr.getId()) |
| 201 | distinctAttrToNode.try_emplace(Key: attr.getId(), Args&: cu); |
| 202 | |
| 203 | return cu; |
| 204 | } |
| 205 | |
| 206 | /// Returns a new `DINodeT` that is either distinct or not, depending on |
| 207 | /// `isDistinct`. |
| 208 | template <class DINodeT, class... Ts> |
| 209 | static DINodeT *getDistinctOrUnique(bool isDistinct, Ts &&...args) { |
| 210 | if (isDistinct) |
| 211 | return DINodeT::getDistinct(std::forward<Ts>(args)...); |
| 212 | return DINodeT::get(std::forward<Ts>(args)...); |
| 213 | } |
| 214 | |
| 215 | llvm::TempDICompositeType |
| 216 | DebugTranslation::translateTemporaryImpl(DICompositeTypeAttr attr) { |
| 217 | return llvm::DICompositeType::getTemporary( |
| 218 | Context&: llvmCtx, Tag: attr.getTag(), Name: getMDStringOrNull(stringAttr: attr.getName()), File: nullptr, |
| 219 | Line: attr.getLine(), Scope: nullptr, BaseType: nullptr, SizeInBits: attr.getSizeInBits(), |
| 220 | AlignInBits: attr.getAlignInBits(), |
| 221 | /*OffsetInBits=*/0, |
| 222 | /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()), |
| 223 | /*Elements=*/nullptr, /*RuntimeLang=*/0, /*EnumKind=*/std::nullopt, |
| 224 | /*VTableHolder=*/nullptr); |
| 225 | } |
| 226 | |
| 227 | llvm::TempDISubprogram |
| 228 | DebugTranslation::translateTemporaryImpl(DISubprogramAttr attr) { |
| 229 | return llvm::DISubprogram::getTemporary( |
| 230 | Context&: llvmCtx, /*Scope=*/nullptr, /*Name=*/{}, /*LinkageName=*/{}, |
| 231 | /*File=*/nullptr, Line: attr.getLine(), /*Type=*/nullptr, |
| 232 | /*ScopeLine=*/0, /*ContainingType=*/nullptr, /*VirtualIndex=*/0, |
| 233 | /*ThisAdjustment=*/0, Flags: llvm::DINode::FlagZero, |
| 234 | SPFlags: static_cast<llvm::DISubprogram::DISPFlags>(attr.getSubprogramFlags()), |
| 235 | /*Unit=*/nullptr); |
| 236 | } |
| 237 | |
| 238 | llvm::DICompositeType * |
| 239 | DebugTranslation::translateImpl(DICompositeTypeAttr attr) { |
| 240 | // TODO: Use distinct attributes to model this, once they have landed. |
| 241 | // Depending on the tag, composite types must be distinct. |
| 242 | bool isDistinct = false; |
| 243 | switch (attr.getTag()) { |
| 244 | case llvm::dwarf::DW_TAG_class_type: |
| 245 | case llvm::dwarf::DW_TAG_enumeration_type: |
| 246 | case llvm::dwarf::DW_TAG_structure_type: |
| 247 | case llvm::dwarf::DW_TAG_union_type: |
| 248 | case llvm::dwarf::DW_TAG_variant_part: |
| 249 | isDistinct = true; |
| 250 | } |
| 251 | |
| 252 | return getDistinctOrUnique<llvm::DICompositeType>( |
| 253 | isDistinct, args&: llvmCtx, args: attr.getTag(), args: getMDStringOrNull(stringAttr: attr.getName()), |
| 254 | args: translate(attr: attr.getFile()), args: attr.getLine(), args: translate(attr: attr.getScope()), |
| 255 | args: translate(attr: attr.getBaseType()), args: attr.getSizeInBits(), |
| 256 | args: attr.getAlignInBits(), |
| 257 | /*OffsetInBits=*/args: 0, |
| 258 | /*Flags=*/args: static_cast<llvm::DINode::DIFlags>(attr.getFlags()), |
| 259 | args: getMDTupleOrNull(elements: attr.getElements()), |
| 260 | /*RuntimeLang=*/args: 0, /*EnumKind*/ args: std::nullopt, /*VTableHolder=*/args: nullptr, |
| 261 | /*TemplateParams=*/args: nullptr, args: getMDStringOrNull(stringAttr: attr.getIdentifier()), |
| 262 | args: translate(attr: attr.getDiscriminator()), |
| 263 | args: getExpressionAttrOrNull(attr: attr.getDataLocation()), |
| 264 | args: getExpressionAttrOrNull(attr: attr.getAssociated()), |
| 265 | args: getExpressionAttrOrNull(attr: attr.getAllocated()), |
| 266 | args: getExpressionAttrOrNull(attr: attr.getRank())); |
| 267 | } |
| 268 | |
| 269 | llvm::DIDerivedType *DebugTranslation::translateImpl(DIDerivedTypeAttr attr) { |
| 270 | llvm::Metadata * = nullptr; |
| 271 | if (Attribute = attr.getExtraData()) { |
| 272 | extraData = |
| 273 | llvm::TypeSwitch<Attribute, llvm::Metadata *>(extraDataAttr) |
| 274 | .Case(caseFn: [&](DINodeAttr nodeAttr) { return translate(attr: nodeAttr); }) |
| 275 | .Case(caseFn: [&](IntegerAttr intAttr) { |
| 276 | return llvm::ConstantAsMetadata::get( |
| 277 | C: llvm::ConstantInt::get(Context&: llvmCtx, V: intAttr.getValue())); |
| 278 | }) |
| 279 | .DefaultUnreachable( |
| 280 | message: "verifier guarantees DINodeAttr or IntegerAttr" ); |
| 281 | } |
| 282 | |
| 283 | return llvm::DIDerivedType::get( |
| 284 | Context&: llvmCtx, Tag: attr.getTag(), Name: getMDStringOrNull(stringAttr: attr.getName()), |
| 285 | File: translate(attr: attr.getFile()), Line: attr.getLine(), Scope: translate(attr: attr.getScope()), |
| 286 | BaseType: translate(attr: attr.getBaseType()), SizeInBits: attr.getSizeInBits(), |
| 287 | AlignInBits: attr.getAlignInBits(), OffsetInBits: attr.getOffsetInBits(), |
| 288 | DWARFAddressSpace: attr.getDwarfAddressSpace(), /*PtrAuthData=*/std::nullopt, |
| 289 | /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()), ExtraData: extraData); |
| 290 | } |
| 291 | |
| 292 | llvm::DIEnumerator *DebugTranslation::translateImpl(DIEnumeratorAttr attr) { |
| 293 | return llvm::DIEnumerator::get(Context&: llvmCtx, Value: attr.getValue().getValue(), |
| 294 | IsUnsigned: attr.getIsUnsigned(), |
| 295 | Name: getMDStringOrNull(stringAttr: attr.getName())); |
| 296 | } |
| 297 | |
| 298 | llvm::DIStringType *DebugTranslation::translateImpl(DIStringTypeAttr attr) { |
| 299 | return llvm::DIStringType::get( |
| 300 | Context&: llvmCtx, Tag: attr.getTag(), Name: getMDStringOrNull(stringAttr: attr.getName()), |
| 301 | StringLength: translate(attr: attr.getStringLength()), |
| 302 | StringLengthExp: getExpressionAttrOrNull(attr: attr.getStringLengthExp()), |
| 303 | StringLocationExp: getExpressionAttrOrNull(attr: attr.getStringLocationExp()), |
| 304 | SizeInBits: attr.getSizeInBits(), AlignInBits: attr.getAlignInBits(), Encoding: attr.getEncoding(), |
| 305 | CharType: translate(attr: attr.getCharType())); |
| 306 | } |
| 307 | |
| 308 | llvm::DIFile *DebugTranslation::translateImpl(DIFileAttr attr) { |
| 309 | return llvm::DIFile::get(Context&: llvmCtx, Filename: getMDStringOrNull(stringAttr: attr.getName()), |
| 310 | Directory: getMDStringOrNull(stringAttr: attr.getDirectory())); |
| 311 | } |
| 312 | |
| 313 | llvm::DILabel *DebugTranslation::translateImpl(DILabelAttr attr) { |
| 314 | return llvm::DILabel::get(Context&: llvmCtx, Scope: translate(attr: attr.getScope()), |
| 315 | Name: getMDStringOrNull(stringAttr: attr.getName()), |
| 316 | File: translate(attr: attr.getFile()), Line: attr.getLine(), |
| 317 | /*Column=*/0, /*IsArtificial=*/false, |
| 318 | /*CoroSuspendIdx=*/std::nullopt); |
| 319 | } |
| 320 | |
| 321 | llvm::DILexicalBlock *DebugTranslation::translateImpl(DILexicalBlockAttr attr) { |
| 322 | return llvm::DILexicalBlock::getDistinct(Context&: llvmCtx, Scope: translate(attr: attr.getScope()), |
| 323 | File: translate(attr: attr.getFile()), |
| 324 | Line: attr.getLine(), Column: attr.getColumn()); |
| 325 | } |
| 326 | |
| 327 | llvm::DILexicalBlockFile * |
| 328 | DebugTranslation::translateImpl(DILexicalBlockFileAttr attr) { |
| 329 | return llvm::DILexicalBlockFile::getDistinct( |
| 330 | Context&: llvmCtx, Scope: translate(attr: attr.getScope()), File: translate(attr: attr.getFile()), |
| 331 | Discriminator: attr.getDiscriminator()); |
| 332 | } |
| 333 | |
| 334 | llvm::DILocalScope *DebugTranslation::translateImpl(DILocalScopeAttr attr) { |
| 335 | return cast<llvm::DILocalScope>(Val: translate(attr: DINodeAttr(attr))); |
| 336 | } |
| 337 | |
| 338 | llvm::DIVariable *DebugTranslation::translateImpl(DIVariableAttr attr) { |
| 339 | return cast<llvm::DIVariable>(Val: translate(attr: DINodeAttr(attr))); |
| 340 | } |
| 341 | |
| 342 | llvm::DILocalVariable * |
| 343 | DebugTranslation::translateImpl(DILocalVariableAttr attr) { |
| 344 | return llvm::DILocalVariable::get( |
| 345 | Context&: llvmCtx, Scope: translate(attr: attr.getScope()), Name: getMDStringOrNull(stringAttr: attr.getName()), |
| 346 | File: translate(attr: attr.getFile()), Line: attr.getLine(), Type: translate(attr: attr.getType()), |
| 347 | Arg: attr.getArg(), Flags: static_cast<llvm::DINode::DIFlags>(attr.getFlags()), |
| 348 | AlignInBits: attr.getAlignInBits(), |
| 349 | /*Annotations=*/nullptr); |
| 350 | } |
| 351 | |
| 352 | llvm::DIGlobalVariable * |
| 353 | DebugTranslation::translateImpl(DIGlobalVariableAttr attr) { |
| 354 | return llvm::DIGlobalVariable::getDistinct( |
| 355 | Context&: llvmCtx, Scope: translate(attr: attr.getScope()), Name: getMDStringOrNull(stringAttr: attr.getName()), |
| 356 | LinkageName: getMDStringOrNull(stringAttr: attr.getLinkageName()), File: translate(attr: attr.getFile()), |
| 357 | Line: attr.getLine(), Type: translate(attr: attr.getType()), IsLocalToUnit: attr.getIsLocalToUnit(), |
| 358 | IsDefinition: attr.getIsDefined(), StaticDataMemberDeclaration: nullptr, TemplateParams: nullptr, AlignInBits: attr.getAlignInBits(), Annotations: nullptr); |
| 359 | } |
| 360 | |
| 361 | llvm::DINode * |
| 362 | DebugTranslation::translateRecursive(DIRecursiveTypeAttrInterface attr) { |
| 363 | DistinctAttr recursiveId = attr.getRecId(); |
| 364 | if (auto *iter = recursiveNodeMap.find(Key: recursiveId); |
| 365 | iter != recursiveNodeMap.end()) { |
| 366 | return iter->second; |
| 367 | } |
| 368 | assert(!attr.getIsRecSelf() && "unbound DI recursive self reference" ); |
| 369 | |
| 370 | auto setRecursivePlaceholder = [&](llvm::DINode *placeholder) { |
| 371 | recursiveNodeMap.try_emplace(Key: recursiveId, Args&: placeholder); |
| 372 | }; |
| 373 | |
| 374 | llvm::DINode *result = |
| 375 | TypeSwitch<DIRecursiveTypeAttrInterface, llvm::DINode *>(attr) |
| 376 | .Case(caseFn: [&](DICompositeTypeAttr attr) { |
| 377 | auto temporary = translateTemporaryImpl(attr); |
| 378 | setRecursivePlaceholder(temporary.get()); |
| 379 | // Must call `translateImpl` directly instead of `translate` to |
| 380 | // avoid handling the recursive interface again. |
| 381 | auto *concrete = translateImpl(attr); |
| 382 | temporary->replaceAllUsesWith(MD: concrete); |
| 383 | return concrete; |
| 384 | }) |
| 385 | .Case(caseFn: [&](DISubprogramAttr attr) { |
| 386 | auto temporary = translateTemporaryImpl(attr); |
| 387 | setRecursivePlaceholder(temporary.get()); |
| 388 | // Must call `translateImpl` directly instead of `translate` to |
| 389 | // avoid handling the recursive interface again. |
| 390 | auto *concrete = translateImpl(attr); |
| 391 | temporary->replaceAllUsesWith(MD: concrete); |
| 392 | return concrete; |
| 393 | }) |
| 394 | .Case(caseFn: [&](DICompileUnitAttr attr) { |
| 395 | auto temporary = translateTemporaryImpl(attr); |
| 396 | setRecursivePlaceholder(temporary.get()); |
| 397 | auto *concrete = translateImpl(attr); |
| 398 | temporary->replaceAllUsesWith(MD: concrete); |
| 399 | return concrete; |
| 400 | }); |
| 401 | |
| 402 | assert(recursiveNodeMap.back().first == recursiveId && |
| 403 | "internal inconsistency: unexpected recursive translation stack" ); |
| 404 | recursiveNodeMap.pop_back(); |
| 405 | |
| 406 | return result; |
| 407 | } |
| 408 | |
| 409 | llvm::DIScope *DebugTranslation::translateImpl(DIScopeAttr attr) { |
| 410 | return cast<llvm::DIScope>(Val: translate(attr: DINodeAttr(attr))); |
| 411 | } |
| 412 | |
| 413 | llvm::DISubprogram *DebugTranslation::translateImpl(DISubprogramAttr attr) { |
| 414 | if (auto iter = distinctAttrToNode.find(Val: attr.getId()); |
| 415 | iter != distinctAttrToNode.end()) |
| 416 | return cast<llvm::DISubprogram>(Val: iter->second); |
| 417 | |
| 418 | llvm::DIScope *scope = translate(attr: attr.getScope()); |
| 419 | llvm::DIFile *file = translate(attr: attr.getFile()); |
| 420 | llvm::DIType *type = translate(attr: attr.getType()); |
| 421 | llvm::DICompileUnit *compileUnit = translate(attr: attr.getCompileUnit()); |
| 422 | |
| 423 | // Check again after recursive calls in case this distinct node recurses back |
| 424 | // to itself. |
| 425 | if (auto iter = distinctAttrToNode.find(Val: attr.getId()); |
| 426 | iter != distinctAttrToNode.end()) |
| 427 | return cast<llvm::DISubprogram>(Val: iter->second); |
| 428 | |
| 429 | bool isDefinition = static_cast<bool>(attr.getSubprogramFlags() & |
| 430 | LLVM::DISubprogramFlags::Definition); |
| 431 | |
| 432 | llvm::DISubprogram *node = getDistinctOrUnique<llvm::DISubprogram>( |
| 433 | isDistinct: isDefinition, args&: llvmCtx, args&: scope, args: getMDStringOrNull(stringAttr: attr.getName()), |
| 434 | args: getMDStringOrNull(stringAttr: attr.getLinkageName()), args&: file, args: attr.getLine(), args&: type, |
| 435 | args: attr.getScopeLine(), |
| 436 | /*ContainingType=*/args: nullptr, /*VirtualIndex=*/args: 0, |
| 437 | /*ThisAdjustment=*/args: 0, args: llvm::DINode::FlagZero, |
| 438 | args: static_cast<llvm::DISubprogram::DISPFlags>(attr.getSubprogramFlags()), |
| 439 | args&: compileUnit, /*TemplateParams=*/args: nullptr, /*Declaration=*/args: nullptr, |
| 440 | args: getRetainedNodesOrNull(retainedNodes: attr.getRetainedNodes()), args: nullptr, |
| 441 | args: getMDTupleOrNull(elements: attr.getAnnotations())); |
| 442 | if (attr.getId()) |
| 443 | distinctAttrToNode.try_emplace(Key: attr.getId(), Args&: node); |
| 444 | return node; |
| 445 | } |
| 446 | |
| 447 | llvm::DIModule *DebugTranslation::translateImpl(DIModuleAttr attr) { |
| 448 | return llvm::DIModule::get( |
| 449 | Context&: llvmCtx, File: translate(attr: attr.getFile()), Scope: translate(attr: attr.getScope()), |
| 450 | Name: getMDStringOrNull(stringAttr: attr.getName()), |
| 451 | ConfigurationMacros: getMDStringOrNull(stringAttr: attr.getConfigMacros()), |
| 452 | IncludePath: getMDStringOrNull(stringAttr: attr.getIncludePath()), |
| 453 | APINotesFile: getMDStringOrNull(stringAttr: attr.getApinotes()), LineNo: attr.getLine(), IsDecl: attr.getIsDecl()); |
| 454 | } |
| 455 | |
| 456 | llvm::DINamespace *DebugTranslation::translateImpl(DINamespaceAttr attr) { |
| 457 | return llvm::DINamespace::get(Context&: llvmCtx, Scope: translate(attr: attr.getScope()), |
| 458 | Name: getMDStringOrNull(stringAttr: attr.getName()), |
| 459 | ExportSymbols: attr.getExportSymbols()); |
| 460 | } |
| 461 | |
| 462 | llvm::DIImportedEntity * |
| 463 | DebugTranslation::translateImpl(DIImportedEntityAttr attr) { |
| 464 | return llvm::DIImportedEntity::get( |
| 465 | Context&: llvmCtx, Tag: attr.getTag(), Scope: translate(attr: attr.getScope()), |
| 466 | Entity: translate(attr: attr.getEntity()), File: translate(attr: attr.getFile()), Line: attr.getLine(), |
| 467 | Name: getMDStringOrNull(stringAttr: attr.getName()), Elements: getMDTupleOrNull(elements: attr.getElements())); |
| 468 | } |
| 469 | |
| 470 | llvm::DISubrange *DebugTranslation::translateImpl(DISubrangeAttr attr) { |
| 471 | auto getMetadataOrNull = [&](Attribute attr) -> llvm::Metadata * { |
| 472 | if (!attr) |
| 473 | return nullptr; |
| 474 | |
| 475 | llvm::Metadata *metadata = |
| 476 | llvm::TypeSwitch<Attribute, llvm::Metadata *>(attr) |
| 477 | .Case(caseFn: [&](IntegerAttr intAttr) { |
| 478 | return llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
| 479 | Ty: llvm::Type::getInt64Ty(C&: llvmCtx), V: intAttr.getInt())); |
| 480 | }) |
| 481 | .Case(caseFn: [&](LLVM::DIExpressionAttr expr) { |
| 482 | return translateExpression(attr: expr); |
| 483 | }) |
| 484 | .Case(caseFn: [&](LLVM::DILocalVariableAttr local) { |
| 485 | return translate(attr: local); |
| 486 | }) |
| 487 | .Case<>(caseFn: [&](LLVM::DIGlobalVariableAttr global) { |
| 488 | return translate(attr: global); |
| 489 | }) |
| 490 | .Default(nullptr); |
| 491 | return metadata; |
| 492 | }; |
| 493 | return llvm::DISubrange::get(Context&: llvmCtx, CountNode: getMetadataOrNull(attr.getCount()), |
| 494 | LowerBound: getMetadataOrNull(attr.getLowerBound()), |
| 495 | UpperBound: getMetadataOrNull(attr.getUpperBound()), |
| 496 | Stride: getMetadataOrNull(attr.getStride())); |
| 497 | } |
| 498 | |
| 499 | llvm::DICommonBlock *DebugTranslation::translateImpl(DICommonBlockAttr attr) { |
| 500 | return llvm::DICommonBlock::get(Context&: llvmCtx, Scope: translate(attr: attr.getScope()), |
| 501 | Decl: translate(attr: attr.getDecl()), |
| 502 | Name: getMDStringOrNull(stringAttr: attr.getName()), |
| 503 | File: translate(attr: attr.getFile()), LineNo: attr.getLine()); |
| 504 | } |
| 505 | |
| 506 | llvm::DIGenericSubrange * |
| 507 | DebugTranslation::translateImpl(DIGenericSubrangeAttr attr) { |
| 508 | auto getMetadataOrNull = [&](Attribute attr) -> llvm::Metadata * { |
| 509 | if (!attr) |
| 510 | return nullptr; |
| 511 | |
| 512 | llvm::Metadata *metadata = |
| 513 | llvm::TypeSwitch<Attribute, llvm::Metadata *>(attr) |
| 514 | .Case(caseFn: [&](LLVM::DIExpressionAttr expr) { |
| 515 | return translateExpression(attr: expr); |
| 516 | }) |
| 517 | .Case(caseFn: [&](LLVM::DILocalVariableAttr local) { |
| 518 | return translate(attr: local); |
| 519 | }) |
| 520 | .Case(caseFn: [&](LLVM::DIGlobalVariableAttr global) { |
| 521 | return translate(attr: global); |
| 522 | }) |
| 523 | .Default(nullptr); |
| 524 | return metadata; |
| 525 | }; |
| 526 | return llvm::DIGenericSubrange::get(Context&: llvmCtx, |
| 527 | CountNode: getMetadataOrNull(attr.getCount()), |
| 528 | LowerBound: getMetadataOrNull(attr.getLowerBound()), |
| 529 | UpperBound: getMetadataOrNull(attr.getUpperBound()), |
| 530 | Stride: getMetadataOrNull(attr.getStride())); |
| 531 | } |
| 532 | |
| 533 | llvm::DISubroutineType * |
| 534 | DebugTranslation::translateImpl(DISubroutineTypeAttr attr) { |
| 535 | // Concatenate the result and argument types into a single array. |
| 536 | SmallVector<llvm::Metadata *> types; |
| 537 | for (DITypeAttr type : attr.getTypes()) |
| 538 | types.push_back(Elt: translate(attr: type)); |
| 539 | return llvm::DISubroutineType::get( |
| 540 | Context&: llvmCtx, Flags: llvm::DINode::FlagZero, CC: attr.getCallingConvention(), |
| 541 | TypeArray: llvm::DITypeArray(llvm::MDNode::get(Context&: llvmCtx, MDs: types))); |
| 542 | } |
| 543 | |
| 544 | llvm::DIType *DebugTranslation::translateImpl(DITypeAttr attr) { |
| 545 | return cast<llvm::DIType>(Val: translate(attr: DINodeAttr(attr))); |
| 546 | } |
| 547 | |
| 548 | llvm::DINode *DebugTranslation::translate(DINodeAttr attr) { |
| 549 | if (!attr) |
| 550 | return nullptr; |
| 551 | // Check for a cached instance. |
| 552 | if (llvm::DINode *node = attrToNode.lookup(Val: attr)) |
| 553 | return node; |
| 554 | |
| 555 | llvm::DINode *node = nullptr; |
| 556 | // Recursive types go through a dedicated handler. All other types are |
| 557 | // dispatched directly to their specific handlers. |
| 558 | if (auto recTypeAttr = dyn_cast<DIRecursiveTypeAttrInterface>(Val&: attr)) |
| 559 | if (recTypeAttr.getRecId()) |
| 560 | node = translateRecursive(attr: recTypeAttr); |
| 561 | |
| 562 | if (!node) |
| 563 | node = TypeSwitch<DINodeAttr, llvm::DINode *>(attr) |
| 564 | .Case<DIBasicTypeAttr, DICommonBlockAttr, DICompileUnitAttr, |
| 565 | DICompositeTypeAttr, DIDerivedTypeAttr, DIEnumeratorAttr, |
| 566 | DIFileAttr, DIGenericSubrangeAttr, DIGlobalVariableAttr, |
| 567 | DIImportedEntityAttr, DILabelAttr, DILexicalBlockAttr, |
| 568 | DILexicalBlockFileAttr, DILocalVariableAttr, DIModuleAttr, |
| 569 | DINamespaceAttr, DINullTypeAttr, DIStringTypeAttr, |
| 570 | DISubprogramAttr, DISubrangeAttr, DISubroutineTypeAttr>( |
| 571 | caseFn: [&](auto attr) { return translateImpl(attr); }); |
| 572 | |
| 573 | if (node && !node->isTemporary()) |
| 574 | attrToNode.insert(KV: {attr, node}); |
| 575 | return node; |
| 576 | } |
| 577 | |
| 578 | //===----------------------------------------------------------------------===// |
| 579 | // Locations |
| 580 | //===----------------------------------------------------------------------===// |
| 581 | |
| 582 | /// Translate the given location to an llvm debug location. |
| 583 | llvm::DILocation *DebugTranslation::translateLoc(Location loc, |
| 584 | llvm::DILocalScope *scope) { |
| 585 | if (!debugEmissionIsEnabled) |
| 586 | return nullptr; |
| 587 | return translateLoc(loc, scope, /*inlinedAt=*/nullptr); |
| 588 | } |
| 589 | |
| 590 | llvm::DIExpression * |
| 591 | DebugTranslation::translateExpression(LLVM::DIExpressionAttr attr) { |
| 592 | SmallVector<uint64_t, 1> ops; |
| 593 | if (attr) { |
| 594 | // Append operations their operands to the list. |
| 595 | for (const DIExpressionElemAttr &op : attr.getOperations()) { |
| 596 | ops.push_back(Elt: op.getOpcode()); |
| 597 | append_range(C&: ops, R: op.getArguments()); |
| 598 | } |
| 599 | } |
| 600 | return llvm::DIExpression::get(Context&: llvmCtx, Elements: ops); |
| 601 | } |
| 602 | |
| 603 | llvm::DIGlobalVariableExpression * |
| 604 | DebugTranslation::translateGlobalVariableExpression( |
| 605 | LLVM::DIGlobalVariableExpressionAttr attr) { |
| 606 | return llvm::DIGlobalVariableExpression::get( |
| 607 | Context&: llvmCtx, Variable: translate(attr: attr.getVar()), Expression: translateExpression(attr: attr.getExpr())); |
| 608 | } |
| 609 | |
| 610 | /// Translate the given location to an llvm DebugLoc. |
| 611 | llvm::DILocation *DebugTranslation::translateLoc(Location loc, |
| 612 | llvm::DILocalScope *scope, |
| 613 | llvm::DILocation *inlinedAt) { |
| 614 | // LLVM doesn't have a representation for unknown. |
| 615 | if (isa<UnknownLoc>(Val: loc)) |
| 616 | return nullptr; |
| 617 | |
| 618 | // Check for a cached instance. |
| 619 | auto existingIt = locationToLoc.find(Val: std::make_tuple(args&: loc, args&: scope, args&: inlinedAt)); |
| 620 | if (existingIt != locationToLoc.end()) |
| 621 | return existingIt->second; |
| 622 | |
| 623 | llvm::DILocation *llvmLoc = nullptr; |
| 624 | if (auto callLoc = dyn_cast<CallSiteLoc>(Val&: loc)) { |
| 625 | // For callsites, the caller is fed as the inlinedAt for the callee. |
| 626 | auto *callerLoc = translateLoc(loc: callLoc.getCaller(), scope, inlinedAt); |
| 627 | // If the caller scope is not translatable, the overall callsite cannot be |
| 628 | // represented in LLVM (the callee scope may not match the parent function). |
| 629 | if (!callerLoc) { |
| 630 | // If there is an inlinedAt scope (an outer caller), skip to that |
| 631 | // directly. Otherwise, cannot translate. |
| 632 | if (!inlinedAt) |
| 633 | return nullptr; |
| 634 | callerLoc = inlinedAt; |
| 635 | } |
| 636 | llvmLoc = translateLoc(loc: callLoc.getCallee(), scope: nullptr, inlinedAt: callerLoc); |
| 637 | // Fallback: Ignore callee if it has no debug scope. |
| 638 | if (!llvmLoc) |
| 639 | llvmLoc = callerLoc; |
| 640 | |
| 641 | } else if (auto fileLoc = dyn_cast<FileLineColLoc>(Val&: loc)) { |
| 642 | // A scope of a DILocation cannot be null. |
| 643 | if (!scope) |
| 644 | return nullptr; |
| 645 | llvmLoc = |
| 646 | llvm::DILocation::get(Context&: llvmCtx, Line: fileLoc.getLine(), Column: fileLoc.getColumn(), |
| 647 | Scope: scope, InlinedAt: const_cast<llvm::DILocation *>(inlinedAt)); |
| 648 | |
| 649 | } else if (auto fusedLoc = dyn_cast<FusedLoc>(Val&: loc)) { |
| 650 | ArrayRef<Location> locations = fusedLoc.getLocations(); |
| 651 | |
| 652 | // Check for a scope encoded with the location. |
| 653 | if (auto scopedAttr = |
| 654 | dyn_cast_or_null<LLVM::DILocalScopeAttr>(Val: fusedLoc.getMetadata())) |
| 655 | scope = translate(attr: scopedAttr); |
| 656 | |
| 657 | // For fused locations, merge each of the nodes. |
| 658 | llvmLoc = translateLoc(loc: locations.front(), scope, inlinedAt); |
| 659 | for (Location locIt : locations.drop_front()) { |
| 660 | llvmLoc = llvm::DILocation::getMergedLocation( |
| 661 | LocA: llvmLoc, LocB: translateLoc(loc: locIt, scope, inlinedAt)); |
| 662 | } |
| 663 | |
| 664 | } else if (auto nameLoc = dyn_cast<NameLoc>(Val&: loc)) { |
| 665 | llvmLoc = translateLoc(loc: nameLoc.getChildLoc(), scope, inlinedAt); |
| 666 | |
| 667 | } else if (auto opaqueLoc = dyn_cast<OpaqueLoc>(Val&: loc)) { |
| 668 | llvmLoc = translateLoc(loc: opaqueLoc.getFallbackLocation(), scope, inlinedAt); |
| 669 | } else { |
| 670 | llvm_unreachable("unknown location kind" ); |
| 671 | } |
| 672 | |
| 673 | locationToLoc.try_emplace(Key: std::make_tuple(args&: loc, args&: scope, args&: inlinedAt), Args&: llvmLoc); |
| 674 | return llvmLoc; |
| 675 | } |
| 676 | |
| 677 | /// Create an llvm debug file for the given file path. |
| 678 | llvm::DIFile *DebugTranslation::translateFile(StringRef fileName) { |
| 679 | auto *&file = fileMap[fileName]; |
| 680 | if (file) |
| 681 | return file; |
| 682 | |
| 683 | // Make sure the current working directory is up-to-date. |
| 684 | if (currentWorkingDir.empty()) |
| 685 | llvm::sys::fs::current_path(result&: currentWorkingDir); |
| 686 | |
| 687 | StringRef directory = currentWorkingDir; |
| 688 | SmallString<128> dirBuf; |
| 689 | SmallString<128> fileBuf; |
| 690 | if (llvm::sys::path::is_absolute(path: fileName)) { |
| 691 | // Strip the common prefix (if it is more than just "/") from current |
| 692 | // directory and FileName for a more space-efficient encoding. |
| 693 | auto fileIt = llvm::sys::path::begin(path: fileName); |
| 694 | auto fileE = llvm::sys::path::end(path: fileName); |
| 695 | auto curDirIt = llvm::sys::path::begin(path: directory); |
| 696 | auto curDirE = llvm::sys::path::end(path: directory); |
| 697 | for (; curDirIt != curDirE && *curDirIt == *fileIt; ++curDirIt, ++fileIt) |
| 698 | llvm::sys::path::append(path&: dirBuf, a: *curDirIt); |
| 699 | if (std::distance(first: llvm::sys::path::begin(path: directory), last: curDirIt) == 1) { |
| 700 | // Don't strip the common prefix if it is only the root "/" since that |
| 701 | // would make LLVM diagnostic locations confusing. |
| 702 | directory = StringRef(); |
| 703 | } else { |
| 704 | for (; fileIt != fileE; ++fileIt) |
| 705 | llvm::sys::path::append(path&: fileBuf, a: *fileIt); |
| 706 | directory = dirBuf; |
| 707 | fileName = fileBuf; |
| 708 | } |
| 709 | } |
| 710 | return (file = llvm::DIFile::get(Context&: llvmCtx, Filename: fileName, Directory: directory)); |
| 711 | } |
| 712 | |