| 1 | //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===// |
| 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 | // This coordinates the debug information generation while generating code. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "CGDebugInfo.h" |
| 14 | #include "CGBlocks.h" |
| 15 | #include "CGCXXABI.h" |
| 16 | #include "CGObjCRuntime.h" |
| 17 | #include "CGRecordLayout.h" |
| 18 | #include "CodeGenFunction.h" |
| 19 | #include "CodeGenModule.h" |
| 20 | #include "ConstantEmitter.h" |
| 21 | #include "TargetInfo.h" |
| 22 | #include "clang/AST/ASTContext.h" |
| 23 | #include "clang/AST/Attr.h" |
| 24 | #include "clang/AST/DeclCXX.h" |
| 25 | #include "clang/AST/DeclFriend.h" |
| 26 | #include "clang/AST/DeclObjC.h" |
| 27 | #include "clang/AST/DeclTemplate.h" |
| 28 | #include "clang/AST/Expr.h" |
| 29 | #include "clang/AST/RecordLayout.h" |
| 30 | #include "clang/AST/RecursiveASTVisitor.h" |
| 31 | #include "clang/AST/VTableBuilder.h" |
| 32 | #include "clang/Basic/CodeGenOptions.h" |
| 33 | #include "clang/Basic/SourceManager.h" |
| 34 | #include "clang/Basic/Version.h" |
| 35 | #include "clang/CodeGen/ModuleBuilder.h" |
| 36 | #include "clang/Frontend/FrontendOptions.h" |
| 37 | #include "clang/Lex/HeaderSearchOptions.h" |
| 38 | #include "clang/Lex/ModuleMap.h" |
| 39 | #include "clang/Lex/PreprocessorOptions.h" |
| 40 | #include "llvm/ADT/DenseSet.h" |
| 41 | #include "llvm/ADT/SmallVector.h" |
| 42 | #include "llvm/ADT/StringExtras.h" |
| 43 | #include "llvm/IR/Constants.h" |
| 44 | #include "llvm/IR/DataLayout.h" |
| 45 | #include "llvm/IR/DerivedTypes.h" |
| 46 | #include "llvm/IR/Instruction.h" |
| 47 | #include "llvm/IR/Instructions.h" |
| 48 | #include "llvm/IR/Intrinsics.h" |
| 49 | #include "llvm/IR/Metadata.h" |
| 50 | #include "llvm/IR/Module.h" |
| 51 | #include "llvm/Support/MD5.h" |
| 52 | #include "llvm/Support/Path.h" |
| 53 | #include "llvm/Support/SHA1.h" |
| 54 | #include "llvm/Support/SHA256.h" |
| 55 | #include "llvm/Support/TimeProfiler.h" |
| 56 | #include <cstdint> |
| 57 | #include <optional> |
| 58 | using namespace clang; |
| 59 | using namespace clang::CodeGen; |
| 60 | |
| 61 | // TODO: consider deprecating ClArrayBoundsPseudoFn; functionality is subsumed |
| 62 | // by -fsanitize-annotate-debug-info |
| 63 | static llvm::cl::opt<bool> ClArrayBoundsPseudoFn( |
| 64 | "array-bounds-pseudofn" , llvm::cl::Hidden, llvm::cl::Optional, |
| 65 | llvm::cl::desc("Emit debug info that places array-bounds instrumentation " |
| 66 | "in an inline function called __ubsan_check_array_bounds." )); |
| 67 | |
| 68 | static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) { |
| 69 | auto TI = Ctx.getTypeInfo(T: Ty); |
| 70 | if (TI.isAlignRequired()) |
| 71 | return TI.Align; |
| 72 | |
| 73 | // MaxFieldAlignmentAttr is the attribute added to types |
| 74 | // declared after #pragma pack(n). |
| 75 | if (auto *Decl = Ty->getAsRecordDecl()) |
| 76 | if (Decl->hasAttr<MaxFieldAlignmentAttr>()) |
| 77 | return TI.Align; |
| 78 | |
| 79 | return 0; |
| 80 | } |
| 81 | |
| 82 | static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) { |
| 83 | return getTypeAlignIfRequired(Ty: Ty.getTypePtr(), Ctx); |
| 84 | } |
| 85 | |
| 86 | static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) { |
| 87 | return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0; |
| 88 | } |
| 89 | |
| 90 | /// Returns true if \ref VD is a a holding variable (aka a |
| 91 | /// VarDecl retrieved using \ref BindingDecl::getHoldingVar). |
| 92 | static bool IsDecomposedVarDecl(VarDecl const *VD) { |
| 93 | auto const *Init = VD->getInit(); |
| 94 | if (!Init) |
| 95 | return false; |
| 96 | |
| 97 | auto const *RefExpr = |
| 98 | llvm::dyn_cast_or_null<DeclRefExpr>(Val: Init->IgnoreUnlessSpelledInSource()); |
| 99 | if (!RefExpr) |
| 100 | return false; |
| 101 | |
| 102 | return llvm::dyn_cast_or_null<DecompositionDecl>(Val: RefExpr->getDecl()); |
| 103 | } |
| 104 | |
| 105 | /// Returns true if \ref VD is a compiler-generated variable |
| 106 | /// and should be treated as artificial for the purposes |
| 107 | /// of debug-info generation. |
| 108 | static bool IsArtificial(VarDecl const *VD) { |
| 109 | // Tuple-like bindings are marked as implicit despite |
| 110 | // being spelled out in source. Don't treat them as artificial |
| 111 | // variables. |
| 112 | if (IsDecomposedVarDecl(VD)) |
| 113 | return false; |
| 114 | |
| 115 | return VD->isImplicit() || (isa<Decl>(Val: VD->getDeclContext()) && |
| 116 | cast<Decl>(Val: VD->getDeclContext())->isImplicit()); |
| 117 | } |
| 118 | |
| 119 | CGDebugInfo::CGDebugInfo(CodeGenModule &CGM) |
| 120 | : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()), |
| 121 | DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs), |
| 122 | DBuilder(CGM.getModule()) { |
| 123 | CreateCompileUnit(); |
| 124 | } |
| 125 | |
| 126 | CGDebugInfo::~CGDebugInfo() { |
| 127 | assert(LexicalBlockStack.empty() && |
| 128 | "Region stack mismatch, stack not empty!" ); |
| 129 | } |
| 130 | |
| 131 | void CGDebugInfo::addInstSourceAtomMetadata(llvm::Instruction *I, |
| 132 | uint64_t Group, uint8_t Rank) { |
| 133 | if (!I->getDebugLoc() || Group == 0 || !I->getDebugLoc()->getLine()) |
| 134 | return; |
| 135 | |
| 136 | // Saturate the 3-bit rank. |
| 137 | Rank = std::min<uint8_t>(a: Rank, b: 7); |
| 138 | |
| 139 | const llvm::DebugLoc &DL = I->getDebugLoc(); |
| 140 | |
| 141 | // Each instruction can only be attributed to one source atom (a limitation of |
| 142 | // the implementation). If this instruction is already part of a source atom, |
| 143 | // pick the group in which it has highest precedence (lowest rank). |
| 144 | if (DL->getAtomGroup() && DL->getAtomRank() && DL->getAtomRank() < Rank) { |
| 145 | Group = DL->getAtomGroup(); |
| 146 | Rank = DL->getAtomRank(); |
| 147 | } |
| 148 | |
| 149 | // Update the function-local watermark so we don't reuse this number for |
| 150 | // another atom. |
| 151 | KeyInstructionsInfo.HighestEmittedAtom = |
| 152 | std::max(a: Group, b: KeyInstructionsInfo.HighestEmittedAtom); |
| 153 | |
| 154 | // Apply the new DILocation to the instruction. |
| 155 | llvm::DILocation *NewDL = llvm::DILocation::get( |
| 156 | Context&: I->getContext(), Line: DL.getLine(), Column: DL.getCol(), Scope: DL.getScope(), |
| 157 | InlinedAt: DL.getInlinedAt(), ImplicitCode: DL.isImplicitCode(), AtomGroup: Group, AtomRank: Rank); |
| 158 | I->setDebugLoc(NewDL); |
| 159 | } |
| 160 | |
| 161 | void CGDebugInfo::addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, |
| 162 | llvm::Value *Backup) { |
| 163 | addInstToSpecificSourceAtom(KeyInstruction, Backup, |
| 164 | Atom: KeyInstructionsInfo.CurrentAtom); |
| 165 | } |
| 166 | |
| 167 | void CGDebugInfo::addInstToSpecificSourceAtom(llvm::Instruction *KeyInstruction, |
| 168 | llvm::Value *Backup, |
| 169 | uint64_t Group) { |
| 170 | if (!Group || !CGM.getCodeGenOpts().DebugKeyInstructions) |
| 171 | return; |
| 172 | |
| 173 | addInstSourceAtomMetadata(I: KeyInstruction, Group, /*Rank=*/1); |
| 174 | |
| 175 | llvm::Instruction *BackupI = |
| 176 | llvm::dyn_cast_or_null<llvm::Instruction>(Val: Backup); |
| 177 | if (!BackupI) |
| 178 | return; |
| 179 | |
| 180 | // Add the backup instruction to the group. |
| 181 | addInstSourceAtomMetadata(I: BackupI, Group, /*Rank=*/2); |
| 182 | |
| 183 | // Look through chains of casts too, as they're probably going to evaporate. |
| 184 | // FIXME: And other nops like zero length geps? |
| 185 | // FIXME: Should use Cast->isNoopCast()? |
| 186 | uint8_t Rank = 3; |
| 187 | while (auto *Cast = dyn_cast<llvm::CastInst>(Val: BackupI)) { |
| 188 | BackupI = dyn_cast<llvm::Instruction>(Val: Cast->getOperand(i_nocapture: 0)); |
| 189 | if (!BackupI) |
| 190 | break; |
| 191 | addInstSourceAtomMetadata(I: BackupI, Group, Rank: Rank++); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | void CGDebugInfo::completeFunction() { |
| 196 | // Reset the atom group number tracker as the numbers are function-local. |
| 197 | KeyInstructionsInfo.NextAtom = 1; |
| 198 | KeyInstructionsInfo.HighestEmittedAtom = 0; |
| 199 | KeyInstructionsInfo.CurrentAtom = 0; |
| 200 | } |
| 201 | |
| 202 | ApplyAtomGroup::ApplyAtomGroup(CGDebugInfo *DI) : DI(DI) { |
| 203 | if (!DI) |
| 204 | return; |
| 205 | OriginalAtom = DI->KeyInstructionsInfo.CurrentAtom; |
| 206 | DI->KeyInstructionsInfo.CurrentAtom = DI->KeyInstructionsInfo.NextAtom++; |
| 207 | } |
| 208 | |
| 209 | ApplyAtomGroup::~ApplyAtomGroup() { |
| 210 | if (!DI) |
| 211 | return; |
| 212 | |
| 213 | // We may not have used the group number at all. |
| 214 | DI->KeyInstructionsInfo.NextAtom = |
| 215 | std::min(a: DI->KeyInstructionsInfo.HighestEmittedAtom + 1, |
| 216 | b: DI->KeyInstructionsInfo.NextAtom); |
| 217 | |
| 218 | DI->KeyInstructionsInfo.CurrentAtom = OriginalAtom; |
| 219 | } |
| 220 | |
| 221 | ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, |
| 222 | SourceLocation TemporaryLocation) |
| 223 | : CGF(&CGF) { |
| 224 | init(TemporaryLocation); |
| 225 | } |
| 226 | |
| 227 | ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, |
| 228 | bool DefaultToEmpty, |
| 229 | SourceLocation TemporaryLocation) |
| 230 | : CGF(&CGF) { |
| 231 | init(TemporaryLocation, DefaultToEmpty); |
| 232 | } |
| 233 | |
| 234 | void ApplyDebugLocation::init(SourceLocation TemporaryLocation, |
| 235 | bool DefaultToEmpty) { |
| 236 | auto *DI = CGF->getDebugInfo(); |
| 237 | if (!DI) { |
| 238 | CGF = nullptr; |
| 239 | return; |
| 240 | } |
| 241 | |
| 242 | OriginalLocation = CGF->Builder.getCurrentDebugLocation(); |
| 243 | |
| 244 | if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled()) |
| 245 | return; |
| 246 | |
| 247 | if (TemporaryLocation.isValid()) { |
| 248 | DI->EmitLocation(Builder&: CGF->Builder, Loc: TemporaryLocation); |
| 249 | return; |
| 250 | } |
| 251 | |
| 252 | if (DefaultToEmpty) { |
| 253 | CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc()); |
| 254 | return; |
| 255 | } |
| 256 | |
| 257 | // Construct a location that has a valid scope, but no line info. |
| 258 | assert(!DI->LexicalBlockStack.empty()); |
| 259 | CGF->Builder.SetCurrentDebugLocation( |
| 260 | llvm::DILocation::get(Context&: DI->LexicalBlockStack.back()->getContext(), Line: 0, Column: 0, |
| 261 | Scope: DI->LexicalBlockStack.back(), InlinedAt: DI->getInlinedAt())); |
| 262 | } |
| 263 | |
| 264 | ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E) |
| 265 | : CGF(&CGF) { |
| 266 | init(TemporaryLocation: E->getExprLoc()); |
| 267 | } |
| 268 | |
| 269 | ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc) |
| 270 | : CGF(&CGF) { |
| 271 | if (!CGF.getDebugInfo()) { |
| 272 | this->CGF = nullptr; |
| 273 | return; |
| 274 | } |
| 275 | OriginalLocation = CGF.Builder.getCurrentDebugLocation(); |
| 276 | if (Loc) { |
| 277 | // Key Instructions: drop the atom group and rank to avoid accidentally |
| 278 | // propagating it around. |
| 279 | if (Loc->getAtomGroup()) |
| 280 | Loc = llvm::DILocation::get(Context&: Loc->getContext(), Line: Loc.getLine(), |
| 281 | Column: Loc->getColumn(), Scope: Loc->getScope(), |
| 282 | InlinedAt: Loc->getInlinedAt(), ImplicitCode: Loc.isImplicitCode()); |
| 283 | CGF.Builder.SetCurrentDebugLocation(std::move(Loc)); |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | ApplyDebugLocation::~ApplyDebugLocation() { |
| 288 | // Query CGF so the location isn't overwritten when location updates are |
| 289 | // temporarily disabled (for C++ default function arguments) |
| 290 | if (CGF) |
| 291 | CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation)); |
| 292 | } |
| 293 | |
| 294 | ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF, |
| 295 | GlobalDecl InlinedFn) |
| 296 | : CGF(&CGF) { |
| 297 | if (!CGF.getDebugInfo()) { |
| 298 | this->CGF = nullptr; |
| 299 | return; |
| 300 | } |
| 301 | auto &DI = *CGF.getDebugInfo(); |
| 302 | SavedLocation = DI.getLocation(); |
| 303 | assert((DI.getInlinedAt() == |
| 304 | CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) && |
| 305 | "CGDebugInfo and IRBuilder are out of sync" ); |
| 306 | |
| 307 | DI.EmitInlineFunctionStart(Builder&: CGF.Builder, GD: InlinedFn); |
| 308 | } |
| 309 | |
| 310 | ApplyInlineDebugLocation::~ApplyInlineDebugLocation() { |
| 311 | if (!CGF) |
| 312 | return; |
| 313 | auto &DI = *CGF->getDebugInfo(); |
| 314 | DI.EmitInlineFunctionEnd(Builder&: CGF->Builder); |
| 315 | DI.EmitLocation(Builder&: CGF->Builder, Loc: SavedLocation); |
| 316 | } |
| 317 | |
| 318 | void CGDebugInfo::setLocation(SourceLocation Loc) { |
| 319 | // If the new location isn't valid return. |
| 320 | if (Loc.isInvalid()) |
| 321 | return; |
| 322 | |
| 323 | CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc); |
| 324 | |
| 325 | // If we've changed files in the middle of a lexical scope go ahead |
| 326 | // and create a new lexical scope with file node if it's different |
| 327 | // from the one in the scope. |
| 328 | if (LexicalBlockStack.empty()) |
| 329 | return; |
| 330 | |
| 331 | SourceManager &SM = CGM.getContext().getSourceManager(); |
| 332 | auto *Scope = cast<llvm::DIScope>(Val&: LexicalBlockStack.back()); |
| 333 | PresumedLoc PCLoc = SM.getPresumedLoc(Loc: CurLoc); |
| 334 | if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(Loc: CurLoc)) |
| 335 | return; |
| 336 | |
| 337 | if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Val: Scope)) { |
| 338 | LexicalBlockStack.pop_back(); |
| 339 | LexicalBlockStack.emplace_back(args: DBuilder.createLexicalBlockFile( |
| 340 | Scope: LBF->getScope(), File: getOrCreateFile(Loc: CurLoc))); |
| 341 | } else if (isa<llvm::DILexicalBlock>(Val: Scope) || |
| 342 | isa<llvm::DISubprogram>(Val: Scope)) { |
| 343 | LexicalBlockStack.pop_back(); |
| 344 | LexicalBlockStack.emplace_back( |
| 345 | args: DBuilder.createLexicalBlockFile(Scope, File: getOrCreateFile(Loc: CurLoc))); |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) { |
| 350 | llvm::DIScope *Mod = getParentModuleOrNull(D); |
| 351 | return getContextDescriptor(Context: cast<Decl>(Val: D->getDeclContext()), |
| 352 | Default: Mod ? Mod : TheCU); |
| 353 | } |
| 354 | |
| 355 | llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context, |
| 356 | llvm::DIScope *Default) { |
| 357 | if (!Context) |
| 358 | return Default; |
| 359 | |
| 360 | auto I = RegionMap.find(Val: Context); |
| 361 | if (I != RegionMap.end()) { |
| 362 | llvm::Metadata *V = I->second; |
| 363 | return dyn_cast_or_null<llvm::DIScope>(Val: V); |
| 364 | } |
| 365 | |
| 366 | // Check namespace. |
| 367 | if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Val: Context)) |
| 368 | return getOrCreateNamespace(N: NSDecl); |
| 369 | |
| 370 | if (const auto *RDecl = dyn_cast<RecordDecl>(Val: Context)) |
| 371 | if (!RDecl->isDependentType()) |
| 372 | return getOrCreateType(Ty: CGM.getContext().getTypeDeclType(Decl: RDecl), |
| 373 | Fg: TheCU->getFile()); |
| 374 | return Default; |
| 375 | } |
| 376 | |
| 377 | PrintingPolicy CGDebugInfo::getPrintingPolicy() const { |
| 378 | PrintingPolicy PP = CGM.getContext().getPrintingPolicy(); |
| 379 | |
| 380 | // If we're emitting codeview, it's important to try to match MSVC's naming so |
| 381 | // that visualizers written for MSVC will trigger for our class names. In |
| 382 | // particular, we can't have spaces between arguments of standard templates |
| 383 | // like basic_string and vector, but we must have spaces between consecutive |
| 384 | // angle brackets that close nested template argument lists. |
| 385 | if (CGM.getCodeGenOpts().EmitCodeView) { |
| 386 | PP.MSVCFormatting = true; |
| 387 | PP.SplitTemplateClosers = true; |
| 388 | } else { |
| 389 | // For DWARF, printing rules are underspecified. |
| 390 | // SplitTemplateClosers yields better interop with GCC and GDB (PR46052). |
| 391 | PP.SplitTemplateClosers = true; |
| 392 | } |
| 393 | |
| 394 | PP.SuppressInlineNamespace = |
| 395 | PrintingPolicy::SuppressInlineNamespaceMode::None; |
| 396 | PP.PrintAsCanonical = true; |
| 397 | PP.UsePreferredNames = false; |
| 398 | PP.AlwaysIncludeTypeForTemplateArgument = true; |
| 399 | PP.UseEnumerators = false; |
| 400 | |
| 401 | // Apply -fdebug-prefix-map. |
| 402 | PP.Callbacks = &PrintCB; |
| 403 | return PP; |
| 404 | } |
| 405 | |
| 406 | StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) { |
| 407 | return internString(A: GetName(FD)); |
| 408 | } |
| 409 | |
| 410 | StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) { |
| 411 | SmallString<256> MethodName; |
| 412 | llvm::raw_svector_ostream OS(MethodName); |
| 413 | OS << (OMD->isInstanceMethod() ? '-' : '+') << '['; |
| 414 | const DeclContext *DC = OMD->getDeclContext(); |
| 415 | if (const auto *OID = dyn_cast<ObjCImplementationDecl>(Val: DC)) { |
| 416 | OS << OID->getName(); |
| 417 | } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(Val: DC)) { |
| 418 | OS << OID->getName(); |
| 419 | } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(Val: DC)) { |
| 420 | if (OC->IsClassExtension()) { |
| 421 | OS << OC->getClassInterface()->getName(); |
| 422 | } else { |
| 423 | OS << OC->getIdentifier()->getNameStart() << '(' |
| 424 | << OC->getIdentifier()->getNameStart() << ')'; |
| 425 | } |
| 426 | } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(Val: DC)) { |
| 427 | OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')'; |
| 428 | } |
| 429 | OS << ' ' << OMD->getSelector().getAsString() << ']'; |
| 430 | |
| 431 | return internString(A: OS.str()); |
| 432 | } |
| 433 | |
| 434 | StringRef CGDebugInfo::getSelectorName(Selector S) { |
| 435 | return internString(A: S.getAsString()); |
| 436 | } |
| 437 | |
| 438 | StringRef CGDebugInfo::getClassName(const RecordDecl *RD) { |
| 439 | if (isa<ClassTemplateSpecializationDecl>(Val: RD)) { |
| 440 | // Copy this name on the side and use its reference. |
| 441 | return internString(A: GetName(RD)); |
| 442 | } |
| 443 | |
| 444 | // quick optimization to avoid having to intern strings that are already |
| 445 | // stored reliably elsewhere |
| 446 | if (const IdentifierInfo *II = RD->getIdentifier()) |
| 447 | return II->getName(); |
| 448 | |
| 449 | // The CodeView printer in LLVM wants to see the names of unnamed types |
| 450 | // because they need to have a unique identifier. |
| 451 | // These names are used to reconstruct the fully qualified type names. |
| 452 | if (CGM.getCodeGenOpts().EmitCodeView) { |
| 453 | if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) { |
| 454 | assert(RD->getDeclContext() == D->getDeclContext() && |
| 455 | "Typedef should not be in another decl context!" ); |
| 456 | assert(D->getDeclName().getAsIdentifierInfo() && |
| 457 | "Typedef was not named!" ); |
| 458 | return D->getDeclName().getAsIdentifierInfo()->getName(); |
| 459 | } |
| 460 | |
| 461 | if (CGM.getLangOpts().CPlusPlus) { |
| 462 | StringRef Name; |
| 463 | |
| 464 | ASTContext &Context = CGM.getContext(); |
| 465 | if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(TD: RD)) |
| 466 | // Anonymous types without a name for linkage purposes have their |
| 467 | // declarator mangled in if they have one. |
| 468 | Name = DD->getName(); |
| 469 | else if (const TypedefNameDecl *TND = |
| 470 | Context.getTypedefNameForUnnamedTagDecl(TD: RD)) |
| 471 | // Anonymous types without a name for linkage purposes have their |
| 472 | // associate typedef mangled in if they have one. |
| 473 | Name = TND->getName(); |
| 474 | |
| 475 | // Give lambdas a display name based on their name mangling. |
| 476 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
| 477 | if (CXXRD->isLambda()) |
| 478 | return internString( |
| 479 | A: CGM.getCXXABI().getMangleContext().getLambdaString(Lambda: CXXRD)); |
| 480 | |
| 481 | if (!Name.empty()) { |
| 482 | SmallString<256> UnnamedType("<unnamed-type-" ); |
| 483 | UnnamedType += Name; |
| 484 | UnnamedType += '>'; |
| 485 | return internString(A: UnnamedType); |
| 486 | } |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | return StringRef(); |
| 491 | } |
| 492 | |
| 493 | std::optional<llvm::DIFile::ChecksumKind> |
| 494 | CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const { |
| 495 | Checksum.clear(); |
| 496 | |
| 497 | if (!CGM.getCodeGenOpts().EmitCodeView && |
| 498 | CGM.getCodeGenOpts().DwarfVersion < 5) |
| 499 | return std::nullopt; |
| 500 | |
| 501 | SourceManager &SM = CGM.getContext().getSourceManager(); |
| 502 | std::optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID); |
| 503 | if (!MemBuffer) |
| 504 | return std::nullopt; |
| 505 | |
| 506 | auto Data = llvm::arrayRefFromStringRef(Input: MemBuffer->getBuffer()); |
| 507 | switch (CGM.getCodeGenOpts().getDebugSrcHash()) { |
| 508 | case clang::CodeGenOptions::DSH_MD5: |
| 509 | llvm::toHex(Input: llvm::MD5::hash(Data), /*LowerCase=*/true, Output&: Checksum); |
| 510 | return llvm::DIFile::CSK_MD5; |
| 511 | case clang::CodeGenOptions::DSH_SHA1: |
| 512 | llvm::toHex(Input: llvm::SHA1::hash(Data), /*LowerCase=*/true, Output&: Checksum); |
| 513 | return llvm::DIFile::CSK_SHA1; |
| 514 | case clang::CodeGenOptions::DSH_SHA256: |
| 515 | llvm::toHex(Input: llvm::SHA256::hash(Data), /*LowerCase=*/true, Output&: Checksum); |
| 516 | return llvm::DIFile::CSK_SHA256; |
| 517 | } |
| 518 | llvm_unreachable("Unhandled DebugSrcHashKind enum" ); |
| 519 | } |
| 520 | |
| 521 | std::optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM, |
| 522 | FileID FID) { |
| 523 | if (!CGM.getCodeGenOpts().EmbedSource) |
| 524 | return std::nullopt; |
| 525 | |
| 526 | bool SourceInvalid = false; |
| 527 | StringRef Source = SM.getBufferData(FID, Invalid: &SourceInvalid); |
| 528 | |
| 529 | if (SourceInvalid) |
| 530 | return std::nullopt; |
| 531 | |
| 532 | return Source; |
| 533 | } |
| 534 | |
| 535 | llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) { |
| 536 | SourceManager &SM = CGM.getContext().getSourceManager(); |
| 537 | StringRef FileName; |
| 538 | FileID FID; |
| 539 | std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo; |
| 540 | |
| 541 | if (Loc.isInvalid()) { |
| 542 | // The DIFile used by the CU is distinct from the main source file. Call |
| 543 | // createFile() below for canonicalization if the source file was specified |
| 544 | // with an absolute path. |
| 545 | FileName = TheCU->getFile()->getFilename(); |
| 546 | CSInfo = TheCU->getFile()->getChecksum(); |
| 547 | } else { |
| 548 | PresumedLoc PLoc = SM.getPresumedLoc(Loc); |
| 549 | FileName = PLoc.getFilename(); |
| 550 | |
| 551 | if (FileName.empty()) { |
| 552 | FileName = TheCU->getFile()->getFilename(); |
| 553 | } else { |
| 554 | FileName = PLoc.getFilename(); |
| 555 | } |
| 556 | FID = PLoc.getFileID(); |
| 557 | } |
| 558 | |
| 559 | // Cache the results. |
| 560 | auto It = DIFileCache.find(Val: FileName.data()); |
| 561 | if (It != DIFileCache.end()) { |
| 562 | // Verify that the information still exists. |
| 563 | if (llvm::Metadata *V = It->second) |
| 564 | return cast<llvm::DIFile>(Val: V); |
| 565 | } |
| 566 | |
| 567 | // Put Checksum at a scope where it will persist past the createFile call. |
| 568 | SmallString<64> Checksum; |
| 569 | if (!CSInfo) { |
| 570 | std::optional<llvm::DIFile::ChecksumKind> CSKind = |
| 571 | computeChecksum(FID, Checksum); |
| 572 | if (CSKind) |
| 573 | CSInfo.emplace(args&: *CSKind, args&: Checksum); |
| 574 | } |
| 575 | return createFile(FileName, CSInfo, Source: getSource(SM, FID: SM.getFileID(SpellingLoc: Loc))); |
| 576 | } |
| 577 | |
| 578 | llvm::DIFile *CGDebugInfo::createFile( |
| 579 | StringRef FileName, |
| 580 | std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo, |
| 581 | std::optional<StringRef> Source) { |
| 582 | StringRef Dir; |
| 583 | StringRef File; |
| 584 | std::string RemappedFile = remapDIPath(FileName); |
| 585 | std::string CurDir = remapDIPath(getCurrentDirname()); |
| 586 | SmallString<128> DirBuf; |
| 587 | SmallString<128> FileBuf; |
| 588 | if (llvm::sys::path::is_absolute(path: RemappedFile)) { |
| 589 | // Strip the common prefix (if it is more than just "/" or "C:\") from |
| 590 | // current directory and FileName for a more space-efficient encoding. |
| 591 | auto FileIt = llvm::sys::path::begin(path: RemappedFile); |
| 592 | auto FileE = llvm::sys::path::end(path: RemappedFile); |
| 593 | auto CurDirIt = llvm::sys::path::begin(path: CurDir); |
| 594 | auto CurDirE = llvm::sys::path::end(path: CurDir); |
| 595 | for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt) |
| 596 | llvm::sys::path::append(path&: DirBuf, a: *CurDirIt); |
| 597 | if (llvm::sys::path::root_path(path: DirBuf) == DirBuf) { |
| 598 | // Don't strip the common prefix if it is only the root ("/" or "C:\") |
| 599 | // since that would make LLVM diagnostic locations confusing. |
| 600 | Dir = {}; |
| 601 | File = RemappedFile; |
| 602 | } else { |
| 603 | for (; FileIt != FileE; ++FileIt) |
| 604 | llvm::sys::path::append(path&: FileBuf, a: *FileIt); |
| 605 | Dir = DirBuf; |
| 606 | File = FileBuf; |
| 607 | } |
| 608 | } else { |
| 609 | if (!llvm::sys::path::is_absolute(path: FileName)) |
| 610 | Dir = CurDir; |
| 611 | File = RemappedFile; |
| 612 | } |
| 613 | llvm::DIFile *F = DBuilder.createFile(Filename: File, Directory: Dir, Checksum: CSInfo, Source); |
| 614 | DIFileCache[FileName.data()].reset(MD: F); |
| 615 | return F; |
| 616 | } |
| 617 | |
| 618 | std::string CGDebugInfo::remapDIPath(StringRef Path) const { |
| 619 | SmallString<256> P = Path; |
| 620 | for (auto &[From, To] : llvm::reverse(C: CGM.getCodeGenOpts().DebugPrefixMap)) |
| 621 | if (llvm::sys::path::replace_path_prefix(Path&: P, OldPrefix: From, NewPrefix: To)) |
| 622 | break; |
| 623 | return P.str().str(); |
| 624 | } |
| 625 | |
| 626 | unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) { |
| 627 | if (Loc.isInvalid()) |
| 628 | return 0; |
| 629 | SourceManager &SM = CGM.getContext().getSourceManager(); |
| 630 | return SM.getPresumedLoc(Loc).getLine(); |
| 631 | } |
| 632 | |
| 633 | unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) { |
| 634 | // We may not want column information at all. |
| 635 | if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo) |
| 636 | return 0; |
| 637 | |
| 638 | // If the location is invalid then use the current column. |
| 639 | if (Loc.isInvalid() && CurLoc.isInvalid()) |
| 640 | return 0; |
| 641 | SourceManager &SM = CGM.getContext().getSourceManager(); |
| 642 | PresumedLoc PLoc = SM.getPresumedLoc(Loc: Loc.isValid() ? Loc : CurLoc); |
| 643 | return PLoc.isValid() ? PLoc.getColumn() : 0; |
| 644 | } |
| 645 | |
| 646 | StringRef CGDebugInfo::getCurrentDirname() { |
| 647 | if (!CGM.getCodeGenOpts().DebugCompilationDir.empty()) |
| 648 | return CGM.getCodeGenOpts().DebugCompilationDir; |
| 649 | |
| 650 | if (!CWDName.empty()) |
| 651 | return CWDName; |
| 652 | llvm::ErrorOr<std::string> CWD = |
| 653 | CGM.getFileSystem()->getCurrentWorkingDirectory(); |
| 654 | if (!CWD) |
| 655 | return StringRef(); |
| 656 | return CWDName = internString(A: *CWD); |
| 657 | } |
| 658 | |
| 659 | void CGDebugInfo::CreateCompileUnit() { |
| 660 | SmallString<64> Checksum; |
| 661 | std::optional<llvm::DIFile::ChecksumKind> CSKind; |
| 662 | std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo; |
| 663 | |
| 664 | // Should we be asking the SourceManager for the main file name, instead of |
| 665 | // accepting it as an argument? This just causes the main file name to |
| 666 | // mismatch with source locations and create extra lexical scopes or |
| 667 | // mismatched debug info (a CU with a DW_AT_file of "-", because that's what |
| 668 | // the driver passed, but functions/other things have DW_AT_file of "<stdin>" |
| 669 | // because that's what the SourceManager says) |
| 670 | |
| 671 | // Get absolute path name. |
| 672 | SourceManager &SM = CGM.getContext().getSourceManager(); |
| 673 | auto &CGO = CGM.getCodeGenOpts(); |
| 674 | const LangOptions &LO = CGM.getLangOpts(); |
| 675 | std::string MainFileName = CGO.MainFileName; |
| 676 | if (MainFileName.empty()) |
| 677 | MainFileName = "<stdin>" ; |
| 678 | |
| 679 | // The main file name provided via the "-main-file-name" option contains just |
| 680 | // the file name itself with no path information. This file name may have had |
| 681 | // a relative path, so we look into the actual file entry for the main |
| 682 | // file to determine the real absolute path for the file. |
| 683 | std::string MainFileDir; |
| 684 | if (OptionalFileEntryRef MainFile = |
| 685 | SM.getFileEntryRefForID(FID: SM.getMainFileID())) { |
| 686 | MainFileDir = std::string(MainFile->getDir().getName()); |
| 687 | if (!llvm::sys::path::is_absolute(path: MainFileName)) { |
| 688 | llvm::SmallString<1024> MainFileDirSS(MainFileDir); |
| 689 | llvm::sys::path::Style Style = |
| 690 | LO.UseTargetPathSeparator |
| 691 | ? (CGM.getTarget().getTriple().isOSWindows() |
| 692 | ? llvm::sys::path::Style::windows_backslash |
| 693 | : llvm::sys::path::Style::posix) |
| 694 | : llvm::sys::path::Style::native; |
| 695 | llvm::sys::path::append(path&: MainFileDirSS, style: Style, a: MainFileName); |
| 696 | MainFileName = std::string( |
| 697 | llvm::sys::path::remove_leading_dotslash(path: MainFileDirSS, style: Style)); |
| 698 | } |
| 699 | // If the main file name provided is identical to the input file name, and |
| 700 | // if the input file is a preprocessed source, use the module name for |
| 701 | // debug info. The module name comes from the name specified in the first |
| 702 | // linemarker if the input is a preprocessed source. In this case we don't |
| 703 | // know the content to compute a checksum. |
| 704 | if (MainFile->getName() == MainFileName && |
| 705 | FrontendOptions::getInputKindForExtension( |
| 706 | Extension: MainFile->getName().rsplit(Separator: '.').second) |
| 707 | .isPreprocessed()) { |
| 708 | MainFileName = CGM.getModule().getName().str(); |
| 709 | } else { |
| 710 | CSKind = computeChecksum(FID: SM.getMainFileID(), Checksum); |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | llvm::dwarf::SourceLanguage LangTag; |
| 715 | if (LO.CPlusPlus) { |
| 716 | if (LO.ObjC) |
| 717 | LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus; |
| 718 | else if (CGO.DebugStrictDwarf && CGO.DwarfVersion < 5) |
| 719 | LangTag = llvm::dwarf::DW_LANG_C_plus_plus; |
| 720 | else if (LO.CPlusPlus14) |
| 721 | LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14; |
| 722 | else if (LO.CPlusPlus11) |
| 723 | LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11; |
| 724 | else |
| 725 | LangTag = llvm::dwarf::DW_LANG_C_plus_plus; |
| 726 | } else if (LO.ObjC) { |
| 727 | LangTag = llvm::dwarf::DW_LANG_ObjC; |
| 728 | } else if (LO.OpenCL && (!CGM.getCodeGenOpts().DebugStrictDwarf || |
| 729 | CGM.getCodeGenOpts().DwarfVersion >= 5)) { |
| 730 | LangTag = llvm::dwarf::DW_LANG_OpenCL; |
| 731 | } else if (LO.C11 && !(CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)) { |
| 732 | LangTag = llvm::dwarf::DW_LANG_C11; |
| 733 | } else if (LO.C99) { |
| 734 | LangTag = llvm::dwarf::DW_LANG_C99; |
| 735 | } else { |
| 736 | LangTag = llvm::dwarf::DW_LANG_C89; |
| 737 | } |
| 738 | |
| 739 | std::string Producer = getClangFullVersion(); |
| 740 | |
| 741 | // Figure out which version of the ObjC runtime we have. |
| 742 | unsigned RuntimeVers = 0; |
| 743 | if (LO.ObjC) |
| 744 | RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1; |
| 745 | |
| 746 | llvm::DICompileUnit::DebugEmissionKind EmissionKind; |
| 747 | switch (DebugKind) { |
| 748 | case llvm::codegenoptions::NoDebugInfo: |
| 749 | case llvm::codegenoptions::LocTrackingOnly: |
| 750 | EmissionKind = llvm::DICompileUnit::NoDebug; |
| 751 | break; |
| 752 | case llvm::codegenoptions::DebugLineTablesOnly: |
| 753 | EmissionKind = llvm::DICompileUnit::LineTablesOnly; |
| 754 | break; |
| 755 | case llvm::codegenoptions::DebugDirectivesOnly: |
| 756 | EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly; |
| 757 | break; |
| 758 | case llvm::codegenoptions::DebugInfoConstructor: |
| 759 | case llvm::codegenoptions::LimitedDebugInfo: |
| 760 | case llvm::codegenoptions::FullDebugInfo: |
| 761 | case llvm::codegenoptions::UnusedTypeInfo: |
| 762 | EmissionKind = llvm::DICompileUnit::FullDebug; |
| 763 | break; |
| 764 | } |
| 765 | |
| 766 | uint64_t DwoId = 0; |
| 767 | auto &CGOpts = CGM.getCodeGenOpts(); |
| 768 | // The DIFile used by the CU is distinct from the main source |
| 769 | // file. Its directory part specifies what becomes the |
| 770 | // DW_AT_comp_dir (the compilation directory), even if the source |
| 771 | // file was specified with an absolute path. |
| 772 | if (CSKind) |
| 773 | CSInfo.emplace(args&: *CSKind, args&: Checksum); |
| 774 | llvm::DIFile *CUFile = DBuilder.createFile( |
| 775 | Filename: remapDIPath(Path: MainFileName), Directory: remapDIPath(Path: getCurrentDirname()), Checksum: CSInfo, |
| 776 | Source: getSource(SM, FID: SM.getMainFileID())); |
| 777 | |
| 778 | StringRef Sysroot, SDK; |
| 779 | if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) { |
| 780 | Sysroot = CGM.getHeaderSearchOpts().Sysroot; |
| 781 | auto B = llvm::sys::path::rbegin(path: Sysroot); |
| 782 | auto E = llvm::sys::path::rend(path: Sysroot); |
| 783 | auto It = |
| 784 | std::find_if(first: B, last: E, pred: [](auto SDK) { return SDK.ends_with(".sdk" ); }); |
| 785 | if (It != E) |
| 786 | SDK = *It; |
| 787 | } |
| 788 | |
| 789 | llvm::DICompileUnit::DebugNameTableKind NameTableKind = |
| 790 | static_cast<llvm::DICompileUnit::DebugNameTableKind>( |
| 791 | CGOpts.DebugNameTable); |
| 792 | if (CGM.getTarget().getTriple().isNVPTX()) |
| 793 | NameTableKind = llvm::DICompileUnit::DebugNameTableKind::None; |
| 794 | else if (CGM.getTarget().getTriple().getVendor() == llvm::Triple::Apple) |
| 795 | NameTableKind = llvm::DICompileUnit::DebugNameTableKind::Apple; |
| 796 | |
| 797 | // Create new compile unit. |
| 798 | TheCU = DBuilder.createCompileUnit( |
| 799 | Lang: LangTag, File: CUFile, Producer: CGOpts.EmitVersionIdentMetadata ? Producer : "" , |
| 800 | isOptimized: LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO, |
| 801 | Flags: CGOpts.DwarfDebugFlags, RV: RuntimeVers, SplitName: CGOpts.SplitDwarfFile, Kind: EmissionKind, |
| 802 | DWOId: DwoId, SplitDebugInlining: CGOpts.SplitDwarfInlining, DebugInfoForProfiling: CGOpts.DebugInfoForProfiling, |
| 803 | NameTableKind, RangesBaseAddress: CGOpts.DebugRangesBaseAddress, SysRoot: remapDIPath(Path: Sysroot), SDK); |
| 804 | } |
| 805 | |
| 806 | llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) { |
| 807 | llvm::dwarf::TypeKind Encoding; |
| 808 | StringRef BTName; |
| 809 | switch (BT->getKind()) { |
| 810 | #define BUILTIN_TYPE(Id, SingletonId) |
| 811 | #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: |
| 812 | #include "clang/AST/BuiltinTypes.def" |
| 813 | case BuiltinType::Dependent: |
| 814 | llvm_unreachable("Unexpected builtin type" ); |
| 815 | case BuiltinType::NullPtr: |
| 816 | return DBuilder.createNullPtrType(); |
| 817 | case BuiltinType::Void: |
| 818 | return nullptr; |
| 819 | case BuiltinType::ObjCClass: |
| 820 | if (!ClassTy) |
| 821 | ClassTy = |
| 822 | DBuilder.createForwardDecl(Tag: llvm::dwarf::DW_TAG_structure_type, |
| 823 | Name: "objc_class" , Scope: TheCU, F: TheCU->getFile(), Line: 0); |
| 824 | return ClassTy; |
| 825 | case BuiltinType::ObjCId: { |
| 826 | // typedef struct objc_class *Class; |
| 827 | // typedef struct objc_object { |
| 828 | // Class isa; |
| 829 | // } *id; |
| 830 | |
| 831 | if (ObjTy) |
| 832 | return ObjTy; |
| 833 | |
| 834 | if (!ClassTy) |
| 835 | ClassTy = |
| 836 | DBuilder.createForwardDecl(Tag: llvm::dwarf::DW_TAG_structure_type, |
| 837 | Name: "objc_class" , Scope: TheCU, F: TheCU->getFile(), Line: 0); |
| 838 | |
| 839 | unsigned Size = CGM.getContext().getTypeSize(T: CGM.getContext().VoidPtrTy); |
| 840 | |
| 841 | auto *ISATy = DBuilder.createPointerType(PointeeTy: ClassTy, SizeInBits: Size); |
| 842 | |
| 843 | ObjTy = DBuilder.createStructType(Scope: TheCU, Name: "objc_object" , File: TheCU->getFile(), LineNumber: 0, |
| 844 | SizeInBits: (uint64_t)0, AlignInBits: 0, Flags: llvm::DINode::FlagZero, |
| 845 | DerivedFrom: nullptr, Elements: llvm::DINodeArray()); |
| 846 | |
| 847 | DBuilder.replaceArrays( |
| 848 | T&: ObjTy, Elements: DBuilder.getOrCreateArray(Elements: &*DBuilder.createMemberType( |
| 849 | Scope: ObjTy, Name: "isa" , File: TheCU->getFile(), LineNo: 0, SizeInBits: Size, AlignInBits: 0, OffsetInBits: 0, |
| 850 | Flags: llvm::DINode::FlagZero, Ty: ISATy))); |
| 851 | return ObjTy; |
| 852 | } |
| 853 | case BuiltinType::ObjCSel: { |
| 854 | if (!SelTy) |
| 855 | SelTy = DBuilder.createForwardDecl(Tag: llvm::dwarf::DW_TAG_structure_type, |
| 856 | Name: "objc_selector" , Scope: TheCU, |
| 857 | F: TheCU->getFile(), Line: 0); |
| 858 | return SelTy; |
| 859 | } |
| 860 | |
| 861 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
| 862 | case BuiltinType::Id: \ |
| 863 | return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \ |
| 864 | SingletonId); |
| 865 | #include "clang/Basic/OpenCLImageTypes.def" |
| 866 | case BuiltinType::OCLSampler: |
| 867 | return getOrCreateStructPtrType(Name: "opencl_sampler_t" , Cache&: OCLSamplerDITy); |
| 868 | case BuiltinType::OCLEvent: |
| 869 | return getOrCreateStructPtrType(Name: "opencl_event_t" , Cache&: OCLEventDITy); |
| 870 | case BuiltinType::OCLClkEvent: |
| 871 | return getOrCreateStructPtrType(Name: "opencl_clk_event_t" , Cache&: OCLClkEventDITy); |
| 872 | case BuiltinType::OCLQueue: |
| 873 | return getOrCreateStructPtrType(Name: "opencl_queue_t" , Cache&: OCLQueueDITy); |
| 874 | case BuiltinType::OCLReserveID: |
| 875 | return getOrCreateStructPtrType(Name: "opencl_reserve_id_t" , Cache&: OCLReserveIDDITy); |
| 876 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
| 877 | case BuiltinType::Id: \ |
| 878 | return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty); |
| 879 | #include "clang/Basic/OpenCLExtensionTypes.def" |
| 880 | #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \ |
| 881 | case BuiltinType::Id: \ |
| 882 | return getOrCreateStructPtrType(#Name, SingletonId); |
| 883 | #include "clang/Basic/HLSLIntangibleTypes.def" |
| 884 | |
| 885 | #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 886 | #include "clang/Basic/AArch64ACLETypes.def" |
| 887 | { |
| 888 | if (BT->getKind() == BuiltinType::MFloat8) { |
| 889 | Encoding = llvm::dwarf::DW_ATE_unsigned_char; |
| 890 | BTName = BT->getName(Policy: CGM.getLangOpts()); |
| 891 | // Bit size and offset of the type. |
| 892 | uint64_t Size = CGM.getContext().getTypeSize(T: BT); |
| 893 | return DBuilder.createBasicType(Name: BTName, SizeInBits: Size, Encoding); |
| 894 | } |
| 895 | ASTContext::BuiltinVectorTypeInfo Info = |
| 896 | // For svcount_t, only the lower 2 bytes are relevant. |
| 897 | BT->getKind() == BuiltinType::SveCount |
| 898 | ? ASTContext::BuiltinVectorTypeInfo( |
| 899 | CGM.getContext().BoolTy, llvm::ElementCount::getFixed(MinVal: 16), |
| 900 | 1) |
| 901 | : CGM.getContext().getBuiltinVectorTypeInfo(VecTy: BT); |
| 902 | |
| 903 | // A single vector of bytes may not suffice as the representation of |
| 904 | // svcount_t tuples because of the gap between the active 16bits of |
| 905 | // successive tuple members. Currently no such tuples are defined for |
| 906 | // svcount_t, so assert that NumVectors is 1. |
| 907 | assert((BT->getKind() != BuiltinType::SveCount || Info.NumVectors == 1) && |
| 908 | "Unsupported number of vectors for svcount_t" ); |
| 909 | |
| 910 | // Debuggers can't extract 1bit from a vector, so will display a |
| 911 | // bitpattern for predicates instead. |
| 912 | unsigned NumElems = Info.EC.getKnownMinValue() * Info.NumVectors; |
| 913 | if (Info.ElementType == CGM.getContext().BoolTy) { |
| 914 | NumElems /= 8; |
| 915 | Info.ElementType = CGM.getContext().UnsignedCharTy; |
| 916 | } |
| 917 | |
| 918 | llvm::Metadata *LowerBound, *UpperBound; |
| 919 | LowerBound = llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
| 920 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: 0)); |
| 921 | if (Info.EC.isScalable()) { |
| 922 | unsigned NumElemsPerVG = NumElems / 2; |
| 923 | SmallVector<uint64_t, 9> Expr( |
| 924 | {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx, |
| 925 | /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul, |
| 926 | llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus}); |
| 927 | UpperBound = DBuilder.createExpression(Addr: Expr); |
| 928 | } else |
| 929 | UpperBound = llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
| 930 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: NumElems - 1)); |
| 931 | |
| 932 | llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange( |
| 933 | /*count*/ Count: nullptr, LowerBound, UpperBound, /*stride*/ Stride: nullptr); |
| 934 | llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Elements: Subscript); |
| 935 | llvm::DIType *ElemTy = |
| 936 | getOrCreateType(Ty: Info.ElementType, Fg: TheCU->getFile()); |
| 937 | auto Align = getTypeAlignIfRequired(Ty: BT, Ctx: CGM.getContext()); |
| 938 | return DBuilder.createVectorType(/*Size*/ 0, AlignInBits: Align, Ty: ElemTy, |
| 939 | Subscripts: SubscriptArray); |
| 940 | } |
| 941 | // It doesn't make sense to generate debug info for PowerPC MMA vector types. |
| 942 | // So we return a safe type here to avoid generating an error. |
| 943 | #define PPC_VECTOR_TYPE(Name, Id, size) \ |
| 944 | case BuiltinType::Id: |
| 945 | #include "clang/Basic/PPCTypes.def" |
| 946 | return CreateType(BT: cast<const BuiltinType>(Val&: CGM.getContext().IntTy)); |
| 947 | |
| 948 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
| 949 | #include "clang/Basic/RISCVVTypes.def" |
| 950 | { |
| 951 | ASTContext::BuiltinVectorTypeInfo Info = |
| 952 | CGM.getContext().getBuiltinVectorTypeInfo(VecTy: BT); |
| 953 | |
| 954 | unsigned ElementCount = Info.EC.getKnownMinValue(); |
| 955 | unsigned SEW = CGM.getContext().getTypeSize(T: Info.ElementType); |
| 956 | |
| 957 | bool Fractional = false; |
| 958 | unsigned LMUL; |
| 959 | unsigned NFIELDS = Info.NumVectors; |
| 960 | unsigned FixedSize = ElementCount * SEW; |
| 961 | if (Info.ElementType == CGM.getContext().BoolTy) { |
| 962 | // Mask type only occupies one vector register. |
| 963 | LMUL = 1; |
| 964 | } else if (FixedSize < 64) { |
| 965 | // In RVV scalable vector types, we encode 64 bits in the fixed part. |
| 966 | Fractional = true; |
| 967 | LMUL = 64 / FixedSize; |
| 968 | } else { |
| 969 | LMUL = FixedSize / 64; |
| 970 | } |
| 971 | |
| 972 | // Element count = (VLENB / SEW) x LMUL x NFIELDS |
| 973 | SmallVector<uint64_t, 12> Expr( |
| 974 | // The DW_OP_bregx operation has two operands: a register which is |
| 975 | // specified by an unsigned LEB128 number, followed by a signed LEB128 |
| 976 | // offset. |
| 977 | {llvm::dwarf::DW_OP_bregx, // Read the contents of a register. |
| 978 | 4096 + 0xC22, // RISC-V VLENB CSR register. |
| 979 | 0, // Offset for DW_OP_bregx. It is dummy here. |
| 980 | llvm::dwarf::DW_OP_constu, |
| 981 | SEW / 8, // SEW is in bits. |
| 982 | llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL}); |
| 983 | if (Fractional) |
| 984 | Expr.push_back(Elt: llvm::dwarf::DW_OP_div); |
| 985 | else |
| 986 | Expr.push_back(Elt: llvm::dwarf::DW_OP_mul); |
| 987 | // NFIELDS multiplier |
| 988 | if (NFIELDS > 1) |
| 989 | Expr.append(IL: {llvm::dwarf::DW_OP_constu, NFIELDS, llvm::dwarf::DW_OP_mul}); |
| 990 | // Element max index = count - 1 |
| 991 | Expr.append(IL: {llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus}); |
| 992 | |
| 993 | auto *LowerBound = |
| 994 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
| 995 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: 0)); |
| 996 | auto *UpperBound = DBuilder.createExpression(Addr: Expr); |
| 997 | llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange( |
| 998 | /*count*/ Count: nullptr, LowerBound, UpperBound, /*stride*/ Stride: nullptr); |
| 999 | llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Elements: Subscript); |
| 1000 | llvm::DIType *ElemTy = |
| 1001 | getOrCreateType(Ty: Info.ElementType, Fg: TheCU->getFile()); |
| 1002 | |
| 1003 | auto Align = getTypeAlignIfRequired(Ty: BT, Ctx: CGM.getContext()); |
| 1004 | return DBuilder.createVectorType(/*Size=*/0, AlignInBits: Align, Ty: ElemTy, |
| 1005 | Subscripts: SubscriptArray); |
| 1006 | } |
| 1007 | |
| 1008 | #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \ |
| 1009 | case BuiltinType::Id: { \ |
| 1010 | if (!SingletonId) \ |
| 1011 | SingletonId = \ |
| 1012 | DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, \ |
| 1013 | MangledName, TheCU, TheCU->getFile(), 0); \ |
| 1014 | return SingletonId; \ |
| 1015 | } |
| 1016 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
| 1017 | #define AMDGPU_OPAQUE_PTR_TYPE(Name, Id, SingletonId, Width, Align, AS) \ |
| 1018 | case BuiltinType::Id: { \ |
| 1019 | if (!SingletonId) \ |
| 1020 | SingletonId = \ |
| 1021 | DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name, \ |
| 1022 | TheCU, TheCU->getFile(), 0); \ |
| 1023 | return SingletonId; \ |
| 1024 | } |
| 1025 | #define AMDGPU_NAMED_BARRIER_TYPE(Name, Id, SingletonId, Width, Align, Scope) \ |
| 1026 | case BuiltinType::Id: { \ |
| 1027 | if (!SingletonId) \ |
| 1028 | SingletonId = \ |
| 1029 | DBuilder.createBasicType(Name, Width, llvm::dwarf::DW_ATE_unsigned); \ |
| 1030 | return SingletonId; \ |
| 1031 | } |
| 1032 | #include "clang/Basic/AMDGPUTypes.def" |
| 1033 | case BuiltinType::UChar: |
| 1034 | case BuiltinType::Char_U: |
| 1035 | Encoding = llvm::dwarf::DW_ATE_unsigned_char; |
| 1036 | break; |
| 1037 | case BuiltinType::Char_S: |
| 1038 | case BuiltinType::SChar: |
| 1039 | Encoding = llvm::dwarf::DW_ATE_signed_char; |
| 1040 | break; |
| 1041 | case BuiltinType::Char8: |
| 1042 | case BuiltinType::Char16: |
| 1043 | case BuiltinType::Char32: |
| 1044 | Encoding = llvm::dwarf::DW_ATE_UTF; |
| 1045 | break; |
| 1046 | case BuiltinType::UShort: |
| 1047 | case BuiltinType::UInt: |
| 1048 | case BuiltinType::UInt128: |
| 1049 | case BuiltinType::ULong: |
| 1050 | case BuiltinType::WChar_U: |
| 1051 | case BuiltinType::ULongLong: |
| 1052 | Encoding = llvm::dwarf::DW_ATE_unsigned; |
| 1053 | break; |
| 1054 | case BuiltinType::Short: |
| 1055 | case BuiltinType::Int: |
| 1056 | case BuiltinType::Int128: |
| 1057 | case BuiltinType::Long: |
| 1058 | case BuiltinType::WChar_S: |
| 1059 | case BuiltinType::LongLong: |
| 1060 | Encoding = llvm::dwarf::DW_ATE_signed; |
| 1061 | break; |
| 1062 | case BuiltinType::Bool: |
| 1063 | Encoding = llvm::dwarf::DW_ATE_boolean; |
| 1064 | break; |
| 1065 | case BuiltinType::Half: |
| 1066 | case BuiltinType::Float: |
| 1067 | case BuiltinType::LongDouble: |
| 1068 | case BuiltinType::Float16: |
| 1069 | case BuiltinType::BFloat16: |
| 1070 | case BuiltinType::Float128: |
| 1071 | case BuiltinType::Double: |
| 1072 | case BuiltinType::Ibm128: |
| 1073 | // FIXME: For targets where long double, __ibm128 and __float128 have the |
| 1074 | // same size, they are currently indistinguishable in the debugger without |
| 1075 | // some special treatment. However, there is currently no consensus on |
| 1076 | // encoding and this should be updated once a DWARF encoding exists for |
| 1077 | // distinct floating point types of the same size. |
| 1078 | Encoding = llvm::dwarf::DW_ATE_float; |
| 1079 | break; |
| 1080 | case BuiltinType::ShortAccum: |
| 1081 | case BuiltinType::Accum: |
| 1082 | case BuiltinType::LongAccum: |
| 1083 | case BuiltinType::ShortFract: |
| 1084 | case BuiltinType::Fract: |
| 1085 | case BuiltinType::LongFract: |
| 1086 | case BuiltinType::SatShortFract: |
| 1087 | case BuiltinType::SatFract: |
| 1088 | case BuiltinType::SatLongFract: |
| 1089 | case BuiltinType::SatShortAccum: |
| 1090 | case BuiltinType::SatAccum: |
| 1091 | case BuiltinType::SatLongAccum: |
| 1092 | Encoding = llvm::dwarf::DW_ATE_signed_fixed; |
| 1093 | break; |
| 1094 | case BuiltinType::UShortAccum: |
| 1095 | case BuiltinType::UAccum: |
| 1096 | case BuiltinType::ULongAccum: |
| 1097 | case BuiltinType::UShortFract: |
| 1098 | case BuiltinType::UFract: |
| 1099 | case BuiltinType::ULongFract: |
| 1100 | case BuiltinType::SatUShortAccum: |
| 1101 | case BuiltinType::SatUAccum: |
| 1102 | case BuiltinType::SatULongAccum: |
| 1103 | case BuiltinType::SatUShortFract: |
| 1104 | case BuiltinType::SatUFract: |
| 1105 | case BuiltinType::SatULongFract: |
| 1106 | Encoding = llvm::dwarf::DW_ATE_unsigned_fixed; |
| 1107 | break; |
| 1108 | } |
| 1109 | |
| 1110 | BTName = BT->getName(Policy: CGM.getLangOpts()); |
| 1111 | // Bit size and offset of the type. |
| 1112 | uint64_t Size = CGM.getContext().getTypeSize(T: BT); |
| 1113 | return DBuilder.createBasicType(Name: BTName, SizeInBits: Size, Encoding); |
| 1114 | } |
| 1115 | |
| 1116 | llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) { |
| 1117 | |
| 1118 | StringRef Name = Ty->isUnsigned() ? "unsigned _BitInt" : "_BitInt" ; |
| 1119 | llvm::dwarf::TypeKind Encoding = Ty->isUnsigned() |
| 1120 | ? llvm::dwarf::DW_ATE_unsigned |
| 1121 | : llvm::dwarf::DW_ATE_signed; |
| 1122 | |
| 1123 | return DBuilder.createBasicType(Name, SizeInBits: CGM.getContext().getTypeSize(T: Ty), |
| 1124 | Encoding); |
| 1125 | } |
| 1126 | |
| 1127 | llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) { |
| 1128 | // Bit size and offset of the type. |
| 1129 | llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float; |
| 1130 | if (Ty->isComplexIntegerType()) |
| 1131 | Encoding = llvm::dwarf::DW_ATE_lo_user; |
| 1132 | |
| 1133 | uint64_t Size = CGM.getContext().getTypeSize(T: Ty); |
| 1134 | return DBuilder.createBasicType(Name: "complex" , SizeInBits: Size, Encoding); |
| 1135 | } |
| 1136 | |
| 1137 | static void stripUnusedQualifiers(Qualifiers &Q) { |
| 1138 | // Ignore these qualifiers for now. |
| 1139 | Q.removeObjCGCAttr(); |
| 1140 | Q.removeAddressSpace(); |
| 1141 | Q.removeObjCLifetime(); |
| 1142 | Q.removeUnaligned(); |
| 1143 | } |
| 1144 | |
| 1145 | static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) { |
| 1146 | if (Q.hasConst()) { |
| 1147 | Q.removeConst(); |
| 1148 | return llvm::dwarf::DW_TAG_const_type; |
| 1149 | } |
| 1150 | if (Q.hasVolatile()) { |
| 1151 | Q.removeVolatile(); |
| 1152 | return llvm::dwarf::DW_TAG_volatile_type; |
| 1153 | } |
| 1154 | if (Q.hasRestrict()) { |
| 1155 | Q.removeRestrict(); |
| 1156 | return llvm::dwarf::DW_TAG_restrict_type; |
| 1157 | } |
| 1158 | return (llvm::dwarf::Tag)0; |
| 1159 | } |
| 1160 | |
| 1161 | llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty, |
| 1162 | llvm::DIFile *Unit) { |
| 1163 | QualifierCollector Qc; |
| 1164 | const Type *T = Qc.strip(type: Ty); |
| 1165 | |
| 1166 | stripUnusedQualifiers(Q&: Qc); |
| 1167 | |
| 1168 | // We will create one Derived type for one qualifier and recurse to handle any |
| 1169 | // additional ones. |
| 1170 | llvm::dwarf::Tag Tag = getNextQualifier(Q&: Qc); |
| 1171 | if (!Tag) { |
| 1172 | if (Qc.getPointerAuth()) { |
| 1173 | unsigned Key = Qc.getPointerAuth().getKey(); |
| 1174 | bool IsDiscr = Qc.getPointerAuth().isAddressDiscriminated(); |
| 1175 | unsigned = Qc.getPointerAuth().getExtraDiscriminator(); |
| 1176 | bool IsaPointer = Qc.getPointerAuth().isIsaPointer(); |
| 1177 | bool AuthenticatesNullValues = |
| 1178 | Qc.getPointerAuth().authenticatesNullValues(); |
| 1179 | Qc.removePointerAuth(); |
| 1180 | assert(Qc.empty() && "Unknown type qualifier for debug info" ); |
| 1181 | llvm::DIType *FromTy = getOrCreateType(Ty: QualType(T, 0), Fg: Unit); |
| 1182 | return DBuilder.createPtrAuthQualifiedType(FromTy, Key, IsAddressDiscriminated: IsDiscr, |
| 1183 | ExtraDiscriminator: ExtraDiscr, IsaPointer, |
| 1184 | authenticatesNullValues: AuthenticatesNullValues); |
| 1185 | } else { |
| 1186 | assert(Qc.empty() && "Unknown type qualifier for debug info" ); |
| 1187 | return getOrCreateType(Ty: QualType(T, 0), Fg: Unit); |
| 1188 | } |
| 1189 | } |
| 1190 | |
| 1191 | auto *FromTy = getOrCreateType(Ty: Qc.apply(Context: CGM.getContext(), T), Fg: Unit); |
| 1192 | |
| 1193 | // No need to fill in the Name, Line, Size, Alignment, Offset in case of |
| 1194 | // CVR derived types. |
| 1195 | return DBuilder.createQualifiedType(Tag, FromTy); |
| 1196 | } |
| 1197 | |
| 1198 | llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F, |
| 1199 | llvm::DIFile *Unit) { |
| 1200 | FunctionProtoType::ExtProtoInfo EPI = F->getExtProtoInfo(); |
| 1201 | Qualifiers &Q = EPI.TypeQuals; |
| 1202 | stripUnusedQualifiers(Q); |
| 1203 | |
| 1204 | // We will create one Derived type for one qualifier and recurse to handle any |
| 1205 | // additional ones. |
| 1206 | llvm::dwarf::Tag Tag = getNextQualifier(Q); |
| 1207 | if (!Tag) { |
| 1208 | assert(Q.empty() && "Unknown type qualifier for debug info" ); |
| 1209 | return nullptr; |
| 1210 | } |
| 1211 | |
| 1212 | auto *FromTy = |
| 1213 | getOrCreateType(Ty: CGM.getContext().getFunctionType(ResultTy: F->getReturnType(), |
| 1214 | Args: F->getParamTypes(), EPI), |
| 1215 | Fg: Unit); |
| 1216 | |
| 1217 | // No need to fill in the Name, Line, Size, Alignment, Offset in case of |
| 1218 | // CVR derived types. |
| 1219 | return DBuilder.createQualifiedType(Tag, FromTy); |
| 1220 | } |
| 1221 | |
| 1222 | llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, |
| 1223 | llvm::DIFile *Unit) { |
| 1224 | |
| 1225 | // The frontend treats 'id' as a typedef to an ObjCObjectType, |
| 1226 | // whereas 'id<protocol>' is treated as an ObjCPointerType. For the |
| 1227 | // debug info, we want to emit 'id' in both cases. |
| 1228 | if (Ty->isObjCQualifiedIdType()) |
| 1229 | return getOrCreateType(Ty: CGM.getContext().getObjCIdType(), Fg: Unit); |
| 1230 | |
| 1231 | return CreatePointerLikeType(Tag: llvm::dwarf::DW_TAG_pointer_type, Ty, |
| 1232 | PointeeTy: Ty->getPointeeType(), F: Unit); |
| 1233 | } |
| 1234 | |
| 1235 | llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty, |
| 1236 | llvm::DIFile *Unit) { |
| 1237 | return CreatePointerLikeType(Tag: llvm::dwarf::DW_TAG_pointer_type, Ty, |
| 1238 | PointeeTy: Ty->getPointeeType(), F: Unit); |
| 1239 | } |
| 1240 | |
| 1241 | /// \return whether a C++ mangling exists for the type defined by TD. |
| 1242 | static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) { |
| 1243 | switch (TheCU->getSourceLanguage()) { |
| 1244 | case llvm::dwarf::DW_LANG_C_plus_plus: |
| 1245 | case llvm::dwarf::DW_LANG_C_plus_plus_11: |
| 1246 | case llvm::dwarf::DW_LANG_C_plus_plus_14: |
| 1247 | return true; |
| 1248 | case llvm::dwarf::DW_LANG_ObjC_plus_plus: |
| 1249 | return isa<CXXRecordDecl>(Val: TD) || isa<EnumDecl>(Val: TD); |
| 1250 | default: |
| 1251 | return false; |
| 1252 | } |
| 1253 | } |
| 1254 | |
| 1255 | // Determines if the debug info for this tag declaration needs a type |
| 1256 | // identifier. The purpose of the unique identifier is to deduplicate type |
| 1257 | // information for identical types across TUs. Because of the C++ one definition |
| 1258 | // rule (ODR), it is valid to assume that the type is defined the same way in |
| 1259 | // every TU and its debug info is equivalent. |
| 1260 | // |
| 1261 | // C does not have the ODR, and it is common for codebases to contain multiple |
| 1262 | // different definitions of a struct with the same name in different TUs. |
| 1263 | // Therefore, if the type doesn't have a C++ mangling, don't give it an |
| 1264 | // identifer. Type information in C is smaller and simpler than C++ type |
| 1265 | // information, so the increase in debug info size is negligible. |
| 1266 | // |
| 1267 | // If the type is not externally visible, it should be unique to the current TU, |
| 1268 | // and should not need an identifier to participate in type deduplication. |
| 1269 | // However, when emitting CodeView, the format internally uses these |
| 1270 | // unique type name identifers for references between debug info. For example, |
| 1271 | // the method of a class in an anonymous namespace uses the identifer to refer |
| 1272 | // to its parent class. The Microsoft C++ ABI attempts to provide unique names |
| 1273 | // for such types, so when emitting CodeView, always use identifiers for C++ |
| 1274 | // types. This may create problems when attempting to emit CodeView when the MS |
| 1275 | // C++ ABI is not in use. |
| 1276 | static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM, |
| 1277 | llvm::DICompileUnit *TheCU) { |
| 1278 | // We only add a type identifier for types with C++ name mangling. |
| 1279 | if (!hasCXXMangling(TD, TheCU)) |
| 1280 | return false; |
| 1281 | |
| 1282 | // Externally visible types with C++ mangling need a type identifier. |
| 1283 | if (TD->isExternallyVisible()) |
| 1284 | return true; |
| 1285 | |
| 1286 | // CodeView types with C++ mangling need a type identifier. |
| 1287 | if (CGM.getCodeGenOpts().EmitCodeView) |
| 1288 | return true; |
| 1289 | |
| 1290 | return false; |
| 1291 | } |
| 1292 | |
| 1293 | // Returns a unique type identifier string if one exists, or an empty string. |
| 1294 | static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM, |
| 1295 | llvm::DICompileUnit *TheCU) { |
| 1296 | SmallString<256> Identifier; |
| 1297 | const TagDecl *TD = Ty->getDecl(); |
| 1298 | |
| 1299 | if (!needsTypeIdentifier(TD, CGM, TheCU)) |
| 1300 | return Identifier; |
| 1301 | if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: TD)) |
| 1302 | if (RD->getDefinition()) |
| 1303 | if (RD->isDynamicClass() && |
| 1304 | CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage) |
| 1305 | return Identifier; |
| 1306 | |
| 1307 | // TODO: This is using the RTTI name. Is there a better way to get |
| 1308 | // a unique string for a type? |
| 1309 | llvm::raw_svector_ostream Out(Identifier); |
| 1310 | CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(T: QualType(Ty, 0), Out); |
| 1311 | return Identifier; |
| 1312 | } |
| 1313 | |
| 1314 | /// \return the appropriate DWARF tag for a composite type. |
| 1315 | static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) { |
| 1316 | llvm::dwarf::Tag Tag; |
| 1317 | if (RD->isStruct() || RD->isInterface()) |
| 1318 | Tag = llvm::dwarf::DW_TAG_structure_type; |
| 1319 | else if (RD->isUnion()) |
| 1320 | Tag = llvm::dwarf::DW_TAG_union_type; |
| 1321 | else { |
| 1322 | // FIXME: This could be a struct type giving a default visibility different |
| 1323 | // than C++ class type, but needs llvm metadata changes first. |
| 1324 | assert(RD->isClass()); |
| 1325 | Tag = llvm::dwarf::DW_TAG_class_type; |
| 1326 | } |
| 1327 | return Tag; |
| 1328 | } |
| 1329 | |
| 1330 | llvm::DICompositeType * |
| 1331 | CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty, |
| 1332 | llvm::DIScope *Ctx) { |
| 1333 | const RecordDecl *RD = Ty->getDecl(); |
| 1334 | if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(Decl: RD))) |
| 1335 | return cast<llvm::DICompositeType>(Val: T); |
| 1336 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: RD->getLocation()); |
| 1337 | const unsigned Line = |
| 1338 | getLineNumber(Loc: RD->getLocation().isValid() ? RD->getLocation() : CurLoc); |
| 1339 | StringRef RDName = getClassName(RD); |
| 1340 | |
| 1341 | uint64_t Size = 0; |
| 1342 | uint32_t Align = 0; |
| 1343 | |
| 1344 | const RecordDecl *D = RD->getDefinition(); |
| 1345 | if (D && D->isCompleteDefinition()) |
| 1346 | Size = CGM.getContext().getTypeSize(T: Ty); |
| 1347 | |
| 1348 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl; |
| 1349 | |
| 1350 | // Add flag to nontrivial forward declarations. To be consistent with MSVC, |
| 1351 | // add the flag if a record has no definition because we don't know whether |
| 1352 | // it will be trivial or not. |
| 1353 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
| 1354 | if (!CXXRD->hasDefinition() || |
| 1355 | (CXXRD->hasDefinition() && !CXXRD->isTrivial())) |
| 1356 | Flags |= llvm::DINode::FlagNonTrivial; |
| 1357 | |
| 1358 | // Create the type. |
| 1359 | SmallString<256> Identifier; |
| 1360 | // Don't include a linkage name in line tables only. |
| 1361 | if (CGM.getCodeGenOpts().hasReducedDebugInfo()) |
| 1362 | Identifier = getTypeIdentifier(Ty, CGM, TheCU); |
| 1363 | llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType( |
| 1364 | Tag: getTagForRecord(RD), Name: RDName, Scope: Ctx, F: DefUnit, Line, RuntimeLang: 0, SizeInBits: Size, AlignInBits: Align, Flags, |
| 1365 | UniqueIdentifier: Identifier); |
| 1366 | if (CGM.getCodeGenOpts().DebugFwdTemplateParams) |
| 1367 | if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) |
| 1368 | DBuilder.replaceArrays(T&: RetTy, Elements: llvm::DINodeArray(), |
| 1369 | TParams: CollectCXXTemplateParams(TS: TSpecial, F: DefUnit)); |
| 1370 | ReplaceMap.emplace_back( |
| 1371 | args: std::piecewise_construct, args: std::make_tuple(args&: Ty), |
| 1372 | args: std::make_tuple(args: static_cast<llvm::Metadata *>(RetTy))); |
| 1373 | return RetTy; |
| 1374 | } |
| 1375 | |
| 1376 | llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag, |
| 1377 | const Type *Ty, |
| 1378 | QualType PointeeTy, |
| 1379 | llvm::DIFile *Unit) { |
| 1380 | // Bit size, align and offset of the type. |
| 1381 | // Size is always the size of a pointer. |
| 1382 | uint64_t Size = CGM.getContext().getTypeSize(T: Ty); |
| 1383 | auto Align = getTypeAlignIfRequired(Ty, Ctx: CGM.getContext()); |
| 1384 | std::optional<unsigned> DWARFAddressSpace = |
| 1385 | CGM.getTarget().getDWARFAddressSpace( |
| 1386 | AddressSpace: CGM.getTypes().getTargetAddressSpace(T: PointeeTy)); |
| 1387 | |
| 1388 | const BTFTagAttributedType *BTFAttrTy; |
| 1389 | if (auto *Atomic = PointeeTy->getAs<AtomicType>()) |
| 1390 | BTFAttrTy = dyn_cast<BTFTagAttributedType>(Val: Atomic->getValueType()); |
| 1391 | else |
| 1392 | BTFAttrTy = dyn_cast<BTFTagAttributedType>(Val&: PointeeTy); |
| 1393 | SmallVector<llvm::Metadata *, 4> Annots; |
| 1394 | while (BTFAttrTy) { |
| 1395 | StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag(); |
| 1396 | if (!Tag.empty()) { |
| 1397 | llvm::Metadata *Ops[2] = { |
| 1398 | llvm::MDString::get(Context&: CGM.getLLVMContext(), Str: StringRef("btf_type_tag" )), |
| 1399 | llvm::MDString::get(Context&: CGM.getLLVMContext(), Str: Tag)}; |
| 1400 | Annots.insert(I: Annots.begin(), |
| 1401 | Elt: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: Ops)); |
| 1402 | } |
| 1403 | BTFAttrTy = dyn_cast<BTFTagAttributedType>(Val: BTFAttrTy->getWrappedType()); |
| 1404 | } |
| 1405 | |
| 1406 | llvm::DINodeArray Annotations = nullptr; |
| 1407 | if (Annots.size() > 0) |
| 1408 | Annotations = DBuilder.getOrCreateArray(Elements: Annots); |
| 1409 | |
| 1410 | if (Tag == llvm::dwarf::DW_TAG_reference_type || |
| 1411 | Tag == llvm::dwarf::DW_TAG_rvalue_reference_type) |
| 1412 | return DBuilder.createReferenceType(Tag, RTy: getOrCreateType(Ty: PointeeTy, Fg: Unit), |
| 1413 | SizeInBits: Size, AlignInBits: Align, DWARFAddressSpace); |
| 1414 | else |
| 1415 | return DBuilder.createPointerType(PointeeTy: getOrCreateType(Ty: PointeeTy, Fg: Unit), SizeInBits: Size, |
| 1416 | AlignInBits: Align, DWARFAddressSpace, Name: StringRef(), |
| 1417 | Annotations); |
| 1418 | } |
| 1419 | |
| 1420 | llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name, |
| 1421 | llvm::DIType *&Cache) { |
| 1422 | if (Cache) |
| 1423 | return Cache; |
| 1424 | Cache = DBuilder.createForwardDecl(Tag: llvm::dwarf::DW_TAG_structure_type, Name, |
| 1425 | Scope: TheCU, F: TheCU->getFile(), Line: 0); |
| 1426 | unsigned Size = CGM.getContext().getTypeSize(T: CGM.getContext().VoidPtrTy); |
| 1427 | Cache = DBuilder.createPointerType(PointeeTy: Cache, SizeInBits: Size); |
| 1428 | return Cache; |
| 1429 | } |
| 1430 | |
| 1431 | uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer( |
| 1432 | const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy, |
| 1433 | unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) { |
| 1434 | QualType FType; |
| 1435 | |
| 1436 | // Advanced by calls to CreateMemberType in increments of FType, then |
| 1437 | // returned as the overall size of the default elements. |
| 1438 | uint64_t FieldOffset = 0; |
| 1439 | |
| 1440 | // Blocks in OpenCL have unique constraints which make the standard fields |
| 1441 | // redundant while requiring size and align fields for enqueue_kernel. See |
| 1442 | // initializeForBlockHeader in CGBlocks.cpp |
| 1443 | if (CGM.getLangOpts().OpenCL) { |
| 1444 | FType = CGM.getContext().IntTy; |
| 1445 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__size" , Offset: &FieldOffset)); |
| 1446 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__align" , Offset: &FieldOffset)); |
| 1447 | } else { |
| 1448 | FType = CGM.getContext().getPointerType(T: CGM.getContext().VoidTy); |
| 1449 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__isa" , Offset: &FieldOffset)); |
| 1450 | FType = CGM.getContext().IntTy; |
| 1451 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__flags" , Offset: &FieldOffset)); |
| 1452 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__reserved" , Offset: &FieldOffset)); |
| 1453 | FType = CGM.getContext().getPointerType(T: Ty->getPointeeType()); |
| 1454 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__FuncPtr" , Offset: &FieldOffset)); |
| 1455 | FType = CGM.getContext().getPointerType(T: CGM.getContext().VoidTy); |
| 1456 | uint64_t FieldSize = CGM.getContext().getTypeSize(T: Ty); |
| 1457 | uint32_t FieldAlign = CGM.getContext().getTypeAlign(T: Ty); |
| 1458 | EltTys.push_back(Elt: DBuilder.createMemberType( |
| 1459 | Scope: Unit, Name: "__descriptor" , File: nullptr, LineNo, SizeInBits: FieldSize, AlignInBits: FieldAlign, |
| 1460 | OffsetInBits: FieldOffset, Flags: llvm::DINode::FlagZero, Ty: DescTy)); |
| 1461 | FieldOffset += FieldSize; |
| 1462 | } |
| 1463 | |
| 1464 | return FieldOffset; |
| 1465 | } |
| 1466 | |
| 1467 | llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty, |
| 1468 | llvm::DIFile *Unit) { |
| 1469 | SmallVector<llvm::Metadata *, 8> EltTys; |
| 1470 | QualType FType; |
| 1471 | uint64_t FieldOffset; |
| 1472 | llvm::DINodeArray Elements; |
| 1473 | |
| 1474 | FieldOffset = 0; |
| 1475 | FType = CGM.getContext().UnsignedLongTy; |
| 1476 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "reserved" , Offset: &FieldOffset)); |
| 1477 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "Size" , Offset: &FieldOffset)); |
| 1478 | |
| 1479 | Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
| 1480 | EltTys.clear(); |
| 1481 | |
| 1482 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock; |
| 1483 | |
| 1484 | auto *EltTy = |
| 1485 | DBuilder.createStructType(Scope: Unit, Name: "__block_descriptor" , File: nullptr, LineNumber: 0, |
| 1486 | SizeInBits: FieldOffset, AlignInBits: 0, Flags, DerivedFrom: nullptr, Elements); |
| 1487 | |
| 1488 | // Bit size, align and offset of the type. |
| 1489 | uint64_t Size = CGM.getContext().getTypeSize(T: Ty); |
| 1490 | |
| 1491 | auto *DescTy = DBuilder.createPointerType(PointeeTy: EltTy, SizeInBits: Size); |
| 1492 | |
| 1493 | FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy, |
| 1494 | LineNo: 0, EltTys); |
| 1495 | |
| 1496 | Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
| 1497 | |
| 1498 | // The __block_literal_generic structs are marked with a special |
| 1499 | // DW_AT_APPLE_BLOCK attribute and are an implementation detail only |
| 1500 | // the debugger needs to know about. To allow type uniquing, emit |
| 1501 | // them without a name or a location. |
| 1502 | EltTy = DBuilder.createStructType(Scope: Unit, Name: "" , File: nullptr, LineNumber: 0, SizeInBits: FieldOffset, AlignInBits: 0, |
| 1503 | Flags, DerivedFrom: nullptr, Elements); |
| 1504 | |
| 1505 | return DBuilder.createPointerType(PointeeTy: EltTy, SizeInBits: Size); |
| 1506 | } |
| 1507 | |
| 1508 | static llvm::SmallVector<TemplateArgument> |
| 1509 | GetTemplateArgs(const TemplateDecl *TD, const TemplateSpecializationType *Ty) { |
| 1510 | assert(Ty->isTypeAlias()); |
| 1511 | // TemplateSpecializationType doesn't know if its template args are |
| 1512 | // being substituted into a parameter pack. We can find out if that's |
| 1513 | // the case now by inspecting the TypeAliasTemplateDecl template |
| 1514 | // parameters. Insert Ty's template args into SpecArgs, bundling args |
| 1515 | // passed to a parameter pack into a TemplateArgument::Pack. It also |
| 1516 | // doesn't know the value of any defaulted args, so collect those now |
| 1517 | // too. |
| 1518 | SmallVector<TemplateArgument> SpecArgs; |
| 1519 | ArrayRef SubstArgs = Ty->template_arguments(); |
| 1520 | for (const NamedDecl *Param : TD->getTemplateParameters()->asArray()) { |
| 1521 | // If Param is a parameter pack, pack the remaining arguments. |
| 1522 | if (Param->isParameterPack()) { |
| 1523 | SpecArgs.push_back(Elt: TemplateArgument(SubstArgs)); |
| 1524 | break; |
| 1525 | } |
| 1526 | |
| 1527 | // Skip defaulted args. |
| 1528 | // FIXME: Ideally, we wouldn't do this. We can read the default values |
| 1529 | // for each parameter. However, defaulted arguments which are dependent |
| 1530 | // values or dependent types can't (easily?) be resolved here. |
| 1531 | if (SubstArgs.empty()) { |
| 1532 | // If SubstArgs is now empty (we're taking from it each iteration) and |
| 1533 | // this template parameter isn't a pack, then that should mean we're |
| 1534 | // using default values for the remaining template parameters (after |
| 1535 | // which there may be an empty pack too which we will ignore). |
| 1536 | break; |
| 1537 | } |
| 1538 | |
| 1539 | // Take the next argument. |
| 1540 | SpecArgs.push_back(Elt: SubstArgs.front()); |
| 1541 | SubstArgs = SubstArgs.drop_front(); |
| 1542 | } |
| 1543 | return SpecArgs; |
| 1544 | } |
| 1545 | |
| 1546 | llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, |
| 1547 | llvm::DIFile *Unit) { |
| 1548 | assert(Ty->isTypeAlias()); |
| 1549 | llvm::DIType *Src = getOrCreateType(Ty: Ty->getAliasedType(), Fg: Unit); |
| 1550 | |
| 1551 | const TemplateDecl *TD = Ty->getTemplateName().getAsTemplateDecl(); |
| 1552 | if (isa<BuiltinTemplateDecl>(Val: TD)) |
| 1553 | return Src; |
| 1554 | |
| 1555 | const auto *AliasDecl = cast<TypeAliasTemplateDecl>(Val: TD)->getTemplatedDecl(); |
| 1556 | if (AliasDecl->hasAttr<NoDebugAttr>()) |
| 1557 | return Src; |
| 1558 | |
| 1559 | SmallString<128> NS; |
| 1560 | llvm::raw_svector_ostream OS(NS); |
| 1561 | |
| 1562 | auto PP = getPrintingPolicy(); |
| 1563 | Ty->getTemplateName().print(OS, Policy: PP, Qual: TemplateName::Qualified::None); |
| 1564 | |
| 1565 | SourceLocation Loc = AliasDecl->getLocation(); |
| 1566 | |
| 1567 | if (CGM.getCodeGenOpts().DebugTemplateAlias) { |
| 1568 | auto ArgVector = ::GetTemplateArgs(TD, Ty); |
| 1569 | TemplateArgs Args = {.TList: TD->getTemplateParameters(), .Args: ArgVector}; |
| 1570 | |
| 1571 | // FIXME: Respect DebugTemplateNameKind::Mangled, e.g. by using GetName. |
| 1572 | // Note we can't use GetName without additional work: TypeAliasTemplateDecl |
| 1573 | // doesn't have instantiation information, so |
| 1574 | // TypeAliasTemplateDecl::getNameForDiagnostic wouldn't have access to the |
| 1575 | // template args. |
| 1576 | std::string Name; |
| 1577 | llvm::raw_string_ostream OS(Name); |
| 1578 | TD->getNameForDiagnostic(OS, Policy: PP, /*Qualified=*/false); |
| 1579 | if (CGM.getCodeGenOpts().getDebugSimpleTemplateNames() != |
| 1580 | llvm::codegenoptions::DebugTemplateNamesKind::Simple || |
| 1581 | !HasReconstitutableArgs(Args: Args.Args)) |
| 1582 | printTemplateArgumentList(OS, Args: Args.Args, Policy: PP); |
| 1583 | |
| 1584 | llvm::DIDerivedType *AliasTy = DBuilder.createTemplateAlias( |
| 1585 | Ty: Src, Name, File: getOrCreateFile(Loc), LineNo: getLineNumber(Loc), |
| 1586 | Context: getDeclContextDescriptor(D: AliasDecl), TParams: CollectTemplateParams(Args, Unit)); |
| 1587 | return AliasTy; |
| 1588 | } |
| 1589 | |
| 1590 | printTemplateArgumentList(OS, Args: Ty->template_arguments(), Policy: PP, |
| 1591 | TPL: TD->getTemplateParameters()); |
| 1592 | return DBuilder.createTypedef(Ty: Src, Name: OS.str(), File: getOrCreateFile(Loc), |
| 1593 | LineNo: getLineNumber(Loc), |
| 1594 | Context: getDeclContextDescriptor(D: AliasDecl)); |
| 1595 | } |
| 1596 | |
| 1597 | /// Convert an AccessSpecifier into the corresponding DINode flag. |
| 1598 | /// As an optimization, return 0 if the access specifier equals the |
| 1599 | /// default for the containing type. |
| 1600 | static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access, |
| 1601 | const RecordDecl *RD) { |
| 1602 | AccessSpecifier Default = clang::AS_none; |
| 1603 | if (RD && RD->isClass()) |
| 1604 | Default = clang::AS_private; |
| 1605 | else if (RD && (RD->isStruct() || RD->isUnion())) |
| 1606 | Default = clang::AS_public; |
| 1607 | |
| 1608 | if (Access == Default) |
| 1609 | return llvm::DINode::FlagZero; |
| 1610 | |
| 1611 | switch (Access) { |
| 1612 | case clang::AS_private: |
| 1613 | return llvm::DINode::FlagPrivate; |
| 1614 | case clang::AS_protected: |
| 1615 | return llvm::DINode::FlagProtected; |
| 1616 | case clang::AS_public: |
| 1617 | return llvm::DINode::FlagPublic; |
| 1618 | case clang::AS_none: |
| 1619 | return llvm::DINode::FlagZero; |
| 1620 | } |
| 1621 | llvm_unreachable("unexpected access enumerator" ); |
| 1622 | } |
| 1623 | |
| 1624 | llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty, |
| 1625 | llvm::DIFile *Unit) { |
| 1626 | llvm::DIType *Underlying = |
| 1627 | getOrCreateType(Ty: Ty->getDecl()->getUnderlyingType(), Fg: Unit); |
| 1628 | |
| 1629 | if (Ty->getDecl()->hasAttr<NoDebugAttr>()) |
| 1630 | return Underlying; |
| 1631 | |
| 1632 | // We don't set size information, but do specify where the typedef was |
| 1633 | // declared. |
| 1634 | SourceLocation Loc = Ty->getDecl()->getLocation(); |
| 1635 | |
| 1636 | uint32_t Align = getDeclAlignIfRequired(D: Ty->getDecl(), Ctx: CGM.getContext()); |
| 1637 | // Typedefs are derived from some other type. |
| 1638 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D: Ty->getDecl()); |
| 1639 | |
| 1640 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 1641 | const DeclContext *DC = Ty->getDecl()->getDeclContext(); |
| 1642 | if (isa<RecordDecl>(Val: DC)) |
| 1643 | Flags = getAccessFlag(Access: Ty->getDecl()->getAccess(), RD: cast<RecordDecl>(Val: DC)); |
| 1644 | |
| 1645 | return DBuilder.createTypedef(Ty: Underlying, Name: Ty->getDecl()->getName(), |
| 1646 | File: getOrCreateFile(Loc), LineNo: getLineNumber(Loc), |
| 1647 | Context: getDeclContextDescriptor(D: Ty->getDecl()), AlignInBits: Align, |
| 1648 | Flags, Annotations); |
| 1649 | } |
| 1650 | |
| 1651 | static unsigned getDwarfCC(CallingConv CC) { |
| 1652 | switch (CC) { |
| 1653 | case CC_C: |
| 1654 | // Avoid emitting DW_AT_calling_convention if the C convention was used. |
| 1655 | return 0; |
| 1656 | |
| 1657 | case CC_X86StdCall: |
| 1658 | return llvm::dwarf::DW_CC_BORLAND_stdcall; |
| 1659 | case CC_X86FastCall: |
| 1660 | return llvm::dwarf::DW_CC_BORLAND_msfastcall; |
| 1661 | case CC_X86ThisCall: |
| 1662 | return llvm::dwarf::DW_CC_BORLAND_thiscall; |
| 1663 | case CC_X86VectorCall: |
| 1664 | return llvm::dwarf::DW_CC_LLVM_vectorcall; |
| 1665 | case CC_X86Pascal: |
| 1666 | return llvm::dwarf::DW_CC_BORLAND_pascal; |
| 1667 | case CC_Win64: |
| 1668 | return llvm::dwarf::DW_CC_LLVM_Win64; |
| 1669 | case CC_X86_64SysV: |
| 1670 | return llvm::dwarf::DW_CC_LLVM_X86_64SysV; |
| 1671 | case CC_AAPCS: |
| 1672 | case CC_AArch64VectorCall: |
| 1673 | case CC_AArch64SVEPCS: |
| 1674 | return llvm::dwarf::DW_CC_LLVM_AAPCS; |
| 1675 | case CC_AAPCS_VFP: |
| 1676 | return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP; |
| 1677 | case CC_IntelOclBicc: |
| 1678 | return llvm::dwarf::DW_CC_LLVM_IntelOclBicc; |
| 1679 | case CC_SpirFunction: |
| 1680 | return llvm::dwarf::DW_CC_LLVM_SpirFunction; |
| 1681 | case CC_DeviceKernel: |
| 1682 | return llvm::dwarf::DW_CC_LLVM_DeviceKernel; |
| 1683 | case CC_Swift: |
| 1684 | return llvm::dwarf::DW_CC_LLVM_Swift; |
| 1685 | case CC_SwiftAsync: |
| 1686 | return llvm::dwarf::DW_CC_LLVM_SwiftTail; |
| 1687 | case CC_PreserveMost: |
| 1688 | return llvm::dwarf::DW_CC_LLVM_PreserveMost; |
| 1689 | case CC_PreserveAll: |
| 1690 | return llvm::dwarf::DW_CC_LLVM_PreserveAll; |
| 1691 | case CC_X86RegCall: |
| 1692 | return llvm::dwarf::DW_CC_LLVM_X86RegCall; |
| 1693 | case CC_M68kRTD: |
| 1694 | return llvm::dwarf::DW_CC_LLVM_M68kRTD; |
| 1695 | case CC_PreserveNone: |
| 1696 | return llvm::dwarf::DW_CC_LLVM_PreserveNone; |
| 1697 | case CC_RISCVVectorCall: |
| 1698 | return llvm::dwarf::DW_CC_LLVM_RISCVVectorCall; |
| 1699 | #define CC_VLS_CASE(ABI_VLEN) case CC_RISCVVLSCall_##ABI_VLEN: |
| 1700 | CC_VLS_CASE(32) |
| 1701 | CC_VLS_CASE(64) |
| 1702 | CC_VLS_CASE(128) |
| 1703 | CC_VLS_CASE(256) |
| 1704 | CC_VLS_CASE(512) |
| 1705 | CC_VLS_CASE(1024) |
| 1706 | CC_VLS_CASE(2048) |
| 1707 | CC_VLS_CASE(4096) |
| 1708 | CC_VLS_CASE(8192) |
| 1709 | CC_VLS_CASE(16384) |
| 1710 | CC_VLS_CASE(32768) |
| 1711 | CC_VLS_CASE(65536) |
| 1712 | #undef CC_VLS_CASE |
| 1713 | return llvm::dwarf::DW_CC_LLVM_RISCVVLSCall; |
| 1714 | } |
| 1715 | return 0; |
| 1716 | } |
| 1717 | |
| 1718 | static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) { |
| 1719 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 1720 | if (Func->getExtProtoInfo().RefQualifier == RQ_LValue) |
| 1721 | Flags |= llvm::DINode::FlagLValueReference; |
| 1722 | if (Func->getExtProtoInfo().RefQualifier == RQ_RValue) |
| 1723 | Flags |= llvm::DINode::FlagRValueReference; |
| 1724 | return Flags; |
| 1725 | } |
| 1726 | |
| 1727 | llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty, |
| 1728 | llvm::DIFile *Unit) { |
| 1729 | const auto *FPT = dyn_cast<FunctionProtoType>(Val: Ty); |
| 1730 | if (FPT) { |
| 1731 | if (llvm::DIType *QTy = CreateQualifiedType(F: FPT, Unit)) |
| 1732 | return QTy; |
| 1733 | } |
| 1734 | |
| 1735 | // Create the type without any qualifiers |
| 1736 | |
| 1737 | SmallVector<llvm::Metadata *, 16> EltTys; |
| 1738 | |
| 1739 | // Add the result type at least. |
| 1740 | EltTys.push_back(Elt: getOrCreateType(Ty: Ty->getReturnType(), Fg: Unit)); |
| 1741 | |
| 1742 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 1743 | // Set up remainder of arguments if there is a prototype. |
| 1744 | // otherwise emit it as a variadic function. |
| 1745 | if (!FPT) { |
| 1746 | EltTys.push_back(Elt: DBuilder.createUnspecifiedParameter()); |
| 1747 | } else { |
| 1748 | Flags = getRefFlags(Func: FPT); |
| 1749 | for (const QualType &ParamType : FPT->param_types()) |
| 1750 | EltTys.push_back(Elt: getOrCreateType(Ty: ParamType, Fg: Unit)); |
| 1751 | if (FPT->isVariadic()) |
| 1752 | EltTys.push_back(Elt: DBuilder.createUnspecifiedParameter()); |
| 1753 | } |
| 1754 | |
| 1755 | llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elements: EltTys); |
| 1756 | llvm::DIType *F = DBuilder.createSubroutineType( |
| 1757 | ParameterTypes: EltTypeArray, Flags, CC: getDwarfCC(CC: Ty->getCallConv())); |
| 1758 | return F; |
| 1759 | } |
| 1760 | |
| 1761 | llvm::DIDerivedType * |
| 1762 | CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl, |
| 1763 | llvm::DIScope *RecordTy, const RecordDecl *RD) { |
| 1764 | StringRef Name = BitFieldDecl->getName(); |
| 1765 | QualType Ty = BitFieldDecl->getType(); |
| 1766 | if (BitFieldDecl->hasAttr<PreferredTypeAttr>()) |
| 1767 | Ty = BitFieldDecl->getAttr<PreferredTypeAttr>()->getType(); |
| 1768 | SourceLocation Loc = BitFieldDecl->getLocation(); |
| 1769 | llvm::DIFile *VUnit = getOrCreateFile(Loc); |
| 1770 | llvm::DIType *DebugType = getOrCreateType(Ty, Fg: VUnit); |
| 1771 | |
| 1772 | // Get the location for the field. |
| 1773 | llvm::DIFile *File = getOrCreateFile(Loc); |
| 1774 | unsigned Line = getLineNumber(Loc); |
| 1775 | |
| 1776 | const CGBitFieldInfo &BitFieldInfo = |
| 1777 | CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(FD: BitFieldDecl); |
| 1778 | uint64_t SizeInBits = BitFieldInfo.Size; |
| 1779 | assert(SizeInBits > 0 && "found named 0-width bitfield" ); |
| 1780 | uint64_t StorageOffsetInBits = |
| 1781 | CGM.getContext().toBits(CharSize: BitFieldInfo.StorageOffset); |
| 1782 | uint64_t Offset = BitFieldInfo.Offset; |
| 1783 | // The bit offsets for big endian machines are reversed for big |
| 1784 | // endian target, compensate for that as the DIDerivedType requires |
| 1785 | // un-reversed offsets. |
| 1786 | if (CGM.getDataLayout().isBigEndian()) |
| 1787 | Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset; |
| 1788 | uint64_t OffsetInBits = StorageOffsetInBits + Offset; |
| 1789 | llvm::DINode::DIFlags Flags = getAccessFlag(Access: BitFieldDecl->getAccess(), RD); |
| 1790 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D: BitFieldDecl); |
| 1791 | return DBuilder.createBitFieldMemberType( |
| 1792 | Scope: RecordTy, Name, File, LineNo: Line, SizeInBits, OffsetInBits, StorageOffsetInBits, |
| 1793 | Flags, Ty: DebugType, Annotations); |
| 1794 | } |
| 1795 | |
| 1796 | llvm::DIDerivedType *CGDebugInfo::createBitFieldSeparatorIfNeeded( |
| 1797 | const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI, |
| 1798 | llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD) { |
| 1799 | |
| 1800 | if (!CGM.getTargetCodeGenInfo().shouldEmitDWARFBitFieldSeparators()) |
| 1801 | return nullptr; |
| 1802 | |
| 1803 | /* |
| 1804 | Add a *single* zero-bitfield separator between two non-zero bitfields |
| 1805 | separated by one or more zero-bitfields. This is used to distinguish between |
| 1806 | structures such the ones below, where the memory layout is the same, but how |
| 1807 | the ABI assigns fields to registers differs. |
| 1808 | |
| 1809 | struct foo { |
| 1810 | int space[4]; |
| 1811 | char a : 8; // on amdgpu, passed on v4 |
| 1812 | char b : 8; |
| 1813 | char x : 8; |
| 1814 | char y : 8; |
| 1815 | }; |
| 1816 | struct bar { |
| 1817 | int space[4]; |
| 1818 | char a : 8; // on amdgpu, passed on v4 |
| 1819 | char b : 8; |
| 1820 | char : 0; |
| 1821 | char x : 8; // passed on v5 |
| 1822 | char y : 8; |
| 1823 | }; |
| 1824 | */ |
| 1825 | if (PreviousFieldsDI.empty()) |
| 1826 | return nullptr; |
| 1827 | |
| 1828 | // If we already emitted metadata for a 0-length bitfield, nothing to do here. |
| 1829 | auto *PreviousMDEntry = |
| 1830 | PreviousFieldsDI.empty() ? nullptr : PreviousFieldsDI.back(); |
| 1831 | auto *PreviousMDField = |
| 1832 | dyn_cast_or_null<llvm::DIDerivedType>(Val: PreviousMDEntry); |
| 1833 | if (!PreviousMDField || !PreviousMDField->isBitField() || |
| 1834 | PreviousMDField->getSizeInBits() == 0) |
| 1835 | return nullptr; |
| 1836 | |
| 1837 | auto PreviousBitfield = RD->field_begin(); |
| 1838 | std::advance(i&: PreviousBitfield, n: BitFieldDecl->getFieldIndex() - 1); |
| 1839 | |
| 1840 | assert(PreviousBitfield->isBitField()); |
| 1841 | |
| 1842 | if (!PreviousBitfield->isZeroLengthBitField()) |
| 1843 | return nullptr; |
| 1844 | |
| 1845 | QualType Ty = PreviousBitfield->getType(); |
| 1846 | SourceLocation Loc = PreviousBitfield->getLocation(); |
| 1847 | llvm::DIFile *VUnit = getOrCreateFile(Loc); |
| 1848 | llvm::DIType *DebugType = getOrCreateType(Ty, Fg: VUnit); |
| 1849 | llvm::DIScope *RecordTy = BitFieldDI->getScope(); |
| 1850 | |
| 1851 | llvm::DIFile *File = getOrCreateFile(Loc); |
| 1852 | unsigned Line = getLineNumber(Loc); |
| 1853 | |
| 1854 | uint64_t StorageOffsetInBits = |
| 1855 | cast<llvm::ConstantInt>(Val: BitFieldDI->getStorageOffsetInBits()) |
| 1856 | ->getZExtValue(); |
| 1857 | |
| 1858 | llvm::DINode::DIFlags Flags = |
| 1859 | getAccessFlag(Access: PreviousBitfield->getAccess(), RD); |
| 1860 | llvm::DINodeArray Annotations = |
| 1861 | CollectBTFDeclTagAnnotations(D: *PreviousBitfield); |
| 1862 | return DBuilder.createBitFieldMemberType( |
| 1863 | Scope: RecordTy, Name: "" , File, LineNo: Line, SizeInBits: 0, OffsetInBits: StorageOffsetInBits, StorageOffsetInBits, |
| 1864 | Flags, Ty: DebugType, Annotations); |
| 1865 | } |
| 1866 | |
| 1867 | llvm::DIType *CGDebugInfo::createFieldType( |
| 1868 | StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS, |
| 1869 | uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit, |
| 1870 | llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) { |
| 1871 | llvm::DIType *debugType = getOrCreateType(Ty: type, Fg: tunit); |
| 1872 | |
| 1873 | // Get the location for the field. |
| 1874 | llvm::DIFile *file = getOrCreateFile(Loc: loc); |
| 1875 | const unsigned line = getLineNumber(Loc: loc.isValid() ? loc : CurLoc); |
| 1876 | |
| 1877 | uint64_t SizeInBits = 0; |
| 1878 | auto Align = AlignInBits; |
| 1879 | if (!type->isIncompleteArrayType()) { |
| 1880 | TypeInfo TI = CGM.getContext().getTypeInfo(T: type); |
| 1881 | SizeInBits = TI.Width; |
| 1882 | if (!Align) |
| 1883 | Align = getTypeAlignIfRequired(Ty: type, Ctx: CGM.getContext()); |
| 1884 | } |
| 1885 | |
| 1886 | llvm::DINode::DIFlags flags = getAccessFlag(Access: AS, RD); |
| 1887 | return DBuilder.createMemberType(Scope: scope, Name: name, File: file, LineNo: line, SizeInBits, AlignInBits: Align, |
| 1888 | OffsetInBits: offsetInBits, Flags: flags, Ty: debugType, Annotations); |
| 1889 | } |
| 1890 | |
| 1891 | llvm::DISubprogram * |
| 1892 | CGDebugInfo::createInlinedSubprogram(StringRef FuncName, |
| 1893 | llvm::DIFile *FileScope) { |
| 1894 | // We are caching the subprogram because we don't want to duplicate |
| 1895 | // subprograms with the same message. Note that `SPFlagDefinition` prevents |
| 1896 | // subprograms from being uniqued. |
| 1897 | llvm::DISubprogram *&SP = InlinedSubprogramMap[FuncName]; |
| 1898 | |
| 1899 | if (!SP) { |
| 1900 | llvm::DISubroutineType *DIFnTy = DBuilder.createSubroutineType(ParameterTypes: nullptr); |
| 1901 | SP = DBuilder.createFunction( |
| 1902 | /*Scope=*/FileScope, /*Name=*/FuncName, /*LinkageName=*/StringRef(), |
| 1903 | /*File=*/FileScope, /*LineNo=*/0, /*Ty=*/DIFnTy, |
| 1904 | /*ScopeLine=*/0, |
| 1905 | /*Flags=*/llvm::DINode::FlagArtificial, |
| 1906 | /*SPFlags=*/llvm::DISubprogram::SPFlagDefinition, |
| 1907 | /*TParams=*/nullptr, /*Decl=*/nullptr, /*ThrownTypes=*/nullptr, |
| 1908 | /*Annotations=*/nullptr, /*TargetFuncName=*/StringRef(), |
| 1909 | /*UseKeyInstructions=*/CGM.getCodeGenOpts().DebugKeyInstructions); |
| 1910 | } |
| 1911 | |
| 1912 | return SP; |
| 1913 | } |
| 1914 | |
| 1915 | void CGDebugInfo::CollectRecordLambdaFields( |
| 1916 | const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements, |
| 1917 | llvm::DIType *RecordTy) { |
| 1918 | // For C++11 Lambdas a Field will be the same as a Capture, but the Capture |
| 1919 | // has the name and the location of the variable so we should iterate over |
| 1920 | // both concurrently. |
| 1921 | const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(D: CXXDecl); |
| 1922 | RecordDecl::field_iterator Field = CXXDecl->field_begin(); |
| 1923 | unsigned fieldno = 0; |
| 1924 | for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(), |
| 1925 | E = CXXDecl->captures_end(); |
| 1926 | I != E; ++I, ++Field, ++fieldno) { |
| 1927 | const LambdaCapture &C = *I; |
| 1928 | if (C.capturesVariable()) { |
| 1929 | SourceLocation Loc = C.getLocation(); |
| 1930 | assert(!Field->isBitField() && "lambdas don't have bitfield members!" ); |
| 1931 | ValueDecl *V = C.getCapturedVar(); |
| 1932 | StringRef VName = V->getName(); |
| 1933 | llvm::DIFile *VUnit = getOrCreateFile(Loc); |
| 1934 | auto Align = getDeclAlignIfRequired(D: V, Ctx: CGM.getContext()); |
| 1935 | llvm::DIType *FieldType = createFieldType( |
| 1936 | name: VName, type: Field->getType(), loc: Loc, AS: Field->getAccess(), |
| 1937 | offsetInBits: layout.getFieldOffset(FieldNo: fieldno), AlignInBits: Align, tunit: VUnit, scope: RecordTy, RD: CXXDecl); |
| 1938 | elements.push_back(Elt: FieldType); |
| 1939 | } else if (C.capturesThis()) { |
| 1940 | // TODO: Need to handle 'this' in some way by probably renaming the |
| 1941 | // this of the lambda class and having a field member of 'this' or |
| 1942 | // by using AT_object_pointer for the function and having that be |
| 1943 | // used as 'this' for semantic references. |
| 1944 | FieldDecl *f = *Field; |
| 1945 | llvm::DIFile *VUnit = getOrCreateFile(Loc: f->getLocation()); |
| 1946 | QualType type = f->getType(); |
| 1947 | StringRef ThisName = |
| 1948 | CGM.getCodeGenOpts().EmitCodeView ? "__this" : "this" ; |
| 1949 | llvm::DIType *fieldType = createFieldType( |
| 1950 | name: ThisName, type, loc: f->getLocation(), AS: f->getAccess(), |
| 1951 | offsetInBits: layout.getFieldOffset(FieldNo: fieldno), tunit: VUnit, scope: RecordTy, RD: CXXDecl); |
| 1952 | |
| 1953 | elements.push_back(Elt: fieldType); |
| 1954 | } |
| 1955 | } |
| 1956 | } |
| 1957 | |
| 1958 | llvm::DIDerivedType * |
| 1959 | CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy, |
| 1960 | const RecordDecl *RD) { |
| 1961 | // Create the descriptor for the static variable, with or without |
| 1962 | // constant initializers. |
| 1963 | Var = Var->getCanonicalDecl(); |
| 1964 | llvm::DIFile *VUnit = getOrCreateFile(Loc: Var->getLocation()); |
| 1965 | llvm::DIType *VTy = getOrCreateType(Ty: Var->getType(), Fg: VUnit); |
| 1966 | |
| 1967 | unsigned LineNumber = getLineNumber(Loc: Var->getLocation()); |
| 1968 | StringRef VName = Var->getName(); |
| 1969 | |
| 1970 | // FIXME: to avoid complications with type merging we should |
| 1971 | // emit the constant on the definition instead of the declaration. |
| 1972 | llvm::Constant *C = nullptr; |
| 1973 | if (Var->getInit()) { |
| 1974 | const APValue *Value = Var->evaluateValue(); |
| 1975 | if (Value) { |
| 1976 | if (Value->isInt()) |
| 1977 | C = llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: Value->getInt()); |
| 1978 | if (Value->isFloat()) |
| 1979 | C = llvm::ConstantFP::get(Context&: CGM.getLLVMContext(), V: Value->getFloat()); |
| 1980 | } |
| 1981 | } |
| 1982 | |
| 1983 | llvm::DINode::DIFlags Flags = getAccessFlag(Access: Var->getAccess(), RD); |
| 1984 | auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5 |
| 1985 | ? llvm::dwarf::DW_TAG_variable |
| 1986 | : llvm::dwarf::DW_TAG_member; |
| 1987 | auto Align = getDeclAlignIfRequired(D: Var, Ctx: CGM.getContext()); |
| 1988 | llvm::DIDerivedType *GV = DBuilder.createStaticMemberType( |
| 1989 | Scope: RecordTy, Name: VName, File: VUnit, LineNo: LineNumber, Ty: VTy, Flags, Val: C, Tag, AlignInBits: Align); |
| 1990 | StaticDataMemberCache[Var->getCanonicalDecl()].reset(MD: GV); |
| 1991 | return GV; |
| 1992 | } |
| 1993 | |
| 1994 | void CGDebugInfo::CollectRecordNormalField( |
| 1995 | const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit, |
| 1996 | SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy, |
| 1997 | const RecordDecl *RD) { |
| 1998 | StringRef name = field->getName(); |
| 1999 | QualType type = field->getType(); |
| 2000 | |
| 2001 | // Ignore unnamed fields unless they're anonymous structs/unions. |
| 2002 | if (name.empty() && !type->isRecordType()) |
| 2003 | return; |
| 2004 | |
| 2005 | llvm::DIType *FieldType; |
| 2006 | if (field->isBitField()) { |
| 2007 | llvm::DIDerivedType *BitFieldType; |
| 2008 | FieldType = BitFieldType = createBitFieldType(BitFieldDecl: field, RecordTy, RD); |
| 2009 | if (llvm::DIType *Separator = |
| 2010 | createBitFieldSeparatorIfNeeded(BitFieldDecl: field, BitFieldDI: BitFieldType, PreviousFieldsDI: elements, RD)) |
| 2011 | elements.push_back(Elt: Separator); |
| 2012 | } else { |
| 2013 | auto Align = getDeclAlignIfRequired(D: field, Ctx: CGM.getContext()); |
| 2014 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D: field); |
| 2015 | FieldType = |
| 2016 | createFieldType(name, type, loc: field->getLocation(), AS: field->getAccess(), |
| 2017 | offsetInBits: OffsetInBits, AlignInBits: Align, tunit, scope: RecordTy, RD, Annotations); |
| 2018 | } |
| 2019 | |
| 2020 | elements.push_back(Elt: FieldType); |
| 2021 | } |
| 2022 | |
| 2023 | void CGDebugInfo::CollectRecordNestedType( |
| 2024 | const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) { |
| 2025 | QualType Ty = CGM.getContext().getTypeDeclType(Decl: TD); |
| 2026 | // Injected class names are not considered nested records. |
| 2027 | if (isa<InjectedClassNameType>(Val: Ty)) |
| 2028 | return; |
| 2029 | SourceLocation Loc = TD->getLocation(); |
| 2030 | if (llvm::DIType *nestedType = getOrCreateType(Ty, Fg: getOrCreateFile(Loc))) |
| 2031 | elements.push_back(Elt: nestedType); |
| 2032 | } |
| 2033 | |
| 2034 | void CGDebugInfo::CollectRecordFields( |
| 2035 | const RecordDecl *record, llvm::DIFile *tunit, |
| 2036 | SmallVectorImpl<llvm::Metadata *> &elements, |
| 2037 | llvm::DICompositeType *RecordTy) { |
| 2038 | const auto *CXXDecl = dyn_cast<CXXRecordDecl>(Val: record); |
| 2039 | |
| 2040 | if (CXXDecl && CXXDecl->isLambda()) |
| 2041 | CollectRecordLambdaFields(CXXDecl, elements, RecordTy); |
| 2042 | else { |
| 2043 | const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(D: record); |
| 2044 | |
| 2045 | // Field number for non-static fields. |
| 2046 | unsigned fieldNo = 0; |
| 2047 | |
| 2048 | // Static and non-static members should appear in the same order as |
| 2049 | // the corresponding declarations in the source program. |
| 2050 | for (const auto *I : record->decls()) |
| 2051 | if (const auto *V = dyn_cast<VarDecl>(Val: I)) { |
| 2052 | if (V->hasAttr<NoDebugAttr>()) |
| 2053 | continue; |
| 2054 | |
| 2055 | // Skip variable template specializations when emitting CodeView. MSVC |
| 2056 | // doesn't emit them. |
| 2057 | if (CGM.getCodeGenOpts().EmitCodeView && |
| 2058 | isa<VarTemplateSpecializationDecl>(Val: V)) |
| 2059 | continue; |
| 2060 | |
| 2061 | if (isa<VarTemplatePartialSpecializationDecl>(Val: V)) |
| 2062 | continue; |
| 2063 | |
| 2064 | // Reuse the existing static member declaration if one exists |
| 2065 | auto MI = StaticDataMemberCache.find(Val: V->getCanonicalDecl()); |
| 2066 | if (MI != StaticDataMemberCache.end()) { |
| 2067 | assert(MI->second && |
| 2068 | "Static data member declaration should still exist" ); |
| 2069 | elements.push_back(Elt: MI->second); |
| 2070 | } else { |
| 2071 | auto Field = CreateRecordStaticField(Var: V, RecordTy, RD: record); |
| 2072 | elements.push_back(Elt: Field); |
| 2073 | } |
| 2074 | } else if (const auto *field = dyn_cast<FieldDecl>(Val: I)) { |
| 2075 | CollectRecordNormalField(field, OffsetInBits: layout.getFieldOffset(FieldNo: fieldNo), tunit, |
| 2076 | elements, RecordTy, RD: record); |
| 2077 | |
| 2078 | // Bump field number for next field. |
| 2079 | ++fieldNo; |
| 2080 | } else if (CGM.getCodeGenOpts().EmitCodeView) { |
| 2081 | // Debug info for nested types is included in the member list only for |
| 2082 | // CodeView. |
| 2083 | if (const auto *nestedType = dyn_cast<TypeDecl>(Val: I)) { |
| 2084 | // MSVC doesn't generate nested type for anonymous struct/union. |
| 2085 | if (isa<RecordDecl>(Val: I) && |
| 2086 | cast<RecordDecl>(Val: I)->isAnonymousStructOrUnion()) |
| 2087 | continue; |
| 2088 | if (!nestedType->isImplicit() && |
| 2089 | nestedType->getDeclContext() == record) |
| 2090 | CollectRecordNestedType(TD: nestedType, elements); |
| 2091 | } |
| 2092 | } |
| 2093 | } |
| 2094 | } |
| 2095 | |
| 2096 | llvm::DISubroutineType * |
| 2097 | CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, |
| 2098 | llvm::DIFile *Unit) { |
| 2099 | const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>(); |
| 2100 | if (Method->isStatic()) |
| 2101 | return cast_or_null<llvm::DISubroutineType>( |
| 2102 | Val: getOrCreateType(Ty: QualType(Func, 0), Fg: Unit)); |
| 2103 | |
| 2104 | QualType ThisType; |
| 2105 | if (!Method->hasCXXExplicitFunctionObjectParameter()) |
| 2106 | ThisType = Method->getThisType(); |
| 2107 | |
| 2108 | return getOrCreateInstanceMethodType(ThisPtr: ThisType, Func, Unit); |
| 2109 | } |
| 2110 | |
| 2111 | llvm::DISubroutineType *CGDebugInfo::getOrCreateMethodTypeForDestructor( |
| 2112 | const CXXMethodDecl *Method, llvm::DIFile *Unit, QualType FNType) { |
| 2113 | const FunctionProtoType *Func = FNType->getAs<FunctionProtoType>(); |
| 2114 | // skip the first param since it is also this |
| 2115 | return getOrCreateInstanceMethodType(ThisPtr: Method->getThisType(), Func, Unit, SkipFirst: true); |
| 2116 | } |
| 2117 | |
| 2118 | llvm::DISubroutineType * |
| 2119 | CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr, |
| 2120 | const FunctionProtoType *Func, |
| 2121 | llvm::DIFile *Unit, bool SkipFirst) { |
| 2122 | FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo(); |
| 2123 | Qualifiers &Qc = EPI.TypeQuals; |
| 2124 | Qc.removeConst(); |
| 2125 | Qc.removeVolatile(); |
| 2126 | Qc.removeRestrict(); |
| 2127 | Qc.removeUnaligned(); |
| 2128 | // Keep the removed qualifiers in sync with |
| 2129 | // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit) |
| 2130 | // On a 'real' member function type, these qualifiers are carried on the type |
| 2131 | // of the first parameter, not as separate DW_TAG_const_type (etc) decorator |
| 2132 | // tags around them. (But, in the raw function types with qualifiers, they have |
| 2133 | // to use wrapper types.) |
| 2134 | |
| 2135 | // Add "this" pointer. |
| 2136 | const auto *OriginalFunc = cast<llvm::DISubroutineType>( |
| 2137 | Val: getOrCreateType(Ty: CGM.getContext().getFunctionType( |
| 2138 | ResultTy: Func->getReturnType(), Args: Func->getParamTypes(), EPI), |
| 2139 | Fg: Unit)); |
| 2140 | llvm::DITypeRefArray Args = OriginalFunc->getTypeArray(); |
| 2141 | assert(Args.size() && "Invalid number of arguments!" ); |
| 2142 | |
| 2143 | SmallVector<llvm::Metadata *, 16> Elts; |
| 2144 | |
| 2145 | // First element is always return type. For 'void' functions it is NULL. |
| 2146 | Elts.push_back(Elt: Args[0]); |
| 2147 | |
| 2148 | const bool HasExplicitObjectParameter = ThisPtr.isNull(); |
| 2149 | |
| 2150 | // "this" pointer is always first argument. For explicit "this" |
| 2151 | // parameters, it will already be in Args[1]. |
| 2152 | if (!HasExplicitObjectParameter) { |
| 2153 | llvm::DIType *ThisPtrType = getOrCreateType(Ty: ThisPtr, Fg: Unit); |
| 2154 | TypeCache[ThisPtr.getAsOpaquePtr()].reset(MD: ThisPtrType); |
| 2155 | ThisPtrType = |
| 2156 | DBuilder.createObjectPointerType(Ty: ThisPtrType, /*Implicit=*/true); |
| 2157 | Elts.push_back(Elt: ThisPtrType); |
| 2158 | } |
| 2159 | |
| 2160 | // Copy rest of the arguments. |
| 2161 | for (unsigned i = (SkipFirst ? 2 : 1), e = Args.size(); i < e; ++i) |
| 2162 | Elts.push_back(Elt: Args[i]); |
| 2163 | |
| 2164 | // Attach FlagObjectPointer to the explicit "this" parameter. |
| 2165 | if (HasExplicitObjectParameter) { |
| 2166 | assert(Elts.size() >= 2 && Args.size() >= 2 && |
| 2167 | "Expected at least return type and object parameter." ); |
| 2168 | Elts[1] = DBuilder.createObjectPointerType(Ty: Args[1], /*Implicit=*/false); |
| 2169 | } |
| 2170 | |
| 2171 | llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elements: Elts); |
| 2172 | |
| 2173 | return DBuilder.createSubroutineType(ParameterTypes: EltTypeArray, Flags: OriginalFunc->getFlags(), |
| 2174 | CC: getDwarfCC(CC: Func->getCallConv())); |
| 2175 | } |
| 2176 | |
| 2177 | /// isFunctionLocalClass - Return true if CXXRecordDecl is defined |
| 2178 | /// inside a function. |
| 2179 | static bool isFunctionLocalClass(const CXXRecordDecl *RD) { |
| 2180 | if (const auto *NRD = dyn_cast<CXXRecordDecl>(Val: RD->getDeclContext())) |
| 2181 | return isFunctionLocalClass(RD: NRD); |
| 2182 | if (isa<FunctionDecl>(Val: RD->getDeclContext())) |
| 2183 | return true; |
| 2184 | return false; |
| 2185 | } |
| 2186 | |
| 2187 | llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction( |
| 2188 | const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) { |
| 2189 | bool IsCtorOrDtor = |
| 2190 | isa<CXXConstructorDecl>(Val: Method) || isa<CXXDestructorDecl>(Val: Method); |
| 2191 | |
| 2192 | StringRef MethodName = getFunctionName(FD: Method); |
| 2193 | llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit); |
| 2194 | |
| 2195 | // Since a single ctor/dtor corresponds to multiple functions, it doesn't |
| 2196 | // make sense to give a single ctor/dtor a linkage name. |
| 2197 | StringRef MethodLinkageName; |
| 2198 | // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional |
| 2199 | // property to use here. It may've been intended to model "is non-external |
| 2200 | // type" but misses cases of non-function-local but non-external classes such |
| 2201 | // as those in anonymous namespaces as well as the reverse - external types |
| 2202 | // that are function local, such as those in (non-local) inline functions. |
| 2203 | if (!IsCtorOrDtor && !isFunctionLocalClass(RD: Method->getParent())) |
| 2204 | MethodLinkageName = CGM.getMangledName(GD: Method); |
| 2205 | |
| 2206 | // Get the location for the method. |
| 2207 | llvm::DIFile *MethodDefUnit = nullptr; |
| 2208 | unsigned MethodLine = 0; |
| 2209 | if (!Method->isImplicit()) { |
| 2210 | MethodDefUnit = getOrCreateFile(Loc: Method->getLocation()); |
| 2211 | MethodLine = getLineNumber(Loc: Method->getLocation()); |
| 2212 | } |
| 2213 | |
| 2214 | // Collect virtual method info. |
| 2215 | llvm::DIType *ContainingType = nullptr; |
| 2216 | unsigned VIndex = 0; |
| 2217 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 2218 | llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; |
| 2219 | int ThisAdjustment = 0; |
| 2220 | |
| 2221 | if (VTableContextBase::hasVtableSlot(MD: Method)) { |
| 2222 | if (Method->isPureVirtual()) |
| 2223 | SPFlags |= llvm::DISubprogram::SPFlagPureVirtual; |
| 2224 | else |
| 2225 | SPFlags |= llvm::DISubprogram::SPFlagVirtual; |
| 2226 | |
| 2227 | if (CGM.getTarget().getCXXABI().isItaniumFamily()) { |
| 2228 | // It doesn't make sense to give a virtual destructor a vtable index, |
| 2229 | // since a single destructor has two entries in the vtable. |
| 2230 | if (!isa<CXXDestructorDecl>(Val: Method)) |
| 2231 | VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD: Method); |
| 2232 | } else { |
| 2233 | // Emit MS ABI vftable information. There is only one entry for the |
| 2234 | // deleting dtor. |
| 2235 | const auto *DD = dyn_cast<CXXDestructorDecl>(Val: Method); |
| 2236 | GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method); |
| 2237 | MethodVFTableLocation ML = |
| 2238 | CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); |
| 2239 | VIndex = ML.Index; |
| 2240 | |
| 2241 | // CodeView only records the vftable offset in the class that introduces |
| 2242 | // the virtual method. This is possible because, unlike Itanium, the MS |
| 2243 | // C++ ABI does not include all virtual methods from non-primary bases in |
| 2244 | // the vtable for the most derived class. For example, if C inherits from |
| 2245 | // A and B, C's primary vftable will not include B's virtual methods. |
| 2246 | if (Method->size_overridden_methods() == 0) |
| 2247 | Flags |= llvm::DINode::FlagIntroducedVirtual; |
| 2248 | |
| 2249 | // The 'this' adjustment accounts for both the virtual and non-virtual |
| 2250 | // portions of the adjustment. Presumably the debugger only uses it when |
| 2251 | // it knows the dynamic type of an object. |
| 2252 | ThisAdjustment = CGM.getCXXABI() |
| 2253 | .getVirtualFunctionPrologueThisAdjustment(GD) |
| 2254 | .getQuantity(); |
| 2255 | } |
| 2256 | ContainingType = RecordTy; |
| 2257 | } |
| 2258 | |
| 2259 | if (Method->getCanonicalDecl()->isDeleted()) |
| 2260 | SPFlags |= llvm::DISubprogram::SPFlagDeleted; |
| 2261 | |
| 2262 | if (Method->isNoReturn()) |
| 2263 | Flags |= llvm::DINode::FlagNoReturn; |
| 2264 | |
| 2265 | if (Method->isStatic()) |
| 2266 | Flags |= llvm::DINode::FlagStaticMember; |
| 2267 | if (Method->isImplicit()) |
| 2268 | Flags |= llvm::DINode::FlagArtificial; |
| 2269 | Flags |= getAccessFlag(Access: Method->getAccess(), RD: Method->getParent()); |
| 2270 | if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Val: Method)) { |
| 2271 | if (CXXC->isExplicit()) |
| 2272 | Flags |= llvm::DINode::FlagExplicit; |
| 2273 | } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Val: Method)) { |
| 2274 | if (CXXC->isExplicit()) |
| 2275 | Flags |= llvm::DINode::FlagExplicit; |
| 2276 | } |
| 2277 | if (Method->hasPrototype()) |
| 2278 | Flags |= llvm::DINode::FlagPrototyped; |
| 2279 | if (Method->getRefQualifier() == RQ_LValue) |
| 2280 | Flags |= llvm::DINode::FlagLValueReference; |
| 2281 | if (Method->getRefQualifier() == RQ_RValue) |
| 2282 | Flags |= llvm::DINode::FlagRValueReference; |
| 2283 | if (!Method->isExternallyVisible()) |
| 2284 | SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; |
| 2285 | if (CGM.getLangOpts().Optimize) |
| 2286 | SPFlags |= llvm::DISubprogram::SPFlagOptimized; |
| 2287 | |
| 2288 | // In this debug mode, emit type info for a class when its constructor type |
| 2289 | // info is emitted. |
| 2290 | if (DebugKind == llvm::codegenoptions::DebugInfoConstructor) |
| 2291 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: Method)) |
| 2292 | completeUnusedClass(D: *CD->getParent()); |
| 2293 | |
| 2294 | llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(FD: Method, Unit); |
| 2295 | llvm::DISubprogram *SP = DBuilder.createMethod( |
| 2296 | Scope: RecordTy, Name: MethodName, LinkageName: MethodLinkageName, File: MethodDefUnit, LineNo: MethodLine, |
| 2297 | Ty: MethodTy, VTableIndex: VIndex, ThisAdjustment, VTableHolder: ContainingType, Flags, SPFlags, |
| 2298 | TParams: TParamsArray.get(), /*ThrownTypes*/ nullptr, |
| 2299 | UseKeyInstructions: CGM.getCodeGenOpts().DebugKeyInstructions); |
| 2300 | |
| 2301 | SPCache[Method->getCanonicalDecl()].reset(MD: SP); |
| 2302 | |
| 2303 | return SP; |
| 2304 | } |
| 2305 | |
| 2306 | void CGDebugInfo::CollectCXXMemberFunctions( |
| 2307 | const CXXRecordDecl *RD, llvm::DIFile *Unit, |
| 2308 | SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) { |
| 2309 | |
| 2310 | // Since we want more than just the individual member decls if we |
| 2311 | // have templated functions iterate over every declaration to gather |
| 2312 | // the functions. |
| 2313 | for (const auto *I : RD->decls()) { |
| 2314 | const auto *Method = dyn_cast<CXXMethodDecl>(Val: I); |
| 2315 | // If the member is implicit, don't add it to the member list. This avoids |
| 2316 | // the member being added to type units by LLVM, while still allowing it |
| 2317 | // to be emitted into the type declaration/reference inside the compile |
| 2318 | // unit. |
| 2319 | // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp. |
| 2320 | // FIXME: Handle Using(Shadow?)Decls here to create |
| 2321 | // DW_TAG_imported_declarations inside the class for base decls brought into |
| 2322 | // derived classes. GDB doesn't seem to notice/leverage these when I tried |
| 2323 | // it, so I'm not rushing to fix this. (GCC seems to produce them, if |
| 2324 | // referenced) |
| 2325 | if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>()) |
| 2326 | continue; |
| 2327 | |
| 2328 | if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType()) |
| 2329 | continue; |
| 2330 | |
| 2331 | // Reuse the existing member function declaration if it exists. |
| 2332 | // It may be associated with the declaration of the type & should be |
| 2333 | // reused as we're building the definition. |
| 2334 | // |
| 2335 | // This situation can arise in the vtable-based debug info reduction where |
| 2336 | // implicit members are emitted in a non-vtable TU. |
| 2337 | auto MI = SPCache.find(Val: Method->getCanonicalDecl()); |
| 2338 | EltTys.push_back(Elt: MI == SPCache.end() |
| 2339 | ? CreateCXXMemberFunction(Method, Unit, RecordTy) |
| 2340 | : static_cast<llvm::Metadata *>(MI->second)); |
| 2341 | } |
| 2342 | } |
| 2343 | |
| 2344 | void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit, |
| 2345 | SmallVectorImpl<llvm::Metadata *> &EltTys, |
| 2346 | llvm::DIType *RecordTy) { |
| 2347 | llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes; |
| 2348 | CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, Bases: RD->bases(), SeenTypes, |
| 2349 | StartingFlags: llvm::DINode::FlagZero); |
| 2350 | |
| 2351 | // If we are generating CodeView debug info, we also need to emit records for |
| 2352 | // indirect virtual base classes. |
| 2353 | if (CGM.getCodeGenOpts().EmitCodeView) { |
| 2354 | CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, Bases: RD->vbases(), SeenTypes, |
| 2355 | StartingFlags: llvm::DINode::FlagIndirectVirtualBase); |
| 2356 | } |
| 2357 | } |
| 2358 | |
| 2359 | void CGDebugInfo::CollectCXXBasesAux( |
| 2360 | const CXXRecordDecl *RD, llvm::DIFile *Unit, |
| 2361 | SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy, |
| 2362 | const CXXRecordDecl::base_class_const_range &Bases, |
| 2363 | llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes, |
| 2364 | llvm::DINode::DIFlags StartingFlags) { |
| 2365 | const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(D: RD); |
| 2366 | for (const auto &BI : Bases) { |
| 2367 | const auto *Base = |
| 2368 | cast<CXXRecordDecl>(Val: BI.getType()->castAs<RecordType>()->getDecl()); |
| 2369 | if (!SeenTypes.insert(V: Base).second) |
| 2370 | continue; |
| 2371 | auto *BaseTy = getOrCreateType(Ty: BI.getType(), Fg: Unit); |
| 2372 | llvm::DINode::DIFlags BFlags = StartingFlags; |
| 2373 | uint64_t BaseOffset; |
| 2374 | uint32_t VBPtrOffset = 0; |
| 2375 | |
| 2376 | if (BI.isVirtual()) { |
| 2377 | if (CGM.getTarget().getCXXABI().isItaniumFamily()) { |
| 2378 | // virtual base offset offset is -ve. The code generator emits dwarf |
| 2379 | // expression where it expects +ve number. |
| 2380 | BaseOffset = 0 - CGM.getItaniumVTableContext() |
| 2381 | .getVirtualBaseOffsetOffset(RD, VBase: Base) |
| 2382 | .getQuantity(); |
| 2383 | } else { |
| 2384 | // In the MS ABI, store the vbtable offset, which is analogous to the |
| 2385 | // vbase offset offset in Itanium. |
| 2386 | BaseOffset = |
| 2387 | 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(Derived: RD, VBase: Base); |
| 2388 | VBPtrOffset = CGM.getContext() |
| 2389 | .getASTRecordLayout(D: RD) |
| 2390 | .getVBPtrOffset() |
| 2391 | .getQuantity(); |
| 2392 | } |
| 2393 | BFlags |= llvm::DINode::FlagVirtual; |
| 2394 | } else |
| 2395 | BaseOffset = CGM.getContext().toBits(CharSize: RL.getBaseClassOffset(Base)); |
| 2396 | // FIXME: Inconsistent units for BaseOffset. It is in bytes when |
| 2397 | // BI->isVirtual() and bits when not. |
| 2398 | |
| 2399 | BFlags |= getAccessFlag(Access: BI.getAccessSpecifier(), RD); |
| 2400 | llvm::DIType *DTy = DBuilder.createInheritance(Ty: RecordTy, BaseTy, BaseOffset, |
| 2401 | VBPtrOffset, Flags: BFlags); |
| 2402 | EltTys.push_back(Elt: DTy); |
| 2403 | } |
| 2404 | } |
| 2405 | |
| 2406 | llvm::DINodeArray |
| 2407 | CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs, |
| 2408 | llvm::DIFile *Unit) { |
| 2409 | if (!OArgs) |
| 2410 | return llvm::DINodeArray(); |
| 2411 | TemplateArgs &Args = *OArgs; |
| 2412 | SmallVector<llvm::Metadata *, 16> TemplateParams; |
| 2413 | for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) { |
| 2414 | const TemplateArgument &TA = Args.Args[i]; |
| 2415 | StringRef Name; |
| 2416 | const bool defaultParameter = TA.getIsDefaulted(); |
| 2417 | if (Args.TList) |
| 2418 | Name = Args.TList->getParam(Idx: i)->getName(); |
| 2419 | |
| 2420 | switch (TA.getKind()) { |
| 2421 | case TemplateArgument::Type: { |
| 2422 | llvm::DIType *TTy = getOrCreateType(Ty: TA.getAsType(), Fg: Unit); |
| 2423 | TemplateParams.push_back(Elt: DBuilder.createTemplateTypeParameter( |
| 2424 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter)); |
| 2425 | |
| 2426 | } break; |
| 2427 | case TemplateArgument::Integral: { |
| 2428 | llvm::DIType *TTy = getOrCreateType(Ty: TA.getIntegralType(), Fg: Unit); |
| 2429 | TemplateParams.push_back(Elt: DBuilder.createTemplateValueParameter( |
| 2430 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter, |
| 2431 | Val: llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: TA.getAsIntegral()))); |
| 2432 | } break; |
| 2433 | case TemplateArgument::Declaration: { |
| 2434 | const ValueDecl *D = TA.getAsDecl(); |
| 2435 | QualType T = TA.getParamTypeForDecl().getDesugaredType(Context: CGM.getContext()); |
| 2436 | llvm::DIType *TTy = getOrCreateType(Ty: T, Fg: Unit); |
| 2437 | llvm::Constant *V = nullptr; |
| 2438 | // Skip retrieve the value if that template parameter has cuda device |
| 2439 | // attribute, i.e. that value is not available at the host side. |
| 2440 | if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice || |
| 2441 | !D->hasAttr<CUDADeviceAttr>()) { |
| 2442 | // Variable pointer template parameters have a value that is the address |
| 2443 | // of the variable. |
| 2444 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
| 2445 | V = CGM.GetAddrOfGlobalVar(D: VD); |
| 2446 | // Member function pointers have special support for building them, |
| 2447 | // though this is currently unsupported in LLVM CodeGen. |
| 2448 | else if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D); |
| 2449 | MD && MD->isImplicitObjectMemberFunction()) |
| 2450 | V = CGM.getCXXABI().EmitMemberFunctionPointer(MD); |
| 2451 | else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
| 2452 | V = CGM.GetAddrOfFunction(GD: FD); |
| 2453 | // Member data pointers have special handling too to compute the fixed |
| 2454 | // offset within the object. |
| 2455 | else if (const auto *MPT = |
| 2456 | dyn_cast<MemberPointerType>(Val: T.getTypePtr())) { |
| 2457 | // These five lines (& possibly the above member function pointer |
| 2458 | // handling) might be able to be refactored to use similar code in |
| 2459 | // CodeGenModule::getMemberPointerConstant |
| 2460 | uint64_t fieldOffset = CGM.getContext().getFieldOffset(FD: D); |
| 2461 | CharUnits chars = |
| 2462 | CGM.getContext().toCharUnitsFromBits(BitSize: (int64_t)fieldOffset); |
| 2463 | V = CGM.getCXXABI().EmitMemberDataPointer(MPT, offset: chars); |
| 2464 | } else if (const auto *GD = dyn_cast<MSGuidDecl>(Val: D)) { |
| 2465 | V = CGM.GetAddrOfMSGuidDecl(GD).getPointer(); |
| 2466 | } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: D)) { |
| 2467 | if (T->isRecordType()) |
| 2468 | V = ConstantEmitter(CGM).emitAbstract( |
| 2469 | loc: SourceLocation(), value: TPO->getValue(), T: TPO->getType()); |
| 2470 | else |
| 2471 | V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer(); |
| 2472 | } |
| 2473 | assert(V && "Failed to find template parameter pointer" ); |
| 2474 | V = V->stripPointerCasts(); |
| 2475 | } |
| 2476 | TemplateParams.push_back(Elt: DBuilder.createTemplateValueParameter( |
| 2477 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter, Val: cast_or_null<llvm::Constant>(Val: V))); |
| 2478 | } break; |
| 2479 | case TemplateArgument::NullPtr: { |
| 2480 | QualType T = TA.getNullPtrType(); |
| 2481 | llvm::DIType *TTy = getOrCreateType(Ty: T, Fg: Unit); |
| 2482 | llvm::Constant *V = nullptr; |
| 2483 | // Special case member data pointer null values since they're actually -1 |
| 2484 | // instead of zero. |
| 2485 | if (const auto *MPT = dyn_cast<MemberPointerType>(Val: T.getTypePtr())) |
| 2486 | // But treat member function pointers as simple zero integers because |
| 2487 | // it's easier than having a special case in LLVM's CodeGen. If LLVM |
| 2488 | // CodeGen grows handling for values of non-null member function |
| 2489 | // pointers then perhaps we could remove this special case and rely on |
| 2490 | // EmitNullMemberPointer for member function pointers. |
| 2491 | if (MPT->isMemberDataPointer()) |
| 2492 | V = CGM.getCXXABI().EmitNullMemberPointer(MPT); |
| 2493 | if (!V) |
| 2494 | V = llvm::ConstantInt::get(Ty: CGM.Int8Ty, V: 0); |
| 2495 | TemplateParams.push_back(Elt: DBuilder.createTemplateValueParameter( |
| 2496 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter, Val: V)); |
| 2497 | } break; |
| 2498 | case TemplateArgument::StructuralValue: { |
| 2499 | QualType T = TA.getStructuralValueType(); |
| 2500 | llvm::DIType *TTy = getOrCreateType(Ty: T, Fg: Unit); |
| 2501 | llvm::Constant *V = ConstantEmitter(CGM).emitAbstract( |
| 2502 | loc: SourceLocation(), value: TA.getAsStructuralValue(), T); |
| 2503 | TemplateParams.push_back(Elt: DBuilder.createTemplateValueParameter( |
| 2504 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter, Val: V)); |
| 2505 | } break; |
| 2506 | case TemplateArgument::Template: { |
| 2507 | std::string QualName; |
| 2508 | llvm::raw_string_ostream OS(QualName); |
| 2509 | TA.getAsTemplate().getAsTemplateDecl()->printQualifiedName( |
| 2510 | OS, Policy: getPrintingPolicy()); |
| 2511 | TemplateParams.push_back(Elt: DBuilder.createTemplateTemplateParameter( |
| 2512 | Scope: TheCU, Name, Ty: nullptr, Val: QualName, IsDefault: defaultParameter)); |
| 2513 | break; |
| 2514 | } |
| 2515 | case TemplateArgument::Pack: |
| 2516 | TemplateParams.push_back(Elt: DBuilder.createTemplateParameterPack( |
| 2517 | Scope: TheCU, Name, Ty: nullptr, |
| 2518 | Val: CollectTemplateParams(OArgs: {{.TList: nullptr, .Args: TA.getPackAsArray()}}, Unit))); |
| 2519 | break; |
| 2520 | case TemplateArgument::Expression: { |
| 2521 | const Expr *E = TA.getAsExpr(); |
| 2522 | QualType T = E->getType(); |
| 2523 | if (E->isGLValue()) |
| 2524 | T = CGM.getContext().getLValueReferenceType(T); |
| 2525 | llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T); |
| 2526 | assert(V && "Expression in template argument isn't constant" ); |
| 2527 | llvm::DIType *TTy = getOrCreateType(Ty: T, Fg: Unit); |
| 2528 | TemplateParams.push_back(Elt: DBuilder.createTemplateValueParameter( |
| 2529 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter, Val: V->stripPointerCasts())); |
| 2530 | } break; |
| 2531 | // And the following should never occur: |
| 2532 | case TemplateArgument::TemplateExpansion: |
| 2533 | case TemplateArgument::Null: |
| 2534 | llvm_unreachable( |
| 2535 | "These argument types shouldn't exist in concrete types" ); |
| 2536 | } |
| 2537 | } |
| 2538 | return DBuilder.getOrCreateArray(Elements: TemplateParams); |
| 2539 | } |
| 2540 | |
| 2541 | std::optional<CGDebugInfo::TemplateArgs> |
| 2542 | CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const { |
| 2543 | if (FD->getTemplatedKind() == |
| 2544 | FunctionDecl::TK_FunctionTemplateSpecialization) { |
| 2545 | const TemplateParameterList *TList = FD->getTemplateSpecializationInfo() |
| 2546 | ->getTemplate() |
| 2547 | ->getTemplateParameters(); |
| 2548 | return {{.TList: TList, .Args: FD->getTemplateSpecializationArgs()->asArray()}}; |
| 2549 | } |
| 2550 | return std::nullopt; |
| 2551 | } |
| 2552 | std::optional<CGDebugInfo::TemplateArgs> |
| 2553 | CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const { |
| 2554 | // Always get the full list of parameters, not just the ones from the |
| 2555 | // specialization. A partial specialization may have fewer parameters than |
| 2556 | // there are arguments. |
| 2557 | auto *TS = dyn_cast<VarTemplateSpecializationDecl>(Val: VD); |
| 2558 | if (!TS) |
| 2559 | return std::nullopt; |
| 2560 | VarTemplateDecl *T = TS->getSpecializedTemplate(); |
| 2561 | const TemplateParameterList *TList = T->getTemplateParameters(); |
| 2562 | auto TA = TS->getTemplateArgs().asArray(); |
| 2563 | return {{.TList: TList, .Args: TA}}; |
| 2564 | } |
| 2565 | std::optional<CGDebugInfo::TemplateArgs> |
| 2566 | CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const { |
| 2567 | if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) { |
| 2568 | // Always get the full list of parameters, not just the ones from the |
| 2569 | // specialization. A partial specialization may have fewer parameters than |
| 2570 | // there are arguments. |
| 2571 | TemplateParameterList *TPList = |
| 2572 | TSpecial->getSpecializedTemplate()->getTemplateParameters(); |
| 2573 | const TemplateArgumentList &TAList = TSpecial->getTemplateArgs(); |
| 2574 | return {{.TList: TPList, .Args: TAList.asArray()}}; |
| 2575 | } |
| 2576 | return std::nullopt; |
| 2577 | } |
| 2578 | |
| 2579 | llvm::DINodeArray |
| 2580 | CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD, |
| 2581 | llvm::DIFile *Unit) { |
| 2582 | return CollectTemplateParams(OArgs: GetTemplateArgs(FD), Unit); |
| 2583 | } |
| 2584 | |
| 2585 | llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL, |
| 2586 | llvm::DIFile *Unit) { |
| 2587 | return CollectTemplateParams(OArgs: GetTemplateArgs(VD: VL), Unit); |
| 2588 | } |
| 2589 | |
| 2590 | llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD, |
| 2591 | llvm::DIFile *Unit) { |
| 2592 | return CollectTemplateParams(OArgs: GetTemplateArgs(RD), Unit); |
| 2593 | } |
| 2594 | |
| 2595 | llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) { |
| 2596 | if (!D->hasAttr<BTFDeclTagAttr>()) |
| 2597 | return nullptr; |
| 2598 | |
| 2599 | SmallVector<llvm::Metadata *, 4> Annotations; |
| 2600 | for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) { |
| 2601 | llvm::Metadata *Ops[2] = { |
| 2602 | llvm::MDString::get(Context&: CGM.getLLVMContext(), Str: StringRef("btf_decl_tag" )), |
| 2603 | llvm::MDString::get(Context&: CGM.getLLVMContext(), Str: I->getBTFDeclTag())}; |
| 2604 | Annotations.push_back(Elt: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: Ops)); |
| 2605 | } |
| 2606 | return DBuilder.getOrCreateArray(Elements: Annotations); |
| 2607 | } |
| 2608 | |
| 2609 | llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) { |
| 2610 | if (VTablePtrType) |
| 2611 | return VTablePtrType; |
| 2612 | |
| 2613 | ASTContext &Context = CGM.getContext(); |
| 2614 | |
| 2615 | /* Function type */ |
| 2616 | llvm::Metadata *STy = getOrCreateType(Ty: Context.IntTy, Fg: Unit); |
| 2617 | llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(Elements: STy); |
| 2618 | llvm::DIType *SubTy = DBuilder.createSubroutineType(ParameterTypes: SElements); |
| 2619 | unsigned Size = Context.getTypeSize(T: Context.VoidPtrTy); |
| 2620 | unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace(); |
| 2621 | std::optional<unsigned> DWARFAddressSpace = |
| 2622 | CGM.getTarget().getDWARFAddressSpace(AddressSpace: VtblPtrAddressSpace); |
| 2623 | |
| 2624 | llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType( |
| 2625 | PointeeTy: SubTy, SizeInBits: Size, AlignInBits: 0, DWARFAddressSpace, Name: "__vtbl_ptr_type" ); |
| 2626 | VTablePtrType = DBuilder.createPointerType(PointeeTy: vtbl_ptr_type, SizeInBits: Size); |
| 2627 | return VTablePtrType; |
| 2628 | } |
| 2629 | |
| 2630 | StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { |
| 2631 | // Copy the gdb compatible name on the side and use its reference. |
| 2632 | return internString(A: "_vptr$" , B: RD->getNameAsString()); |
| 2633 | } |
| 2634 | |
| 2635 | // Emit symbol for the debugger that points to the vtable address for |
| 2636 | // the given class. The symbol is named as '_vtable$'. |
| 2637 | // The debugger does not need to know any details about the contents of the |
| 2638 | // vtable as it can work this out using its knowledge of the ABI and the |
| 2639 | // existing information in the DWARF. The type is assumed to be 'void *'. |
| 2640 | void CGDebugInfo::emitVTableSymbol(llvm::GlobalVariable *VTable, |
| 2641 | const CXXRecordDecl *RD) { |
| 2642 | if (!CGM.getTarget().getCXXABI().isItaniumFamily()) |
| 2643 | return; |
| 2644 | |
| 2645 | ASTContext &Context = CGM.getContext(); |
| 2646 | StringRef SymbolName = "_vtable$" ; |
| 2647 | SourceLocation Loc; |
| 2648 | QualType VoidPtr = Context.getPointerType(T: Context.VoidTy); |
| 2649 | |
| 2650 | // We deal with two different contexts: |
| 2651 | // - The type for the variable, which is part of the class that has the |
| 2652 | // vtable, is placed in the context of the DICompositeType metadata. |
| 2653 | // - The DIGlobalVariable for the vtable is put in the DICompileUnitScope. |
| 2654 | |
| 2655 | // The created non-member should be mark as 'artificial'. It will be |
| 2656 | // placed inside the scope of the C++ class/structure. |
| 2657 | llvm::DIScope *DContext = getContextDescriptor(Context: RD, Default: TheCU); |
| 2658 | auto *Ctxt = cast<llvm::DICompositeType>(Val: DContext); |
| 2659 | llvm::DIFile *Unit = getOrCreateFile(Loc); |
| 2660 | llvm::DIType *VTy = getOrCreateType(Ty: VoidPtr, Fg: Unit); |
| 2661 | llvm::DINode::DIFlags Flags = getAccessFlag(Access: AccessSpecifier::AS_private, RD) | |
| 2662 | llvm::DINode::FlagArtificial; |
| 2663 | auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5 |
| 2664 | ? llvm::dwarf::DW_TAG_variable |
| 2665 | : llvm::dwarf::DW_TAG_member; |
| 2666 | llvm::DIDerivedType *DT = DBuilder.createStaticMemberType( |
| 2667 | Scope: Ctxt, Name: SymbolName, File: Unit, /*LineNumber=*/LineNo: 0, Ty: VTy, Flags, |
| 2668 | /*Val=*/nullptr, Tag); |
| 2669 | |
| 2670 | // Use the same vtable pointer to global alignment for the symbol. |
| 2671 | unsigned PAlign = CGM.getVtableGlobalVarAlignment(); |
| 2672 | |
| 2673 | // The global variable is in the CU scope, and links back to the type it's |
| 2674 | // "within" via the declaration field. |
| 2675 | llvm::DIGlobalVariableExpression *GVE = |
| 2676 | DBuilder.createGlobalVariableExpression( |
| 2677 | Context: TheCU, Name: SymbolName, LinkageName: VTable->getName(), File: Unit, /*LineNo=*/0, |
| 2678 | Ty: getOrCreateType(Ty: VoidPtr, Fg: Unit), IsLocalToUnit: VTable->hasLocalLinkage(), |
| 2679 | /*isDefined=*/true, Expr: nullptr, Decl: DT, /*TemplateParameters=*/TemplateParams: nullptr, |
| 2680 | AlignInBits: PAlign); |
| 2681 | VTable->addDebugInfo(GV: GVE); |
| 2682 | } |
| 2683 | |
| 2684 | StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD, |
| 2685 | DynamicInitKind StubKind, |
| 2686 | llvm::Function *InitFn) { |
| 2687 | // If we're not emitting codeview, use the mangled name. For Itanium, this is |
| 2688 | // arbitrary. |
| 2689 | if (!CGM.getCodeGenOpts().EmitCodeView || |
| 2690 | StubKind == DynamicInitKind::GlobalArrayDestructor) |
| 2691 | return InitFn->getName(); |
| 2692 | |
| 2693 | // Print the normal qualified name for the variable, then break off the last |
| 2694 | // NNS, and add the appropriate other text. Clang always prints the global |
| 2695 | // variable name without template arguments, so we can use rsplit("::") and |
| 2696 | // then recombine the pieces. |
| 2697 | SmallString<128> QualifiedGV; |
| 2698 | StringRef Quals; |
| 2699 | StringRef GVName; |
| 2700 | { |
| 2701 | llvm::raw_svector_ostream OS(QualifiedGV); |
| 2702 | VD->printQualifiedName(OS, Policy: getPrintingPolicy()); |
| 2703 | std::tie(args&: Quals, args&: GVName) = OS.str().rsplit(Separator: "::" ); |
| 2704 | if (GVName.empty()) |
| 2705 | std::swap(a&: Quals, b&: GVName); |
| 2706 | } |
| 2707 | |
| 2708 | SmallString<128> InitName; |
| 2709 | llvm::raw_svector_ostream OS(InitName); |
| 2710 | if (!Quals.empty()) |
| 2711 | OS << Quals << "::" ; |
| 2712 | |
| 2713 | switch (StubKind) { |
| 2714 | case DynamicInitKind::NoStub: |
| 2715 | case DynamicInitKind::GlobalArrayDestructor: |
| 2716 | llvm_unreachable("not an initializer" ); |
| 2717 | case DynamicInitKind::Initializer: |
| 2718 | OS << "`dynamic initializer for '" ; |
| 2719 | break; |
| 2720 | case DynamicInitKind::AtExit: |
| 2721 | OS << "`dynamic atexit destructor for '" ; |
| 2722 | break; |
| 2723 | } |
| 2724 | |
| 2725 | OS << GVName; |
| 2726 | |
| 2727 | // Add any template specialization args. |
| 2728 | if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) { |
| 2729 | printTemplateArgumentList(OS, Args: VTpl->getTemplateArgs().asArray(), |
| 2730 | Policy: getPrintingPolicy()); |
| 2731 | } |
| 2732 | |
| 2733 | OS << '\''; |
| 2734 | |
| 2735 | return internString(A: OS.str()); |
| 2736 | } |
| 2737 | |
| 2738 | void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit, |
| 2739 | SmallVectorImpl<llvm::Metadata *> &EltTys) { |
| 2740 | // If this class is not dynamic then there is not any vtable info to collect. |
| 2741 | if (!RD->isDynamicClass()) |
| 2742 | return; |
| 2743 | |
| 2744 | // Don't emit any vtable shape or vptr info if this class doesn't have an |
| 2745 | // extendable vfptr. This can happen if the class doesn't have virtual |
| 2746 | // methods, or in the MS ABI if those virtual methods only come from virtually |
| 2747 | // inherited bases. |
| 2748 | const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(D: RD); |
| 2749 | if (!RL.hasExtendableVFPtr()) |
| 2750 | return; |
| 2751 | |
| 2752 | // CodeView needs to know how large the vtable of every dynamic class is, so |
| 2753 | // emit a special named pointer type into the element list. The vptr type |
| 2754 | // points to this type as well. |
| 2755 | llvm::DIType *VPtrTy = nullptr; |
| 2756 | bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView && |
| 2757 | CGM.getTarget().getCXXABI().isMicrosoft(); |
| 2758 | if (NeedVTableShape) { |
| 2759 | uint64_t PtrWidth = |
| 2760 | CGM.getContext().getTypeSize(T: CGM.getContext().VoidPtrTy); |
| 2761 | const VTableLayout &VFTLayout = |
| 2762 | CGM.getMicrosoftVTableContext().getVFTableLayout(RD, VFPtrOffset: CharUnits::Zero()); |
| 2763 | unsigned VSlotCount = |
| 2764 | VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData; |
| 2765 | unsigned VTableWidth = PtrWidth * VSlotCount; |
| 2766 | unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace(); |
| 2767 | std::optional<unsigned> DWARFAddressSpace = |
| 2768 | CGM.getTarget().getDWARFAddressSpace(AddressSpace: VtblPtrAddressSpace); |
| 2769 | |
| 2770 | // Create a very wide void* type and insert it directly in the element list. |
| 2771 | llvm::DIType *VTableType = DBuilder.createPointerType( |
| 2772 | PointeeTy: nullptr, SizeInBits: VTableWidth, AlignInBits: 0, DWARFAddressSpace, Name: "__vtbl_ptr_type" ); |
| 2773 | EltTys.push_back(Elt: VTableType); |
| 2774 | |
| 2775 | // The vptr is a pointer to this special vtable type. |
| 2776 | VPtrTy = DBuilder.createPointerType(PointeeTy: VTableType, SizeInBits: PtrWidth); |
| 2777 | } |
| 2778 | |
| 2779 | // If there is a primary base then the artificial vptr member lives there. |
| 2780 | if (RL.getPrimaryBase()) |
| 2781 | return; |
| 2782 | |
| 2783 | if (!VPtrTy) |
| 2784 | VPtrTy = getOrCreateVTablePtrType(Unit); |
| 2785 | |
| 2786 | unsigned Size = CGM.getContext().getTypeSize(T: CGM.getContext().VoidPtrTy); |
| 2787 | llvm::DIType *VPtrMember = |
| 2788 | DBuilder.createMemberType(Scope: Unit, Name: getVTableName(RD), File: Unit, LineNo: 0, SizeInBits: Size, AlignInBits: 0, OffsetInBits: 0, |
| 2789 | Flags: llvm::DINode::FlagArtificial, Ty: VPtrTy); |
| 2790 | EltTys.push_back(Elt: VPtrMember); |
| 2791 | } |
| 2792 | |
| 2793 | llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy, |
| 2794 | SourceLocation Loc) { |
| 2795 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 2796 | llvm::DIType *T = getOrCreateType(Ty: RTy, Fg: getOrCreateFile(Loc)); |
| 2797 | return T; |
| 2798 | } |
| 2799 | |
| 2800 | llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D, |
| 2801 | SourceLocation Loc) { |
| 2802 | return getOrCreateStandaloneType(Ty: D, Loc); |
| 2803 | } |
| 2804 | |
| 2805 | llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D, |
| 2806 | SourceLocation Loc) { |
| 2807 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 2808 | assert(!D.isNull() && "null type" ); |
| 2809 | llvm::DIType *T = getOrCreateType(Ty: D, Fg: getOrCreateFile(Loc)); |
| 2810 | assert(T && "could not create debug info for type" ); |
| 2811 | |
| 2812 | RetainedTypes.push_back(x: D.getAsOpaquePtr()); |
| 2813 | return T; |
| 2814 | } |
| 2815 | |
| 2816 | void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI, |
| 2817 | QualType AllocatedTy, |
| 2818 | SourceLocation Loc) { |
| 2819 | if (CGM.getCodeGenOpts().getDebugInfo() <= |
| 2820 | llvm::codegenoptions::DebugLineTablesOnly) |
| 2821 | return; |
| 2822 | llvm::MDNode *node; |
| 2823 | if (AllocatedTy->isVoidType()) |
| 2824 | node = llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: {}); |
| 2825 | else |
| 2826 | node = getOrCreateType(Ty: AllocatedTy, Fg: getOrCreateFile(Loc)); |
| 2827 | |
| 2828 | CI->setMetadata(Kind: "heapallocsite" , Node: node); |
| 2829 | } |
| 2830 | |
| 2831 | void CGDebugInfo::completeType(const EnumDecl *ED) { |
| 2832 | if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
| 2833 | return; |
| 2834 | QualType Ty = CGM.getContext().getEnumType(Decl: ED); |
| 2835 | void *TyPtr = Ty.getAsOpaquePtr(); |
| 2836 | auto I = TypeCache.find(Val: TyPtr); |
| 2837 | if (I == TypeCache.end() || !cast<llvm::DIType>(Val&: I->second)->isForwardDecl()) |
| 2838 | return; |
| 2839 | llvm::DIType *Res = CreateTypeDefinition(Ty: Ty->castAs<EnumType>()); |
| 2840 | assert(!Res->isForwardDecl()); |
| 2841 | TypeCache[TyPtr].reset(MD: Res); |
| 2842 | } |
| 2843 | |
| 2844 | void CGDebugInfo::completeType(const RecordDecl *RD) { |
| 2845 | if (DebugKind > llvm::codegenoptions::LimitedDebugInfo || |
| 2846 | !CGM.getLangOpts().CPlusPlus) |
| 2847 | completeRequiredType(RD); |
| 2848 | } |
| 2849 | |
| 2850 | /// Return true if the class or any of its methods are marked dllimport. |
| 2851 | static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) { |
| 2852 | if (RD->hasAttr<DLLImportAttr>()) |
| 2853 | return true; |
| 2854 | for (const CXXMethodDecl *MD : RD->methods()) |
| 2855 | if (MD->hasAttr<DLLImportAttr>()) |
| 2856 | return true; |
| 2857 | return false; |
| 2858 | } |
| 2859 | |
| 2860 | /// Does a type definition exist in an imported clang module? |
| 2861 | static bool isDefinedInClangModule(const RecordDecl *RD) { |
| 2862 | // Only definitions that where imported from an AST file come from a module. |
| 2863 | if (!RD || !RD->isFromASTFile()) |
| 2864 | return false; |
| 2865 | // Anonymous entities cannot be addressed. Treat them as not from module. |
| 2866 | if (!RD->isExternallyVisible() && RD->getName().empty()) |
| 2867 | return false; |
| 2868 | if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(Val: RD)) { |
| 2869 | if (!CXXDecl->isCompleteDefinition()) |
| 2870 | return false; |
| 2871 | // Check wether RD is a template. |
| 2872 | auto TemplateKind = CXXDecl->getTemplateSpecializationKind(); |
| 2873 | if (TemplateKind != TSK_Undeclared) { |
| 2874 | // Unfortunately getOwningModule() isn't accurate enough to find the |
| 2875 | // owning module of a ClassTemplateSpecializationDecl that is inside a |
| 2876 | // namespace spanning multiple modules. |
| 2877 | bool Explicit = false; |
| 2878 | if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(Val: CXXDecl)) |
| 2879 | Explicit = TD->isExplicitInstantiationOrSpecialization(); |
| 2880 | if (!Explicit && CXXDecl->getEnclosingNamespaceContext()) |
| 2881 | return false; |
| 2882 | // This is a template, check the origin of the first member. |
| 2883 | if (CXXDecl->field_begin() == CXXDecl->field_end()) |
| 2884 | return TemplateKind == TSK_ExplicitInstantiationDeclaration; |
| 2885 | if (!CXXDecl->field_begin()->isFromASTFile()) |
| 2886 | return false; |
| 2887 | } |
| 2888 | } |
| 2889 | return true; |
| 2890 | } |
| 2891 | |
| 2892 | void CGDebugInfo::completeClassData(const RecordDecl *RD) { |
| 2893 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
| 2894 | if (CXXRD->isDynamicClass() && |
| 2895 | CGM.getVTableLinkage(RD: CXXRD) == |
| 2896 | llvm::GlobalValue::AvailableExternallyLinkage && |
| 2897 | !isClassOrMethodDLLImport(RD: CXXRD)) |
| 2898 | return; |
| 2899 | |
| 2900 | if (DebugTypeExtRefs && isDefinedInClangModule(RD: RD->getDefinition())) |
| 2901 | return; |
| 2902 | |
| 2903 | completeClass(RD); |
| 2904 | } |
| 2905 | |
| 2906 | void CGDebugInfo::completeClass(const RecordDecl *RD) { |
| 2907 | if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
| 2908 | return; |
| 2909 | QualType Ty = CGM.getContext().getRecordType(Decl: RD); |
| 2910 | void *TyPtr = Ty.getAsOpaquePtr(); |
| 2911 | auto I = TypeCache.find(Val: TyPtr); |
| 2912 | if (I != TypeCache.end() && !cast<llvm::DIType>(Val&: I->second)->isForwardDecl()) |
| 2913 | return; |
| 2914 | |
| 2915 | // We want the canonical definition of the structure to not |
| 2916 | // be the typedef. Since that would lead to circular typedef |
| 2917 | // metadata. |
| 2918 | auto [Res, PrefRes] = CreateTypeDefinition(Ty: Ty->castAs<RecordType>()); |
| 2919 | assert(!Res->isForwardDecl()); |
| 2920 | TypeCache[TyPtr].reset(MD: Res); |
| 2921 | } |
| 2922 | |
| 2923 | static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, |
| 2924 | CXXRecordDecl::method_iterator End) { |
| 2925 | for (CXXMethodDecl *MD : llvm::make_range(x: I, y: End)) |
| 2926 | if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction()) |
| 2927 | if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() && |
| 2928 | !MD->getMemberSpecializationInfo()->isExplicitSpecialization()) |
| 2929 | return true; |
| 2930 | return false; |
| 2931 | } |
| 2932 | |
| 2933 | static bool canUseCtorHoming(const CXXRecordDecl *RD) { |
| 2934 | // Constructor homing can be used for classes that cannnot be constructed |
| 2935 | // without emitting code for one of their constructors. This is classes that |
| 2936 | // don't have trivial or constexpr constructors, or can be created from |
| 2937 | // aggregate initialization. Also skip lambda objects because they don't call |
| 2938 | // constructors. |
| 2939 | |
| 2940 | // Skip this optimization if the class or any of its methods are marked |
| 2941 | // dllimport. |
| 2942 | if (isClassOrMethodDLLImport(RD)) |
| 2943 | return false; |
| 2944 | |
| 2945 | if (RD->isLambda() || RD->isAggregate() || |
| 2946 | RD->hasTrivialDefaultConstructor() || |
| 2947 | RD->hasConstexprNonCopyMoveConstructor()) |
| 2948 | return false; |
| 2949 | |
| 2950 | for (const CXXConstructorDecl *Ctor : RD->ctors()) { |
| 2951 | if (Ctor->isCopyOrMoveConstructor()) |
| 2952 | continue; |
| 2953 | if (!Ctor->isDeleted()) |
| 2954 | return true; |
| 2955 | } |
| 2956 | return false; |
| 2957 | } |
| 2958 | |
| 2959 | static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind, |
| 2960 | bool DebugTypeExtRefs, const RecordDecl *RD, |
| 2961 | const LangOptions &LangOpts) { |
| 2962 | if (DebugTypeExtRefs && isDefinedInClangModule(RD: RD->getDefinition())) |
| 2963 | return true; |
| 2964 | |
| 2965 | if (auto *ES = RD->getASTContext().getExternalSource()) |
| 2966 | if (ES->hasExternalDefinitions(D: RD) == ExternalASTSource::EK_Always) |
| 2967 | return true; |
| 2968 | |
| 2969 | // Only emit forward declarations in line tables only to keep debug info size |
| 2970 | // small. This only applies to CodeView, since we don't emit types in DWARF |
| 2971 | // line tables only. |
| 2972 | if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly) |
| 2973 | return true; |
| 2974 | |
| 2975 | if (DebugKind > llvm::codegenoptions::LimitedDebugInfo || |
| 2976 | RD->hasAttr<StandaloneDebugAttr>()) |
| 2977 | return false; |
| 2978 | |
| 2979 | if (!LangOpts.CPlusPlus) |
| 2980 | return false; |
| 2981 | |
| 2982 | if (!RD->isCompleteDefinitionRequired()) |
| 2983 | return true; |
| 2984 | |
| 2985 | const auto *CXXDecl = dyn_cast<CXXRecordDecl>(Val: RD); |
| 2986 | |
| 2987 | if (!CXXDecl) |
| 2988 | return false; |
| 2989 | |
| 2990 | // Only emit complete debug info for a dynamic class when its vtable is |
| 2991 | // emitted. However, Microsoft debuggers don't resolve type information |
| 2992 | // across DLL boundaries, so skip this optimization if the class or any of its |
| 2993 | // methods are marked dllimport. This isn't a complete solution, since objects |
| 2994 | // without any dllimport methods can be used in one DLL and constructed in |
| 2995 | // another, but it is the current behavior of LimitedDebugInfo. |
| 2996 | if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() && |
| 2997 | !isClassOrMethodDLLImport(RD: CXXDecl) && !CXXDecl->hasAttr<MSNoVTableAttr>()) |
| 2998 | return true; |
| 2999 | |
| 3000 | TemplateSpecializationKind Spec = TSK_Undeclared; |
| 3001 | if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) |
| 3002 | Spec = SD->getSpecializationKind(); |
| 3003 | |
| 3004 | if (Spec == TSK_ExplicitInstantiationDeclaration && |
| 3005 | hasExplicitMemberDefinition(I: CXXDecl->method_begin(), |
| 3006 | End: CXXDecl->method_end())) |
| 3007 | return true; |
| 3008 | |
| 3009 | // In constructor homing mode, only emit complete debug info for a class |
| 3010 | // when its constructor is emitted. |
| 3011 | if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) && |
| 3012 | canUseCtorHoming(RD: CXXDecl)) |
| 3013 | return true; |
| 3014 | |
| 3015 | return false; |
| 3016 | } |
| 3017 | |
| 3018 | void CGDebugInfo::completeRequiredType(const RecordDecl *RD) { |
| 3019 | if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, LangOpts: CGM.getLangOpts())) |
| 3020 | return; |
| 3021 | |
| 3022 | QualType Ty = CGM.getContext().getRecordType(Decl: RD); |
| 3023 | llvm::DIType *T = getTypeOrNull(Ty); |
| 3024 | if (T && T->isForwardDecl()) |
| 3025 | completeClassData(RD); |
| 3026 | } |
| 3027 | |
| 3028 | llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) { |
| 3029 | RecordDecl *RD = Ty->getDecl(); |
| 3030 | llvm::DIType *T = cast_or_null<llvm::DIType>(Val: getTypeOrNull(QualType(Ty, 0))); |
| 3031 | if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, |
| 3032 | LangOpts: CGM.getLangOpts())) { |
| 3033 | if (!T) |
| 3034 | T = getOrCreateRecordFwdDecl(Ty, Ctx: getDeclContextDescriptor(D: RD)); |
| 3035 | return T; |
| 3036 | } |
| 3037 | |
| 3038 | auto [Def, Pref] = CreateTypeDefinition(Ty); |
| 3039 | |
| 3040 | return Pref ? Pref : Def; |
| 3041 | } |
| 3042 | |
| 3043 | llvm::DIType *CGDebugInfo::GetPreferredNameType(const CXXRecordDecl *RD, |
| 3044 | llvm::DIFile *Unit) { |
| 3045 | if (!RD) |
| 3046 | return nullptr; |
| 3047 | |
| 3048 | auto const *PNA = RD->getAttr<PreferredNameAttr>(); |
| 3049 | if (!PNA) |
| 3050 | return nullptr; |
| 3051 | |
| 3052 | return getOrCreateType(Ty: PNA->getTypedefType(), Fg: Unit); |
| 3053 | } |
| 3054 | |
| 3055 | std::pair<llvm::DIType *, llvm::DIType *> |
| 3056 | CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) { |
| 3057 | RecordDecl *RD = Ty->getDecl(); |
| 3058 | |
| 3059 | // Get overall information about the record type for the debug info. |
| 3060 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: RD->getLocation()); |
| 3061 | |
| 3062 | // Records and classes and unions can all be recursive. To handle them, we |
| 3063 | // first generate a debug descriptor for the struct as a forward declaration. |
| 3064 | // Then (if it is a definition) we go through and get debug info for all of |
| 3065 | // its members. Finally, we create a descriptor for the complete type (which |
| 3066 | // may refer to the forward decl if the struct is recursive) and replace all |
| 3067 | // uses of the forward declaration with the final definition. |
| 3068 | llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty); |
| 3069 | |
| 3070 | const RecordDecl *D = RD->getDefinition(); |
| 3071 | if (!D || !D->isCompleteDefinition()) |
| 3072 | return {FwdDecl, nullptr}; |
| 3073 | |
| 3074 | if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(Val: RD)) |
| 3075 | CollectContainingType(RD: CXXDecl, CT: FwdDecl); |
| 3076 | |
| 3077 | // Push the struct on region stack. |
| 3078 | LexicalBlockStack.emplace_back(args: &*FwdDecl); |
| 3079 | RegionMap[Ty->getDecl()].reset(MD: FwdDecl); |
| 3080 | |
| 3081 | // Convert all the elements. |
| 3082 | SmallVector<llvm::Metadata *, 16> EltTys; |
| 3083 | // what about nested types? |
| 3084 | |
| 3085 | // Note: The split of CXXDecl information here is intentional, the |
| 3086 | // gdb tests will depend on a certain ordering at printout. The debug |
| 3087 | // information offsets are still correct if we merge them all together |
| 3088 | // though. |
| 3089 | const auto *CXXDecl = dyn_cast<CXXRecordDecl>(Val: RD); |
| 3090 | if (CXXDecl) { |
| 3091 | CollectCXXBases(RD: CXXDecl, Unit: DefUnit, EltTys, RecordTy: FwdDecl); |
| 3092 | CollectVTableInfo(RD: CXXDecl, Unit: DefUnit, EltTys); |
| 3093 | } |
| 3094 | |
| 3095 | // Collect data fields (including static variables and any initializers). |
| 3096 | CollectRecordFields(record: RD, tunit: DefUnit, elements&: EltTys, RecordTy: FwdDecl); |
| 3097 | if (CXXDecl && !CGM.getCodeGenOpts().DebugOmitUnreferencedMethods) |
| 3098 | CollectCXXMemberFunctions(RD: CXXDecl, Unit: DefUnit, EltTys, RecordTy: FwdDecl); |
| 3099 | |
| 3100 | LexicalBlockStack.pop_back(); |
| 3101 | RegionMap.erase(Val: Ty->getDecl()); |
| 3102 | |
| 3103 | llvm::DINodeArray Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
| 3104 | DBuilder.replaceArrays(T&: FwdDecl, Elements); |
| 3105 | |
| 3106 | if (FwdDecl->isTemporary()) |
| 3107 | FwdDecl = |
| 3108 | llvm::MDNode::replaceWithPermanent(N: llvm::TempDICompositeType(FwdDecl)); |
| 3109 | |
| 3110 | RegionMap[Ty->getDecl()].reset(MD: FwdDecl); |
| 3111 | |
| 3112 | if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) |
| 3113 | if (auto *PrefDI = GetPreferredNameType(RD: CXXDecl, Unit: DefUnit)) |
| 3114 | return {FwdDecl, PrefDI}; |
| 3115 | |
| 3116 | return {FwdDecl, nullptr}; |
| 3117 | } |
| 3118 | |
| 3119 | llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty, |
| 3120 | llvm::DIFile *Unit) { |
| 3121 | // Ignore protocols. |
| 3122 | return getOrCreateType(Ty: Ty->getBaseType(), Fg: Unit); |
| 3123 | } |
| 3124 | |
| 3125 | llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty, |
| 3126 | llvm::DIFile *Unit) { |
| 3127 | // Ignore protocols. |
| 3128 | SourceLocation Loc = Ty->getDecl()->getLocation(); |
| 3129 | |
| 3130 | // Use Typedefs to represent ObjCTypeParamType. |
| 3131 | return DBuilder.createTypedef( |
| 3132 | Ty: getOrCreateType(Ty: Ty->getDecl()->getUnderlyingType(), Fg: Unit), |
| 3133 | Name: Ty->getDecl()->getName(), File: getOrCreateFile(Loc), LineNo: getLineNumber(Loc), |
| 3134 | Context: getDeclContextDescriptor(D: Ty->getDecl())); |
| 3135 | } |
| 3136 | |
| 3137 | /// \return true if Getter has the default name for the property PD. |
| 3138 | static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, |
| 3139 | const ObjCMethodDecl *Getter) { |
| 3140 | assert(PD); |
| 3141 | if (!Getter) |
| 3142 | return true; |
| 3143 | |
| 3144 | assert(Getter->getDeclName().isObjCZeroArgSelector()); |
| 3145 | return PD->getName() == |
| 3146 | Getter->getDeclName().getObjCSelector().getNameForSlot(argIndex: 0); |
| 3147 | } |
| 3148 | |
| 3149 | /// \return true if Setter has the default name for the property PD. |
| 3150 | static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, |
| 3151 | const ObjCMethodDecl *Setter) { |
| 3152 | assert(PD); |
| 3153 | if (!Setter) |
| 3154 | return true; |
| 3155 | |
| 3156 | assert(Setter->getDeclName().isObjCOneArgSelector()); |
| 3157 | return SelectorTable::constructSetterName(Name: PD->getName()) == |
| 3158 | Setter->getDeclName().getObjCSelector().getNameForSlot(argIndex: 0); |
| 3159 | } |
| 3160 | |
| 3161 | llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, |
| 3162 | llvm::DIFile *Unit) { |
| 3163 | ObjCInterfaceDecl *ID = Ty->getDecl(); |
| 3164 | if (!ID) |
| 3165 | return nullptr; |
| 3166 | |
| 3167 | auto RuntimeLang = |
| 3168 | static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage()); |
| 3169 | |
| 3170 | // Return a forward declaration if this type was imported from a clang module, |
| 3171 | // and this is not the compile unit with the implementation of the type (which |
| 3172 | // may contain hidden ivars). |
| 3173 | if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() && |
| 3174 | !ID->getImplementation()) |
| 3175 | return DBuilder.createForwardDecl( |
| 3176 | Tag: llvm::dwarf::DW_TAG_structure_type, Name: ID->getName(), |
| 3177 | Scope: getDeclContextDescriptor(D: ID), F: Unit, Line: 0, RuntimeLang); |
| 3178 | |
| 3179 | // Get overall information about the record type for the debug info. |
| 3180 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: ID->getLocation()); |
| 3181 | unsigned Line = getLineNumber(Loc: ID->getLocation()); |
| 3182 | |
| 3183 | // If this is just a forward declaration return a special forward-declaration |
| 3184 | // debug type since we won't be able to lay out the entire type. |
| 3185 | ObjCInterfaceDecl *Def = ID->getDefinition(); |
| 3186 | if (!Def || !Def->getImplementation()) { |
| 3187 | llvm::DIScope *Mod = getParentModuleOrNull(D: ID); |
| 3188 | llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType( |
| 3189 | Tag: llvm::dwarf::DW_TAG_structure_type, Name: ID->getName(), Scope: Mod ? Mod : TheCU, |
| 3190 | F: DefUnit, Line, RuntimeLang); |
| 3191 | ObjCInterfaceCache.push_back(Elt: ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit)); |
| 3192 | return FwdDecl; |
| 3193 | } |
| 3194 | |
| 3195 | return CreateTypeDefinition(Ty, F: Unit); |
| 3196 | } |
| 3197 | |
| 3198 | llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod, |
| 3199 | bool CreateSkeletonCU) { |
| 3200 | // Use the Module pointer as the key into the cache. This is a |
| 3201 | // nullptr if the "Module" is a PCH, which is safe because we don't |
| 3202 | // support chained PCH debug info, so there can only be a single PCH. |
| 3203 | const Module *M = Mod.getModuleOrNull(); |
| 3204 | auto ModRef = ModuleCache.find(Val: M); |
| 3205 | if (ModRef != ModuleCache.end()) |
| 3206 | return cast<llvm::DIModule>(Val&: ModRef->second); |
| 3207 | |
| 3208 | // Macro definitions that were defined with "-D" on the command line. |
| 3209 | SmallString<128> ConfigMacros; |
| 3210 | { |
| 3211 | llvm::raw_svector_ostream OS(ConfigMacros); |
| 3212 | const auto &PPOpts = CGM.getPreprocessorOpts(); |
| 3213 | unsigned I = 0; |
| 3214 | // Translate the macro definitions back into a command line. |
| 3215 | for (auto &M : PPOpts.Macros) { |
| 3216 | if (++I > 1) |
| 3217 | OS << " " ; |
| 3218 | const std::string &Macro = M.first; |
| 3219 | bool Undef = M.second; |
| 3220 | OS << "\"-" << (Undef ? 'U' : 'D'); |
| 3221 | for (char c : Macro) |
| 3222 | switch (c) { |
| 3223 | case '\\': |
| 3224 | OS << "\\\\" ; |
| 3225 | break; |
| 3226 | case '"': |
| 3227 | OS << "\\\"" ; |
| 3228 | break; |
| 3229 | default: |
| 3230 | OS << c; |
| 3231 | } |
| 3232 | OS << '\"'; |
| 3233 | } |
| 3234 | } |
| 3235 | |
| 3236 | bool IsRootModule = M ? !M->Parent : true; |
| 3237 | // When a module name is specified as -fmodule-name, that module gets a |
| 3238 | // clang::Module object, but it won't actually be built or imported; it will |
| 3239 | // be textual. |
| 3240 | if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M) |
| 3241 | assert(StringRef(M->Name).starts_with(CGM.getLangOpts().ModuleName) && |
| 3242 | "clang module without ASTFile must be specified by -fmodule-name" ); |
| 3243 | |
| 3244 | // Return a StringRef to the remapped Path. |
| 3245 | auto RemapPath = [this](StringRef Path) -> std::string { |
| 3246 | std::string Remapped = remapDIPath(Path); |
| 3247 | StringRef Relative(Remapped); |
| 3248 | StringRef CompDir = TheCU->getDirectory(); |
| 3249 | if (Relative.consume_front(Prefix: CompDir)) |
| 3250 | Relative.consume_front(Prefix: llvm::sys::path::get_separator()); |
| 3251 | |
| 3252 | return Relative.str(); |
| 3253 | }; |
| 3254 | |
| 3255 | if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) { |
| 3256 | // PCH files don't have a signature field in the control block, |
| 3257 | // but LLVM detects skeleton CUs by looking for a non-zero DWO id. |
| 3258 | // We use the lower 64 bits for debug info. |
| 3259 | |
| 3260 | uint64_t Signature = 0; |
| 3261 | if (const auto &ModSig = Mod.getSignature()) |
| 3262 | Signature = ModSig.truncatedValue(); |
| 3263 | else |
| 3264 | Signature = ~1ULL; |
| 3265 | |
| 3266 | llvm::DIBuilder DIB(CGM.getModule()); |
| 3267 | SmallString<0> PCM; |
| 3268 | if (!llvm::sys::path::is_absolute(path: Mod.getASTFile())) { |
| 3269 | if (CGM.getHeaderSearchOpts().ModuleFileHomeIsCwd) |
| 3270 | PCM = getCurrentDirname(); |
| 3271 | else |
| 3272 | PCM = Mod.getPath(); |
| 3273 | } |
| 3274 | llvm::sys::path::append(path&: PCM, a: Mod.getASTFile()); |
| 3275 | DIB.createCompileUnit( |
| 3276 | Lang: TheCU->getSourceLanguage(), |
| 3277 | // TODO: Support "Source" from external AST providers? |
| 3278 | File: DIB.createFile(Filename: Mod.getModuleName(), Directory: TheCU->getDirectory()), |
| 3279 | Producer: TheCU->getProducer(), isOptimized: false, Flags: StringRef(), RV: 0, SplitName: RemapPath(PCM), |
| 3280 | Kind: llvm::DICompileUnit::FullDebug, DWOId: Signature); |
| 3281 | DIB.finalize(); |
| 3282 | } |
| 3283 | |
| 3284 | llvm::DIModule *Parent = |
| 3285 | IsRootModule ? nullptr |
| 3286 | : getOrCreateModuleRef(Mod: ASTSourceDescriptor(*M->Parent), |
| 3287 | CreateSkeletonCU); |
| 3288 | std::string IncludePath = Mod.getPath().str(); |
| 3289 | llvm::DIModule *DIMod = |
| 3290 | DBuilder.createModule(Scope: Parent, Name: Mod.getModuleName(), ConfigurationMacros: ConfigMacros, |
| 3291 | IncludePath: RemapPath(IncludePath)); |
| 3292 | ModuleCache[M].reset(MD: DIMod); |
| 3293 | return DIMod; |
| 3294 | } |
| 3295 | |
| 3296 | llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty, |
| 3297 | llvm::DIFile *Unit) { |
| 3298 | ObjCInterfaceDecl *ID = Ty->getDecl(); |
| 3299 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: ID->getLocation()); |
| 3300 | unsigned Line = getLineNumber(Loc: ID->getLocation()); |
| 3301 | unsigned RuntimeLang = TheCU->getSourceLanguage(); |
| 3302 | |
| 3303 | // Bit size, align and offset of the type. |
| 3304 | uint64_t Size = CGM.getContext().getTypeSize(T: Ty); |
| 3305 | auto Align = getTypeAlignIfRequired(Ty, Ctx: CGM.getContext()); |
| 3306 | |
| 3307 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 3308 | if (ID->getImplementation()) |
| 3309 | Flags |= llvm::DINode::FlagObjcClassComplete; |
| 3310 | |
| 3311 | llvm::DIScope *Mod = getParentModuleOrNull(D: ID); |
| 3312 | llvm::DICompositeType *RealDecl = DBuilder.createStructType( |
| 3313 | Scope: Mod ? Mod : Unit, Name: ID->getName(), File: DefUnit, LineNumber: Line, SizeInBits: Size, AlignInBits: Align, Flags, |
| 3314 | DerivedFrom: nullptr, Elements: llvm::DINodeArray(), RunTimeLang: RuntimeLang); |
| 3315 | |
| 3316 | QualType QTy(Ty, 0); |
| 3317 | TypeCache[QTy.getAsOpaquePtr()].reset(MD: RealDecl); |
| 3318 | |
| 3319 | // Push the struct on region stack. |
| 3320 | LexicalBlockStack.emplace_back(args&: RealDecl); |
| 3321 | RegionMap[Ty->getDecl()].reset(MD: RealDecl); |
| 3322 | |
| 3323 | // Convert all the elements. |
| 3324 | SmallVector<llvm::Metadata *, 16> EltTys; |
| 3325 | |
| 3326 | ObjCInterfaceDecl *SClass = ID->getSuperClass(); |
| 3327 | if (SClass) { |
| 3328 | llvm::DIType *SClassTy = |
| 3329 | getOrCreateType(Ty: CGM.getContext().getObjCInterfaceType(Decl: SClass), Fg: Unit); |
| 3330 | if (!SClassTy) |
| 3331 | return nullptr; |
| 3332 | |
| 3333 | llvm::DIType *InhTag = DBuilder.createInheritance(Ty: RealDecl, BaseTy: SClassTy, BaseOffset: 0, VBPtrOffset: 0, |
| 3334 | Flags: llvm::DINode::FlagZero); |
| 3335 | EltTys.push_back(Elt: InhTag); |
| 3336 | } |
| 3337 | |
| 3338 | // Create entries for all of the properties. |
| 3339 | auto AddProperty = [&](const ObjCPropertyDecl *PD) { |
| 3340 | SourceLocation Loc = PD->getLocation(); |
| 3341 | llvm::DIFile *PUnit = getOrCreateFile(Loc); |
| 3342 | unsigned PLine = getLineNumber(Loc); |
| 3343 | ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); |
| 3344 | ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); |
| 3345 | llvm::MDNode *PropertyNode = DBuilder.createObjCProperty( |
| 3346 | Name: PD->getName(), File: PUnit, LineNumber: PLine, |
| 3347 | GetterName: hasDefaultGetterName(PD, Getter) ? "" |
| 3348 | : getSelectorName(S: PD->getGetterName()), |
| 3349 | SetterName: hasDefaultSetterName(PD, Setter) ? "" |
| 3350 | : getSelectorName(S: PD->getSetterName()), |
| 3351 | PropertyAttributes: PD->getPropertyAttributes(), Ty: getOrCreateType(Ty: PD->getType(), Fg: PUnit)); |
| 3352 | EltTys.push_back(Elt: PropertyNode); |
| 3353 | }; |
| 3354 | { |
| 3355 | // Use 'char' for the isClassProperty bit as DenseSet requires space for |
| 3356 | // empty/tombstone keys in the data type (and bool is too small for that). |
| 3357 | typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent; |
| 3358 | /// List of already emitted properties. Two distinct class and instance |
| 3359 | /// properties can share the same identifier (but not two instance |
| 3360 | /// properties or two class properties). |
| 3361 | llvm::DenseSet<IsClassAndIdent> PropertySet; |
| 3362 | /// Returns the IsClassAndIdent key for the given property. |
| 3363 | auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) { |
| 3364 | return std::make_pair(x: PD->isClassProperty(), y: PD->getIdentifier()); |
| 3365 | }; |
| 3366 | for (const ObjCCategoryDecl *ClassExt : ID->known_extensions()) |
| 3367 | for (auto *PD : ClassExt->properties()) { |
| 3368 | PropertySet.insert(V: GetIsClassAndIdent(PD)); |
| 3369 | AddProperty(PD); |
| 3370 | } |
| 3371 | for (const auto *PD : ID->properties()) { |
| 3372 | // Don't emit duplicate metadata for properties that were already in a |
| 3373 | // class extension. |
| 3374 | if (!PropertySet.insert(V: GetIsClassAndIdent(PD)).second) |
| 3375 | continue; |
| 3376 | AddProperty(PD); |
| 3377 | } |
| 3378 | } |
| 3379 | |
| 3380 | const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(D: ID); |
| 3381 | unsigned FieldNo = 0; |
| 3382 | for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; |
| 3383 | Field = Field->getNextIvar(), ++FieldNo) { |
| 3384 | llvm::DIType *FieldTy = getOrCreateType(Ty: Field->getType(), Fg: Unit); |
| 3385 | if (!FieldTy) |
| 3386 | return nullptr; |
| 3387 | |
| 3388 | StringRef FieldName = Field->getName(); |
| 3389 | |
| 3390 | // Ignore unnamed fields. |
| 3391 | if (FieldName.empty()) |
| 3392 | continue; |
| 3393 | |
| 3394 | // Get the location for the field. |
| 3395 | llvm::DIFile *FieldDefUnit = getOrCreateFile(Loc: Field->getLocation()); |
| 3396 | unsigned FieldLine = getLineNumber(Loc: Field->getLocation()); |
| 3397 | QualType FType = Field->getType(); |
| 3398 | uint64_t FieldSize = 0; |
| 3399 | uint32_t FieldAlign = 0; |
| 3400 | |
| 3401 | if (!FType->isIncompleteArrayType()) { |
| 3402 | |
| 3403 | // Bit size, align and offset of the type. |
| 3404 | FieldSize = Field->isBitField() ? Field->getBitWidthValue() |
| 3405 | : CGM.getContext().getTypeSize(T: FType); |
| 3406 | FieldAlign = getTypeAlignIfRequired(Ty: FType, Ctx: CGM.getContext()); |
| 3407 | } |
| 3408 | |
| 3409 | uint64_t FieldOffset; |
| 3410 | if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { |
| 3411 | // We don't know the runtime offset of an ivar if we're using the |
| 3412 | // non-fragile ABI. For bitfields, use the bit offset into the first |
| 3413 | // byte of storage of the bitfield. For other fields, use zero. |
| 3414 | if (Field->isBitField()) { |
| 3415 | FieldOffset = |
| 3416 | CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Ivar: Field); |
| 3417 | FieldOffset %= CGM.getContext().getCharWidth(); |
| 3418 | } else { |
| 3419 | FieldOffset = 0; |
| 3420 | } |
| 3421 | } else { |
| 3422 | FieldOffset = RL.getFieldOffset(FieldNo); |
| 3423 | } |
| 3424 | |
| 3425 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 3426 | if (Field->getAccessControl() == ObjCIvarDecl::Protected) |
| 3427 | Flags = llvm::DINode::FlagProtected; |
| 3428 | else if (Field->getAccessControl() == ObjCIvarDecl::Private) |
| 3429 | Flags = llvm::DINode::FlagPrivate; |
| 3430 | else if (Field->getAccessControl() == ObjCIvarDecl::Public) |
| 3431 | Flags = llvm::DINode::FlagPublic; |
| 3432 | |
| 3433 | if (Field->isBitField()) |
| 3434 | Flags |= llvm::DINode::FlagBitField; |
| 3435 | |
| 3436 | llvm::MDNode *PropertyNode = nullptr; |
| 3437 | if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { |
| 3438 | if (ObjCPropertyImplDecl *PImpD = |
| 3439 | ImpD->FindPropertyImplIvarDecl(ivarId: Field->getIdentifier())) { |
| 3440 | if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { |
| 3441 | SourceLocation Loc = PD->getLocation(); |
| 3442 | llvm::DIFile *PUnit = getOrCreateFile(Loc); |
| 3443 | unsigned PLine = getLineNumber(Loc); |
| 3444 | ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl(); |
| 3445 | ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl(); |
| 3446 | PropertyNode = DBuilder.createObjCProperty( |
| 3447 | Name: PD->getName(), File: PUnit, LineNumber: PLine, |
| 3448 | GetterName: hasDefaultGetterName(PD, Getter) |
| 3449 | ? "" |
| 3450 | : getSelectorName(S: PD->getGetterName()), |
| 3451 | SetterName: hasDefaultSetterName(PD, Setter) |
| 3452 | ? "" |
| 3453 | : getSelectorName(S: PD->getSetterName()), |
| 3454 | PropertyAttributes: PD->getPropertyAttributes(), |
| 3455 | Ty: getOrCreateType(Ty: PD->getType(), Fg: PUnit)); |
| 3456 | } |
| 3457 | } |
| 3458 | } |
| 3459 | FieldTy = DBuilder.createObjCIVar(Name: FieldName, File: FieldDefUnit, LineNo: FieldLine, |
| 3460 | SizeInBits: FieldSize, AlignInBits: FieldAlign, OffsetInBits: FieldOffset, Flags, |
| 3461 | Ty: FieldTy, PropertyNode); |
| 3462 | EltTys.push_back(Elt: FieldTy); |
| 3463 | } |
| 3464 | |
| 3465 | llvm::DINodeArray Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
| 3466 | DBuilder.replaceArrays(T&: RealDecl, Elements); |
| 3467 | |
| 3468 | LexicalBlockStack.pop_back(); |
| 3469 | return RealDecl; |
| 3470 | } |
| 3471 | |
| 3472 | llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty, |
| 3473 | llvm::DIFile *Unit) { |
| 3474 | if (Ty->isPackedVectorBoolType(ctx: CGM.getContext())) { |
| 3475 | // Boolean ext_vector_type(N) are special because their real element type |
| 3476 | // (bits of bit size) is not their Clang element type (_Bool of size byte). |
| 3477 | // For now, we pretend the boolean vector were actually a vector of bytes |
| 3478 | // (where each byte represents 8 bits of the actual vector). |
| 3479 | // FIXME Debug info should actually represent this proper as a vector mask |
| 3480 | // type. |
| 3481 | auto &Ctx = CGM.getContext(); |
| 3482 | uint64_t Size = CGM.getContext().getTypeSize(T: Ty); |
| 3483 | uint64_t NumVectorBytes = Size / Ctx.getCharWidth(); |
| 3484 | |
| 3485 | // Construct the vector of 'char' type. |
| 3486 | QualType CharVecTy = |
| 3487 | Ctx.getVectorType(VectorType: Ctx.CharTy, NumElts: NumVectorBytes, VecKind: VectorKind::Generic); |
| 3488 | return CreateType(Ty: CharVecTy->getAs<VectorType>(), Unit); |
| 3489 | } |
| 3490 | |
| 3491 | llvm::DIType *ElementTy = getOrCreateType(Ty: Ty->getElementType(), Fg: Unit); |
| 3492 | int64_t Count = Ty->getNumElements(); |
| 3493 | |
| 3494 | llvm::Metadata *Subscript; |
| 3495 | QualType QTy(Ty, 0); |
| 3496 | auto SizeExpr = SizeExprCache.find(Val: QTy); |
| 3497 | if (SizeExpr != SizeExprCache.end()) |
| 3498 | Subscript = DBuilder.getOrCreateSubrange( |
| 3499 | Count: SizeExpr->getSecond() /*count*/, LowerBound: nullptr /*lowerBound*/, |
| 3500 | UpperBound: nullptr /*upperBound*/, Stride: nullptr /*stride*/); |
| 3501 | else { |
| 3502 | auto *CountNode = |
| 3503 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
| 3504 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: Count ? Count : -1)); |
| 3505 | Subscript = DBuilder.getOrCreateSubrange( |
| 3506 | Count: CountNode /*count*/, LowerBound: nullptr /*lowerBound*/, UpperBound: nullptr /*upperBound*/, |
| 3507 | Stride: nullptr /*stride*/); |
| 3508 | } |
| 3509 | llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Elements: Subscript); |
| 3510 | |
| 3511 | uint64_t Size = CGM.getContext().getTypeSize(T: Ty); |
| 3512 | auto Align = getTypeAlignIfRequired(Ty, Ctx: CGM.getContext()); |
| 3513 | |
| 3514 | return DBuilder.createVectorType(Size, AlignInBits: Align, Ty: ElementTy, Subscripts: SubscriptArray); |
| 3515 | } |
| 3516 | |
| 3517 | llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty, |
| 3518 | llvm::DIFile *Unit) { |
| 3519 | // FIXME: Create another debug type for matrices |
| 3520 | // For the time being, it treats it like a nested ArrayType. |
| 3521 | |
| 3522 | llvm::DIType *ElementTy = getOrCreateType(Ty: Ty->getElementType(), Fg: Unit); |
| 3523 | uint64_t Size = CGM.getContext().getTypeSize(T: Ty); |
| 3524 | uint32_t Align = getTypeAlignIfRequired(Ty, Ctx: CGM.getContext()); |
| 3525 | |
| 3526 | // Create ranges for both dimensions. |
| 3527 | llvm::SmallVector<llvm::Metadata *, 2> Subscripts; |
| 3528 | auto *ColumnCountNode = |
| 3529 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
| 3530 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: Ty->getNumColumns())); |
| 3531 | auto *RowCountNode = |
| 3532 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
| 3533 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: Ty->getNumRows())); |
| 3534 | Subscripts.push_back(Elt: DBuilder.getOrCreateSubrange( |
| 3535 | Count: ColumnCountNode /*count*/, LowerBound: nullptr /*lowerBound*/, UpperBound: nullptr /*upperBound*/, |
| 3536 | Stride: nullptr /*stride*/)); |
| 3537 | Subscripts.push_back(Elt: DBuilder.getOrCreateSubrange( |
| 3538 | Count: RowCountNode /*count*/, LowerBound: nullptr /*lowerBound*/, UpperBound: nullptr /*upperBound*/, |
| 3539 | Stride: nullptr /*stride*/)); |
| 3540 | llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Elements: Subscripts); |
| 3541 | return DBuilder.createArrayType(Size, AlignInBits: Align, Ty: ElementTy, Subscripts: SubscriptArray); |
| 3542 | } |
| 3543 | |
| 3544 | llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) { |
| 3545 | uint64_t Size; |
| 3546 | uint32_t Align; |
| 3547 | |
| 3548 | // FIXME: make getTypeAlign() aware of VLAs and incomplete array types |
| 3549 | if (const auto *VAT = dyn_cast<VariableArrayType>(Val: Ty)) { |
| 3550 | Size = 0; |
| 3551 | Align = getTypeAlignIfRequired(Ty: CGM.getContext().getBaseElementType(VAT), |
| 3552 | Ctx: CGM.getContext()); |
| 3553 | } else if (Ty->isIncompleteArrayType()) { |
| 3554 | Size = 0; |
| 3555 | if (Ty->getElementType()->isIncompleteType()) |
| 3556 | Align = 0; |
| 3557 | else |
| 3558 | Align = getTypeAlignIfRequired(Ty: Ty->getElementType(), Ctx: CGM.getContext()); |
| 3559 | } else if (Ty->isIncompleteType()) { |
| 3560 | Size = 0; |
| 3561 | Align = 0; |
| 3562 | } else { |
| 3563 | // Size and align of the whole array, not the element type. |
| 3564 | Size = CGM.getContext().getTypeSize(T: Ty); |
| 3565 | Align = getTypeAlignIfRequired(Ty, Ctx: CGM.getContext()); |
| 3566 | } |
| 3567 | |
| 3568 | // Add the dimensions of the array. FIXME: This loses CV qualifiers from |
| 3569 | // interior arrays, do we care? Why aren't nested arrays represented the |
| 3570 | // obvious/recursive way? |
| 3571 | SmallVector<llvm::Metadata *, 8> Subscripts; |
| 3572 | QualType EltTy(Ty, 0); |
| 3573 | while ((Ty = dyn_cast<ArrayType>(Val&: EltTy))) { |
| 3574 | // If the number of elements is known, then count is that number. Otherwise, |
| 3575 | // it's -1. This allows us to represent a subrange with an array of 0 |
| 3576 | // elements, like this: |
| 3577 | // |
| 3578 | // struct foo { |
| 3579 | // int x[0]; |
| 3580 | // }; |
| 3581 | int64_t Count = -1; // Count == -1 is an unbounded array. |
| 3582 | if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: Ty)) |
| 3583 | Count = CAT->getZExtSize(); |
| 3584 | else if (const auto *VAT = dyn_cast<VariableArrayType>(Val: Ty)) { |
| 3585 | if (Expr *Size = VAT->getSizeExpr()) { |
| 3586 | Expr::EvalResult Result; |
| 3587 | if (Size->EvaluateAsInt(Result, Ctx: CGM.getContext())) |
| 3588 | Count = Result.Val.getInt().getExtValue(); |
| 3589 | } |
| 3590 | } |
| 3591 | |
| 3592 | auto SizeNode = SizeExprCache.find(Val: EltTy); |
| 3593 | if (SizeNode != SizeExprCache.end()) |
| 3594 | Subscripts.push_back(Elt: DBuilder.getOrCreateSubrange( |
| 3595 | Count: SizeNode->getSecond() /*count*/, LowerBound: nullptr /*lowerBound*/, |
| 3596 | UpperBound: nullptr /*upperBound*/, Stride: nullptr /*stride*/)); |
| 3597 | else { |
| 3598 | auto *CountNode = |
| 3599 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
| 3600 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: Count)); |
| 3601 | Subscripts.push_back(Elt: DBuilder.getOrCreateSubrange( |
| 3602 | Count: CountNode /*count*/, LowerBound: nullptr /*lowerBound*/, UpperBound: nullptr /*upperBound*/, |
| 3603 | Stride: nullptr /*stride*/)); |
| 3604 | } |
| 3605 | EltTy = Ty->getElementType(); |
| 3606 | } |
| 3607 | |
| 3608 | llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Elements: Subscripts); |
| 3609 | |
| 3610 | return DBuilder.createArrayType(Size, AlignInBits: Align, Ty: getOrCreateType(Ty: EltTy, Fg: Unit), |
| 3611 | Subscripts: SubscriptArray); |
| 3612 | } |
| 3613 | |
| 3614 | llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty, |
| 3615 | llvm::DIFile *Unit) { |
| 3616 | return CreatePointerLikeType(Tag: llvm::dwarf::DW_TAG_reference_type, Ty, |
| 3617 | PointeeTy: Ty->getPointeeType(), Unit); |
| 3618 | } |
| 3619 | |
| 3620 | llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty, |
| 3621 | llvm::DIFile *Unit) { |
| 3622 | llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type; |
| 3623 | // DW_TAG_rvalue_reference_type was introduced in DWARF 4. |
| 3624 | if (CGM.getCodeGenOpts().DebugStrictDwarf && |
| 3625 | CGM.getCodeGenOpts().DwarfVersion < 4) |
| 3626 | Tag = llvm::dwarf::DW_TAG_reference_type; |
| 3627 | |
| 3628 | return CreatePointerLikeType(Tag, Ty, PointeeTy: Ty->getPointeeType(), Unit); |
| 3629 | } |
| 3630 | |
| 3631 | llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty, |
| 3632 | llvm::DIFile *U) { |
| 3633 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 3634 | uint64_t Size = 0; |
| 3635 | |
| 3636 | if (!Ty->isIncompleteType()) { |
| 3637 | Size = CGM.getContext().getTypeSize(T: Ty); |
| 3638 | |
| 3639 | // Set the MS inheritance model. There is no flag for the unspecified model. |
| 3640 | if (CGM.getTarget().getCXXABI().isMicrosoft()) { |
| 3641 | switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) { |
| 3642 | case MSInheritanceModel::Single: |
| 3643 | Flags |= llvm::DINode::FlagSingleInheritance; |
| 3644 | break; |
| 3645 | case MSInheritanceModel::Multiple: |
| 3646 | Flags |= llvm::DINode::FlagMultipleInheritance; |
| 3647 | break; |
| 3648 | case MSInheritanceModel::Virtual: |
| 3649 | Flags |= llvm::DINode::FlagVirtualInheritance; |
| 3650 | break; |
| 3651 | case MSInheritanceModel::Unspecified: |
| 3652 | break; |
| 3653 | } |
| 3654 | } |
| 3655 | } |
| 3656 | |
| 3657 | llvm::DIType *ClassType = getOrCreateType( |
| 3658 | Ty: QualType(Ty->getMostRecentCXXRecordDecl()->getTypeForDecl(), 0), Fg: U); |
| 3659 | if (Ty->isMemberDataPointerType()) |
| 3660 | return DBuilder.createMemberPointerType( |
| 3661 | PointeeTy: getOrCreateType(Ty: Ty->getPointeeType(), Fg: U), Class: ClassType, SizeInBits: Size, /*Align=*/AlignInBits: 0, |
| 3662 | Flags); |
| 3663 | |
| 3664 | const FunctionProtoType *FPT = |
| 3665 | Ty->getPointeeType()->castAs<FunctionProtoType>(); |
| 3666 | return DBuilder.createMemberPointerType( |
| 3667 | PointeeTy: getOrCreateInstanceMethodType( |
| 3668 | ThisPtr: CXXMethodDecl::getThisType(FPT, Decl: Ty->getMostRecentCXXRecordDecl()), |
| 3669 | Func: FPT, Unit: U), |
| 3670 | Class: ClassType, SizeInBits: Size, /*Align=*/AlignInBits: 0, Flags); |
| 3671 | } |
| 3672 | |
| 3673 | llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) { |
| 3674 | auto *FromTy = getOrCreateType(Ty: Ty->getValueType(), Fg: U); |
| 3675 | return DBuilder.createQualifiedType(Tag: llvm::dwarf::DW_TAG_atomic_type, FromTy); |
| 3676 | } |
| 3677 | |
| 3678 | llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) { |
| 3679 | return getOrCreateType(Ty: Ty->getElementType(), Fg: U); |
| 3680 | } |
| 3681 | |
| 3682 | llvm::DIType *CGDebugInfo::CreateType(const HLSLAttributedResourceType *Ty, |
| 3683 | llvm::DIFile *U) { |
| 3684 | return getOrCreateType(Ty: Ty->getWrappedType(), Fg: U); |
| 3685 | } |
| 3686 | |
| 3687 | llvm::DIType *CGDebugInfo::CreateType(const HLSLInlineSpirvType *Ty, |
| 3688 | llvm::DIFile *U) { |
| 3689 | // Debug information unneeded. |
| 3690 | return nullptr; |
| 3691 | } |
| 3692 | |
| 3693 | llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) { |
| 3694 | const EnumDecl *ED = Ty->getDecl(); |
| 3695 | |
| 3696 | uint64_t Size = 0; |
| 3697 | uint32_t Align = 0; |
| 3698 | if (!ED->getTypeForDecl()->isIncompleteType()) { |
| 3699 | Size = CGM.getContext().getTypeSize(T: ED->getTypeForDecl()); |
| 3700 | Align = getDeclAlignIfRequired(D: ED, Ctx: CGM.getContext()); |
| 3701 | } |
| 3702 | |
| 3703 | SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); |
| 3704 | |
| 3705 | bool isImportedFromModule = |
| 3706 | DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition(); |
| 3707 | |
| 3708 | // If this is just a forward declaration, construct an appropriately |
| 3709 | // marked node and just return it. |
| 3710 | if (isImportedFromModule || !ED->getDefinition()) { |
| 3711 | // Note that it is possible for enums to be created as part of |
| 3712 | // their own declcontext. In this case a FwdDecl will be created |
| 3713 | // twice. This doesn't cause a problem because both FwdDecls are |
| 3714 | // entered into the ReplaceMap: finalize() will replace the first |
| 3715 | // FwdDecl with the second and then replace the second with |
| 3716 | // complete type. |
| 3717 | llvm::DIScope *EDContext = getDeclContextDescriptor(D: ED); |
| 3718 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: ED->getLocation()); |
| 3719 | llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType( |
| 3720 | Tag: llvm::dwarf::DW_TAG_enumeration_type, Name: "" , Scope: TheCU, F: DefUnit, Line: 0)); |
| 3721 | |
| 3722 | unsigned Line = getLineNumber(Loc: ED->getLocation()); |
| 3723 | StringRef EDName = ED->getName(); |
| 3724 | llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType( |
| 3725 | Tag: llvm::dwarf::DW_TAG_enumeration_type, Name: EDName, Scope: EDContext, F: DefUnit, Line, |
| 3726 | RuntimeLang: 0, SizeInBits: Size, AlignInBits: Align, Flags: llvm::DINode::FlagFwdDecl, UniqueIdentifier: Identifier); |
| 3727 | |
| 3728 | ReplaceMap.emplace_back( |
| 3729 | args: std::piecewise_construct, args: std::make_tuple(args&: Ty), |
| 3730 | args: std::make_tuple(args: static_cast<llvm::Metadata *>(RetTy))); |
| 3731 | return RetTy; |
| 3732 | } |
| 3733 | |
| 3734 | return CreateTypeDefinition(Ty); |
| 3735 | } |
| 3736 | |
| 3737 | llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { |
| 3738 | const EnumDecl *ED = Ty->getDecl(); |
| 3739 | uint64_t Size = 0; |
| 3740 | uint32_t Align = 0; |
| 3741 | if (!ED->getTypeForDecl()->isIncompleteType()) { |
| 3742 | Size = CGM.getContext().getTypeSize(T: ED->getTypeForDecl()); |
| 3743 | Align = getDeclAlignIfRequired(D: ED, Ctx: CGM.getContext()); |
| 3744 | } |
| 3745 | |
| 3746 | SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); |
| 3747 | |
| 3748 | SmallVector<llvm::Metadata *, 16> Enumerators; |
| 3749 | ED = ED->getDefinition(); |
| 3750 | assert(ED && "An enumeration definition is required" ); |
| 3751 | for (const auto *Enum : ED->enumerators()) { |
| 3752 | Enumerators.push_back( |
| 3753 | Elt: DBuilder.createEnumerator(Name: Enum->getName(), Value: Enum->getInitVal())); |
| 3754 | } |
| 3755 | |
| 3756 | std::optional<EnumExtensibilityAttr::Kind> EnumKind; |
| 3757 | if (auto *Attr = ED->getAttr<EnumExtensibilityAttr>()) |
| 3758 | EnumKind = Attr->getExtensibility(); |
| 3759 | |
| 3760 | // Return a CompositeType for the enum itself. |
| 3761 | llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Elements: Enumerators); |
| 3762 | |
| 3763 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: ED->getLocation()); |
| 3764 | unsigned Line = getLineNumber(Loc: ED->getLocation()); |
| 3765 | llvm::DIScope *EnumContext = getDeclContextDescriptor(D: ED); |
| 3766 | llvm::DIType *ClassTy = getOrCreateType(Ty: ED->getIntegerType(), Fg: DefUnit); |
| 3767 | return DBuilder.createEnumerationType( |
| 3768 | Scope: EnumContext, Name: ED->getName(), File: DefUnit, LineNumber: Line, SizeInBits: Size, AlignInBits: Align, Elements: EltArray, UnderlyingType: ClassTy, |
| 3769 | /*RunTimeLang=*/0, UniqueIdentifier: Identifier, IsScoped: ED->isScoped(), EnumKind); |
| 3770 | } |
| 3771 | |
| 3772 | llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent, |
| 3773 | unsigned MType, SourceLocation LineLoc, |
| 3774 | StringRef Name, StringRef Value) { |
| 3775 | unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(Loc: LineLoc); |
| 3776 | return DBuilder.createMacro(Parent, Line, MacroType: MType, Name, Value); |
| 3777 | } |
| 3778 | |
| 3779 | llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent, |
| 3780 | SourceLocation LineLoc, |
| 3781 | SourceLocation FileLoc) { |
| 3782 | llvm::DIFile *FName = getOrCreateFile(Loc: FileLoc); |
| 3783 | unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(Loc: LineLoc); |
| 3784 | return DBuilder.createTempMacroFile(Parent, Line, File: FName); |
| 3785 | } |
| 3786 | |
| 3787 | llvm::DILocation *CGDebugInfo::CreateSyntheticInlineAt(llvm::DebugLoc Location, |
| 3788 | StringRef FuncName) { |
| 3789 | llvm::DISubprogram *SP = |
| 3790 | createInlinedSubprogram(FuncName, FileScope: Location->getFile()); |
| 3791 | return llvm::DILocation::get(Context&: CGM.getLLVMContext(), /*Line=*/0, /*Column=*/0, |
| 3792 | /*Scope=*/SP, /*InlinedAt=*/Location); |
| 3793 | } |
| 3794 | |
| 3795 | llvm::DILocation *CGDebugInfo::CreateTrapFailureMessageFor( |
| 3796 | llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg) { |
| 3797 | // Create a debug location from `TrapLocation` that adds an artificial inline |
| 3798 | // frame. |
| 3799 | SmallString<64> FuncName(ClangTrapPrefix); |
| 3800 | |
| 3801 | FuncName += "$" ; |
| 3802 | FuncName += Category; |
| 3803 | FuncName += "$" ; |
| 3804 | FuncName += FailureMsg; |
| 3805 | |
| 3806 | return CreateSyntheticInlineAt(Location: TrapLocation, FuncName); |
| 3807 | } |
| 3808 | |
| 3809 | static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { |
| 3810 | Qualifiers Quals; |
| 3811 | do { |
| 3812 | Qualifiers InnerQuals = T.getLocalQualifiers(); |
| 3813 | // Qualifiers::operator+() doesn't like it if you add a Qualifier |
| 3814 | // that is already there. |
| 3815 | Quals += Qualifiers::removeCommonQualifiers(L&: Quals, R&: InnerQuals); |
| 3816 | Quals += InnerQuals; |
| 3817 | QualType LastT = T; |
| 3818 | switch (T->getTypeClass()) { |
| 3819 | default: |
| 3820 | return C.getQualifiedType(T: T.getTypePtr(), Qs: Quals); |
| 3821 | case Type::TemplateSpecialization: { |
| 3822 | const auto *Spec = cast<TemplateSpecializationType>(Val&: T); |
| 3823 | if (Spec->isTypeAlias()) |
| 3824 | return C.getQualifiedType(T: T.getTypePtr(), Qs: Quals); |
| 3825 | T = Spec->desugar(); |
| 3826 | break; |
| 3827 | } |
| 3828 | case Type::TypeOfExpr: |
| 3829 | T = cast<TypeOfExprType>(Val&: T)->getUnderlyingExpr()->getType(); |
| 3830 | break; |
| 3831 | case Type::TypeOf: |
| 3832 | T = cast<TypeOfType>(Val&: T)->getUnmodifiedType(); |
| 3833 | break; |
| 3834 | case Type::Decltype: |
| 3835 | T = cast<DecltypeType>(Val&: T)->getUnderlyingType(); |
| 3836 | break; |
| 3837 | case Type::UnaryTransform: |
| 3838 | T = cast<UnaryTransformType>(Val&: T)->getUnderlyingType(); |
| 3839 | break; |
| 3840 | case Type::Attributed: |
| 3841 | T = cast<AttributedType>(Val&: T)->getEquivalentType(); |
| 3842 | break; |
| 3843 | case Type::BTFTagAttributed: |
| 3844 | T = cast<BTFTagAttributedType>(Val&: T)->getWrappedType(); |
| 3845 | break; |
| 3846 | case Type::CountAttributed: |
| 3847 | T = cast<CountAttributedType>(Val&: T)->desugar(); |
| 3848 | break; |
| 3849 | case Type::Elaborated: |
| 3850 | T = cast<ElaboratedType>(Val&: T)->getNamedType(); |
| 3851 | break; |
| 3852 | case Type::Using: |
| 3853 | T = cast<UsingType>(Val&: T)->getUnderlyingType(); |
| 3854 | break; |
| 3855 | case Type::Paren: |
| 3856 | T = cast<ParenType>(Val&: T)->getInnerType(); |
| 3857 | break; |
| 3858 | case Type::MacroQualified: |
| 3859 | T = cast<MacroQualifiedType>(Val&: T)->getUnderlyingType(); |
| 3860 | break; |
| 3861 | case Type::SubstTemplateTypeParm: |
| 3862 | T = cast<SubstTemplateTypeParmType>(Val&: T)->getReplacementType(); |
| 3863 | break; |
| 3864 | case Type::Auto: |
| 3865 | case Type::DeducedTemplateSpecialization: { |
| 3866 | QualType DT = cast<DeducedType>(Val&: T)->getDeducedType(); |
| 3867 | assert(!DT.isNull() && "Undeduced types shouldn't reach here." ); |
| 3868 | T = DT; |
| 3869 | break; |
| 3870 | } |
| 3871 | case Type::PackIndexing: { |
| 3872 | T = cast<PackIndexingType>(Val&: T)->getSelectedType(); |
| 3873 | break; |
| 3874 | } |
| 3875 | case Type::Adjusted: |
| 3876 | case Type::Decayed: |
| 3877 | // Decayed and adjusted types use the adjusted type in LLVM and DWARF. |
| 3878 | T = cast<AdjustedType>(Val&: T)->getAdjustedType(); |
| 3879 | break; |
| 3880 | } |
| 3881 | |
| 3882 | assert(T != LastT && "Type unwrapping failed to unwrap!" ); |
| 3883 | (void)LastT; |
| 3884 | } while (true); |
| 3885 | } |
| 3886 | |
| 3887 | llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) { |
| 3888 | assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext())); |
| 3889 | auto It = TypeCache.find(Val: Ty.getAsOpaquePtr()); |
| 3890 | if (It != TypeCache.end()) { |
| 3891 | // Verify that the debug info still exists. |
| 3892 | if (llvm::Metadata *V = It->second) |
| 3893 | return cast<llvm::DIType>(Val: V); |
| 3894 | } |
| 3895 | |
| 3896 | return nullptr; |
| 3897 | } |
| 3898 | |
| 3899 | void CGDebugInfo::completeTemplateDefinition( |
| 3900 | const ClassTemplateSpecializationDecl &SD) { |
| 3901 | completeUnusedClass(D: SD); |
| 3902 | } |
| 3903 | |
| 3904 | void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) { |
| 3905 | if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly || |
| 3906 | D.isDynamicClass()) |
| 3907 | return; |
| 3908 | |
| 3909 | completeClassData(RD: &D); |
| 3910 | // In case this type has no member function definitions being emitted, ensure |
| 3911 | // it is retained |
| 3912 | RetainedTypes.push_back(x: CGM.getContext().getRecordType(Decl: &D).getAsOpaquePtr()); |
| 3913 | } |
| 3914 | |
| 3915 | llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) { |
| 3916 | if (Ty.isNull()) |
| 3917 | return nullptr; |
| 3918 | |
| 3919 | llvm::TimeTraceScope TimeScope("DebugType" , [&]() { |
| 3920 | std::string Name; |
| 3921 | llvm::raw_string_ostream OS(Name); |
| 3922 | Ty.print(OS, Policy: getPrintingPolicy()); |
| 3923 | return Name; |
| 3924 | }); |
| 3925 | |
| 3926 | // Unwrap the type as needed for debug information. |
| 3927 | Ty = UnwrapTypeForDebugInfo(T: Ty, C: CGM.getContext()); |
| 3928 | |
| 3929 | if (auto *T = getTypeOrNull(Ty)) |
| 3930 | return T; |
| 3931 | |
| 3932 | llvm::DIType *Res = CreateTypeNode(Ty, Fg: Unit); |
| 3933 | void *TyPtr = Ty.getAsOpaquePtr(); |
| 3934 | |
| 3935 | // And update the type cache. |
| 3936 | TypeCache[TyPtr].reset(MD: Res); |
| 3937 | |
| 3938 | return Res; |
| 3939 | } |
| 3940 | |
| 3941 | llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) { |
| 3942 | // A forward declaration inside a module header does not belong to the module. |
| 3943 | if (isa<RecordDecl>(Val: D) && !cast<RecordDecl>(Val: D)->getDefinition()) |
| 3944 | return nullptr; |
| 3945 | if (DebugTypeExtRefs && D->isFromASTFile()) { |
| 3946 | // Record a reference to an imported clang module or precompiled header. |
| 3947 | auto *Reader = CGM.getContext().getExternalSource(); |
| 3948 | auto Idx = D->getOwningModuleID(); |
| 3949 | auto Info = Reader->getSourceDescriptor(ID: Idx); |
| 3950 | if (Info) |
| 3951 | return getOrCreateModuleRef(Mod: *Info, /*SkeletonCU=*/CreateSkeletonCU: true); |
| 3952 | } else if (ClangModuleMap) { |
| 3953 | // We are building a clang module or a precompiled header. |
| 3954 | // |
| 3955 | // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies |
| 3956 | // and it wouldn't be necessary to specify the parent scope |
| 3957 | // because the type is already unique by definition (it would look |
| 3958 | // like the output of -fno-standalone-debug). On the other hand, |
| 3959 | // the parent scope helps a consumer to quickly locate the object |
| 3960 | // file where the type's definition is located, so it might be |
| 3961 | // best to make this behavior a command line or debugger tuning |
| 3962 | // option. |
| 3963 | if (Module *M = D->getOwningModule()) { |
| 3964 | // This is a (sub-)module. |
| 3965 | auto Info = ASTSourceDescriptor(*M); |
| 3966 | return getOrCreateModuleRef(Mod: Info, /*SkeletonCU=*/CreateSkeletonCU: false); |
| 3967 | } else { |
| 3968 | // This the precompiled header being built. |
| 3969 | return getOrCreateModuleRef(Mod: PCHDescriptor, /*SkeletonCU=*/CreateSkeletonCU: false); |
| 3970 | } |
| 3971 | } |
| 3972 | |
| 3973 | return nullptr; |
| 3974 | } |
| 3975 | |
| 3976 | llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) { |
| 3977 | // Handle qualifiers, which recursively handles what they refer to. |
| 3978 | if (Ty.hasLocalQualifiers()) |
| 3979 | return CreateQualifiedType(Ty, Unit); |
| 3980 | |
| 3981 | // Work out details of type. |
| 3982 | switch (Ty->getTypeClass()) { |
| 3983 | #define TYPE(Class, Base) |
| 3984 | #define ABSTRACT_TYPE(Class, Base) |
| 3985 | #define NON_CANONICAL_TYPE(Class, Base) |
| 3986 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: |
| 3987 | #include "clang/AST/TypeNodes.inc" |
| 3988 | llvm_unreachable("Dependent types cannot show up in debug information" ); |
| 3989 | |
| 3990 | case Type::ExtVector: |
| 3991 | case Type::Vector: |
| 3992 | return CreateType(Ty: cast<VectorType>(Val&: Ty), Unit); |
| 3993 | case Type::ConstantMatrix: |
| 3994 | return CreateType(Ty: cast<ConstantMatrixType>(Val&: Ty), Unit); |
| 3995 | case Type::ObjCObjectPointer: |
| 3996 | return CreateType(Ty: cast<ObjCObjectPointerType>(Val&: Ty), Unit); |
| 3997 | case Type::ObjCObject: |
| 3998 | return CreateType(Ty: cast<ObjCObjectType>(Val&: Ty), Unit); |
| 3999 | case Type::ObjCTypeParam: |
| 4000 | return CreateType(Ty: cast<ObjCTypeParamType>(Val&: Ty), Unit); |
| 4001 | case Type::ObjCInterface: |
| 4002 | return CreateType(Ty: cast<ObjCInterfaceType>(Val&: Ty), Unit); |
| 4003 | case Type::Builtin: |
| 4004 | return CreateType(BT: cast<BuiltinType>(Val&: Ty)); |
| 4005 | case Type::Complex: |
| 4006 | return CreateType(Ty: cast<ComplexType>(Val&: Ty)); |
| 4007 | case Type::Pointer: |
| 4008 | return CreateType(Ty: cast<PointerType>(Val&: Ty), Unit); |
| 4009 | case Type::BlockPointer: |
| 4010 | return CreateType(Ty: cast<BlockPointerType>(Val&: Ty), Unit); |
| 4011 | case Type::Typedef: |
| 4012 | return CreateType(Ty: cast<TypedefType>(Val&: Ty), Unit); |
| 4013 | case Type::Record: |
| 4014 | return CreateType(Ty: cast<RecordType>(Val&: Ty)); |
| 4015 | case Type::Enum: |
| 4016 | return CreateEnumType(Ty: cast<EnumType>(Val&: Ty)); |
| 4017 | case Type::FunctionProto: |
| 4018 | case Type::FunctionNoProto: |
| 4019 | return CreateType(Ty: cast<FunctionType>(Val&: Ty), Unit); |
| 4020 | case Type::ConstantArray: |
| 4021 | case Type::VariableArray: |
| 4022 | case Type::IncompleteArray: |
| 4023 | case Type::ArrayParameter: |
| 4024 | return CreateType(Ty: cast<ArrayType>(Val&: Ty), Unit); |
| 4025 | |
| 4026 | case Type::LValueReference: |
| 4027 | return CreateType(Ty: cast<LValueReferenceType>(Val&: Ty), Unit); |
| 4028 | case Type::RValueReference: |
| 4029 | return CreateType(Ty: cast<RValueReferenceType>(Val&: Ty), Unit); |
| 4030 | |
| 4031 | case Type::MemberPointer: |
| 4032 | return CreateType(Ty: cast<MemberPointerType>(Val&: Ty), U: Unit); |
| 4033 | |
| 4034 | case Type::Atomic: |
| 4035 | return CreateType(Ty: cast<AtomicType>(Val&: Ty), U: Unit); |
| 4036 | |
| 4037 | case Type::BitInt: |
| 4038 | return CreateType(Ty: cast<BitIntType>(Val&: Ty)); |
| 4039 | case Type::Pipe: |
| 4040 | return CreateType(Ty: cast<PipeType>(Val&: Ty), U: Unit); |
| 4041 | |
| 4042 | case Type::TemplateSpecialization: |
| 4043 | return CreateType(Ty: cast<TemplateSpecializationType>(Val&: Ty), Unit); |
| 4044 | case Type::HLSLAttributedResource: |
| 4045 | return CreateType(Ty: cast<HLSLAttributedResourceType>(Val&: Ty), U: Unit); |
| 4046 | case Type::HLSLInlineSpirv: |
| 4047 | return CreateType(Ty: cast<HLSLInlineSpirvType>(Val&: Ty), U: Unit); |
| 4048 | |
| 4049 | case Type::CountAttributed: |
| 4050 | case Type::Auto: |
| 4051 | case Type::Attributed: |
| 4052 | case Type::BTFTagAttributed: |
| 4053 | case Type::Adjusted: |
| 4054 | case Type::Decayed: |
| 4055 | case Type::DeducedTemplateSpecialization: |
| 4056 | case Type::Elaborated: |
| 4057 | case Type::Using: |
| 4058 | case Type::Paren: |
| 4059 | case Type::MacroQualified: |
| 4060 | case Type::SubstTemplateTypeParm: |
| 4061 | case Type::TypeOfExpr: |
| 4062 | case Type::TypeOf: |
| 4063 | case Type::Decltype: |
| 4064 | case Type::PackIndexing: |
| 4065 | case Type::UnaryTransform: |
| 4066 | break; |
| 4067 | } |
| 4068 | |
| 4069 | llvm_unreachable("type should have been unwrapped!" ); |
| 4070 | } |
| 4071 | |
| 4072 | llvm::DICompositeType * |
| 4073 | CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) { |
| 4074 | QualType QTy(Ty, 0); |
| 4075 | |
| 4076 | auto *T = cast_or_null<llvm::DICompositeType>(Val: getTypeOrNull(Ty: QTy)); |
| 4077 | |
| 4078 | // We may have cached a forward decl when we could have created |
| 4079 | // a non-forward decl. Go ahead and create a non-forward decl |
| 4080 | // now. |
| 4081 | if (T && !T->isForwardDecl()) |
| 4082 | return T; |
| 4083 | |
| 4084 | // Otherwise create the type. |
| 4085 | llvm::DICompositeType *Res = CreateLimitedType(Ty); |
| 4086 | |
| 4087 | // Propagate members from the declaration to the definition |
| 4088 | // CreateType(const RecordType*) will overwrite this with the members in the |
| 4089 | // correct order if the full type is needed. |
| 4090 | DBuilder.replaceArrays(T&: Res, Elements: T ? T->getElements() : llvm::DINodeArray()); |
| 4091 | |
| 4092 | // And update the type cache. |
| 4093 | TypeCache[QTy.getAsOpaquePtr()].reset(MD: Res); |
| 4094 | return Res; |
| 4095 | } |
| 4096 | |
| 4097 | // TODO: Currently used for context chains when limiting debug info. |
| 4098 | llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) { |
| 4099 | RecordDecl *RD = Ty->getDecl(); |
| 4100 | |
| 4101 | // Get overall information about the record type for the debug info. |
| 4102 | StringRef RDName = getClassName(RD); |
| 4103 | const SourceLocation Loc = RD->getLocation(); |
| 4104 | llvm::DIFile *DefUnit = nullptr; |
| 4105 | unsigned Line = 0; |
| 4106 | if (Loc.isValid()) { |
| 4107 | DefUnit = getOrCreateFile(Loc); |
| 4108 | Line = getLineNumber(Loc); |
| 4109 | } |
| 4110 | |
| 4111 | llvm::DIScope *RDContext = getDeclContextDescriptor(D: RD); |
| 4112 | |
| 4113 | // If we ended up creating the type during the context chain construction, |
| 4114 | // just return that. |
| 4115 | auto *T = cast_or_null<llvm::DICompositeType>( |
| 4116 | Val: getTypeOrNull(Ty: CGM.getContext().getRecordType(Decl: RD))); |
| 4117 | if (T && (!T->isForwardDecl() || !RD->getDefinition())) |
| 4118 | return T; |
| 4119 | |
| 4120 | // If this is just a forward or incomplete declaration, construct an |
| 4121 | // appropriately marked node and just return it. |
| 4122 | const RecordDecl *D = RD->getDefinition(); |
| 4123 | if (!D || !D->isCompleteDefinition()) |
| 4124 | return getOrCreateRecordFwdDecl(Ty, Ctx: RDContext); |
| 4125 | |
| 4126 | uint64_t Size = CGM.getContext().getTypeSize(T: Ty); |
| 4127 | // __attribute__((aligned)) can increase or decrease alignment *except* on a |
| 4128 | // struct or struct member, where it only increases alignment unless 'packed' |
| 4129 | // is also specified. To handle this case, the `getTypeAlignIfRequired` needs |
| 4130 | // to be used. |
| 4131 | auto Align = getTypeAlignIfRequired(Ty, Ctx: CGM.getContext()); |
| 4132 | |
| 4133 | SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); |
| 4134 | |
| 4135 | // Explicitly record the calling convention and export symbols for C++ |
| 4136 | // records. |
| 4137 | auto Flags = llvm::DINode::FlagZero; |
| 4138 | if (auto CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) { |
| 4139 | if (CGM.getCXXABI().getRecordArgABI(RD: CXXRD) == CGCXXABI::RAA_Indirect) |
| 4140 | Flags |= llvm::DINode::FlagTypePassByReference; |
| 4141 | else |
| 4142 | Flags |= llvm::DINode::FlagTypePassByValue; |
| 4143 | |
| 4144 | // Record if a C++ record is non-trivial type. |
| 4145 | if (!CXXRD->isTrivial()) |
| 4146 | Flags |= llvm::DINode::FlagNonTrivial; |
| 4147 | |
| 4148 | // Record exports it symbols to the containing structure. |
| 4149 | if (CXXRD->isAnonymousStructOrUnion()) |
| 4150 | Flags |= llvm::DINode::FlagExportSymbols; |
| 4151 | |
| 4152 | Flags |= getAccessFlag(Access: CXXRD->getAccess(), |
| 4153 | RD: dyn_cast<CXXRecordDecl>(Val: CXXRD->getDeclContext())); |
| 4154 | } |
| 4155 | |
| 4156 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D); |
| 4157 | llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType( |
| 4158 | Tag: getTagForRecord(RD), Name: RDName, Scope: RDContext, F: DefUnit, Line, RuntimeLang: 0, SizeInBits: Size, AlignInBits: Align, |
| 4159 | Flags, UniqueIdentifier: Identifier, Annotations); |
| 4160 | |
| 4161 | // Elements of composite types usually have back to the type, creating |
| 4162 | // uniquing cycles. Distinct nodes are more efficient. |
| 4163 | switch (RealDecl->getTag()) { |
| 4164 | default: |
| 4165 | llvm_unreachable("invalid composite type tag" ); |
| 4166 | |
| 4167 | case llvm::dwarf::DW_TAG_array_type: |
| 4168 | case llvm::dwarf::DW_TAG_enumeration_type: |
| 4169 | // Array elements and most enumeration elements don't have back references, |
| 4170 | // so they don't tend to be involved in uniquing cycles and there is some |
| 4171 | // chance of merging them when linking together two modules. Only make |
| 4172 | // them distinct if they are ODR-uniqued. |
| 4173 | if (Identifier.empty()) |
| 4174 | break; |
| 4175 | [[fallthrough]]; |
| 4176 | |
| 4177 | case llvm::dwarf::DW_TAG_structure_type: |
| 4178 | case llvm::dwarf::DW_TAG_union_type: |
| 4179 | case llvm::dwarf::DW_TAG_class_type: |
| 4180 | // Immediately resolve to a distinct node. |
| 4181 | RealDecl = |
| 4182 | llvm::MDNode::replaceWithDistinct(N: llvm::TempDICompositeType(RealDecl)); |
| 4183 | break; |
| 4184 | } |
| 4185 | |
| 4186 | RegionMap[Ty->getDecl()].reset(MD: RealDecl); |
| 4187 | TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(MD: RealDecl); |
| 4188 | |
| 4189 | if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) |
| 4190 | DBuilder.replaceArrays(T&: RealDecl, Elements: llvm::DINodeArray(), |
| 4191 | TParams: CollectCXXTemplateParams(RD: TSpecial, Unit: DefUnit)); |
| 4192 | return RealDecl; |
| 4193 | } |
| 4194 | |
| 4195 | void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD, |
| 4196 | llvm::DICompositeType *RealDecl) { |
| 4197 | // A class's primary base or the class itself contains the vtable. |
| 4198 | llvm::DIType *ContainingType = nullptr; |
| 4199 | const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(D: RD); |
| 4200 | if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { |
| 4201 | // Seek non-virtual primary base root. |
| 4202 | while (true) { |
| 4203 | const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(D: PBase); |
| 4204 | const CXXRecordDecl *PBT = BRL.getPrimaryBase(); |
| 4205 | if (PBT && !BRL.isPrimaryBaseVirtual()) |
| 4206 | PBase = PBT; |
| 4207 | else |
| 4208 | break; |
| 4209 | } |
| 4210 | ContainingType = getOrCreateType(Ty: QualType(PBase->getTypeForDecl(), 0), |
| 4211 | Unit: getOrCreateFile(Loc: RD->getLocation())); |
| 4212 | } else if (RD->isDynamicClass()) |
| 4213 | ContainingType = RealDecl; |
| 4214 | |
| 4215 | DBuilder.replaceVTableHolder(T&: RealDecl, VTableHolder: ContainingType); |
| 4216 | } |
| 4217 | |
| 4218 | llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType, |
| 4219 | StringRef Name, uint64_t *Offset) { |
| 4220 | llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(Ty: FType, Unit); |
| 4221 | uint64_t FieldSize = CGM.getContext().getTypeSize(T: FType); |
| 4222 | auto FieldAlign = getTypeAlignIfRequired(Ty: FType, Ctx: CGM.getContext()); |
| 4223 | llvm::DIType *Ty = |
| 4224 | DBuilder.createMemberType(Scope: Unit, Name, File: Unit, LineNo: 0, SizeInBits: FieldSize, AlignInBits: FieldAlign, |
| 4225 | OffsetInBits: *Offset, Flags: llvm::DINode::FlagZero, Ty: FieldTy); |
| 4226 | *Offset += FieldSize; |
| 4227 | return Ty; |
| 4228 | } |
| 4229 | |
| 4230 | void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit, |
| 4231 | StringRef &Name, |
| 4232 | StringRef &LinkageName, |
| 4233 | llvm::DIScope *&FDContext, |
| 4234 | llvm::DINodeArray &TParamsArray, |
| 4235 | llvm::DINode::DIFlags &Flags) { |
| 4236 | const auto *FD = cast<FunctionDecl>(Val: GD.getCanonicalDecl().getDecl()); |
| 4237 | Name = getFunctionName(FD); |
| 4238 | // Use mangled name as linkage name for C/C++ functions. |
| 4239 | if (FD->getType()->getAs<FunctionProtoType>()) |
| 4240 | LinkageName = CGM.getMangledName(GD); |
| 4241 | if (FD->hasPrototype()) |
| 4242 | Flags |= llvm::DINode::FlagPrototyped; |
| 4243 | // No need to replicate the linkage name if it isn't different from the |
| 4244 | // subprogram name, no need to have it at all unless coverage is enabled or |
| 4245 | // debug is set to more than just line tables or extra debug info is needed. |
| 4246 | if (LinkageName == Name || |
| 4247 | (CGM.getCodeGenOpts().CoverageNotesFile.empty() && |
| 4248 | CGM.getCodeGenOpts().CoverageDataFile.empty() && |
| 4249 | !CGM.getCodeGenOpts().DebugInfoForProfiling && |
| 4250 | !CGM.getCodeGenOpts().PseudoProbeForProfiling && |
| 4251 | DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)) |
| 4252 | LinkageName = StringRef(); |
| 4253 | |
| 4254 | // Emit the function scope in line tables only mode (if CodeView) to |
| 4255 | // differentiate between function names. |
| 4256 | if (CGM.getCodeGenOpts().hasReducedDebugInfo() || |
| 4257 | (DebugKind == llvm::codegenoptions::DebugLineTablesOnly && |
| 4258 | CGM.getCodeGenOpts().EmitCodeView)) { |
| 4259 | if (const NamespaceDecl *NSDecl = |
| 4260 | dyn_cast_or_null<NamespaceDecl>(Val: FD->getDeclContext())) |
| 4261 | FDContext = getOrCreateNamespace(N: NSDecl); |
| 4262 | else if (const RecordDecl *RDecl = |
| 4263 | dyn_cast_or_null<RecordDecl>(Val: FD->getDeclContext())) { |
| 4264 | llvm::DIScope *Mod = getParentModuleOrNull(D: RDecl); |
| 4265 | FDContext = getContextDescriptor(Context: RDecl, Default: Mod ? Mod : TheCU); |
| 4266 | } |
| 4267 | } |
| 4268 | if (CGM.getCodeGenOpts().hasReducedDebugInfo()) { |
| 4269 | // Check if it is a noreturn-marked function |
| 4270 | if (FD->isNoReturn()) |
| 4271 | Flags |= llvm::DINode::FlagNoReturn; |
| 4272 | // Collect template parameters. |
| 4273 | TParamsArray = CollectFunctionTemplateParams(FD, Unit); |
| 4274 | } |
| 4275 | } |
| 4276 | |
| 4277 | void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit, |
| 4278 | unsigned &LineNo, QualType &T, |
| 4279 | StringRef &Name, StringRef &LinkageName, |
| 4280 | llvm::MDTuple *&TemplateParameters, |
| 4281 | llvm::DIScope *&VDContext) { |
| 4282 | Unit = getOrCreateFile(Loc: VD->getLocation()); |
| 4283 | LineNo = getLineNumber(Loc: VD->getLocation()); |
| 4284 | |
| 4285 | setLocation(VD->getLocation()); |
| 4286 | |
| 4287 | T = VD->getType(); |
| 4288 | if (T->isIncompleteArrayType()) { |
| 4289 | // CodeGen turns int[] into int[1] so we'll do the same here. |
| 4290 | llvm::APInt ConstVal(32, 1); |
| 4291 | QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); |
| 4292 | |
| 4293 | T = CGM.getContext().getConstantArrayType(EltTy: ET, ArySize: ConstVal, SizeExpr: nullptr, |
| 4294 | ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 4295 | } |
| 4296 | |
| 4297 | Name = VD->getName(); |
| 4298 | if (VD->getDeclContext() && !isa<FunctionDecl>(Val: VD->getDeclContext()) && |
| 4299 | !isa<ObjCMethodDecl>(Val: VD->getDeclContext())) |
| 4300 | LinkageName = CGM.getMangledName(GD: VD); |
| 4301 | if (LinkageName == Name) |
| 4302 | LinkageName = StringRef(); |
| 4303 | |
| 4304 | if (isa<VarTemplateSpecializationDecl>(Val: VD)) { |
| 4305 | llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VL: VD, Unit: &*Unit); |
| 4306 | TemplateParameters = parameterNodes.get(); |
| 4307 | } else { |
| 4308 | TemplateParameters = nullptr; |
| 4309 | } |
| 4310 | |
| 4311 | // Since we emit declarations (DW_AT_members) for static members, place the |
| 4312 | // definition of those static members in the namespace they were declared in |
| 4313 | // in the source code (the lexical decl context). |
| 4314 | // FIXME: Generalize this for even non-member global variables where the |
| 4315 | // declaration and definition may have different lexical decl contexts, once |
| 4316 | // we have support for emitting declarations of (non-member) global variables. |
| 4317 | const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext() |
| 4318 | : VD->getDeclContext(); |
| 4319 | // When a record type contains an in-line initialization of a static data |
| 4320 | // member, and the record type is marked as __declspec(dllexport), an implicit |
| 4321 | // definition of the member will be created in the record context. DWARF |
| 4322 | // doesn't seem to have a nice way to describe this in a form that consumers |
| 4323 | // are likely to understand, so fake the "normal" situation of a definition |
| 4324 | // outside the class by putting it in the global scope. |
| 4325 | if (DC->isRecord()) |
| 4326 | DC = CGM.getContext().getTranslationUnitDecl(); |
| 4327 | |
| 4328 | llvm::DIScope *Mod = getParentModuleOrNull(D: VD); |
| 4329 | VDContext = getContextDescriptor(Context: cast<Decl>(Val: DC), Default: Mod ? Mod : TheCU); |
| 4330 | } |
| 4331 | |
| 4332 | llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD, |
| 4333 | bool Stub) { |
| 4334 | llvm::DINodeArray TParamsArray; |
| 4335 | StringRef Name, LinkageName; |
| 4336 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 4337 | llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; |
| 4338 | SourceLocation Loc = GD.getDecl()->getLocation(); |
| 4339 | llvm::DIFile *Unit = getOrCreateFile(Loc); |
| 4340 | llvm::DIScope *DContext = Unit; |
| 4341 | unsigned Line = getLineNumber(Loc); |
| 4342 | collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext&: DContext, TParamsArray, |
| 4343 | Flags); |
| 4344 | auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
| 4345 | |
| 4346 | // Build function type. |
| 4347 | SmallVector<QualType, 16> ArgTypes; |
| 4348 | for (const ParmVarDecl *Parm : FD->parameters()) |
| 4349 | ArgTypes.push_back(Elt: Parm->getType()); |
| 4350 | |
| 4351 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); |
| 4352 | QualType FnType = CGM.getContext().getFunctionType( |
| 4353 | ResultTy: FD->getReturnType(), Args: ArgTypes, EPI: FunctionProtoType::ExtProtoInfo(CC)); |
| 4354 | if (!FD->isExternallyVisible()) |
| 4355 | SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; |
| 4356 | if (CGM.getLangOpts().Optimize) |
| 4357 | SPFlags |= llvm::DISubprogram::SPFlagOptimized; |
| 4358 | |
| 4359 | if (Stub) { |
| 4360 | Flags |= getCallSiteRelatedAttrs(); |
| 4361 | SPFlags |= llvm::DISubprogram::SPFlagDefinition; |
| 4362 | return DBuilder.createFunction( |
| 4363 | Scope: DContext, Name, LinkageName, File: Unit, LineNo: Line, |
| 4364 | Ty: getOrCreateFunctionType(D: GD.getDecl(), FnType, F: Unit), ScopeLine: 0, Flags, SPFlags, |
| 4365 | TParams: TParamsArray.get(), Decl: getFunctionDeclaration(D: FD), /*ThrownTypes*/ nullptr, |
| 4366 | /*Annotations*/ nullptr, /*TargetFuncName*/ "" , |
| 4367 | UseKeyInstructions: CGM.getCodeGenOpts().DebugKeyInstructions); |
| 4368 | } |
| 4369 | |
| 4370 | llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl( |
| 4371 | Scope: DContext, Name, LinkageName, File: Unit, LineNo: Line, |
| 4372 | Ty: getOrCreateFunctionType(D: GD.getDecl(), FnType, F: Unit), ScopeLine: 0, Flags, SPFlags, |
| 4373 | TParams: TParamsArray.get(), Decl: getFunctionDeclaration(D: FD)); |
| 4374 | const FunctionDecl *CanonDecl = FD->getCanonicalDecl(); |
| 4375 | FwdDeclReplaceMap.emplace_back(args: std::piecewise_construct, |
| 4376 | args: std::make_tuple(args&: CanonDecl), |
| 4377 | args: std::make_tuple(args&: SP)); |
| 4378 | return SP; |
| 4379 | } |
| 4380 | |
| 4381 | llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) { |
| 4382 | return getFunctionFwdDeclOrStub(GD, /* Stub = */ false); |
| 4383 | } |
| 4384 | |
| 4385 | llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) { |
| 4386 | return getFunctionFwdDeclOrStub(GD, /* Stub = */ true); |
| 4387 | } |
| 4388 | |
| 4389 | llvm::DIGlobalVariable * |
| 4390 | CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) { |
| 4391 | QualType T; |
| 4392 | StringRef Name, LinkageName; |
| 4393 | SourceLocation Loc = VD->getLocation(); |
| 4394 | llvm::DIFile *Unit = getOrCreateFile(Loc); |
| 4395 | llvm::DIScope *DContext = Unit; |
| 4396 | unsigned Line = getLineNumber(Loc); |
| 4397 | llvm::MDTuple *TemplateParameters = nullptr; |
| 4398 | |
| 4399 | collectVarDeclProps(VD, Unit, LineNo&: Line, T, Name, LinkageName, TemplateParameters, |
| 4400 | VDContext&: DContext); |
| 4401 | auto Align = getDeclAlignIfRequired(D: VD, Ctx: CGM.getContext()); |
| 4402 | auto *GV = DBuilder.createTempGlobalVariableFwdDecl( |
| 4403 | Context: DContext, Name, LinkageName, File: Unit, LineNo: Line, Ty: getOrCreateType(Ty: T, Unit), |
| 4404 | IsLocalToUnit: !VD->isExternallyVisible(), Decl: nullptr, TemplateParams: TemplateParameters, AlignInBits: Align); |
| 4405 | FwdDeclReplaceMap.emplace_back( |
| 4406 | args: std::piecewise_construct, |
| 4407 | args: std::make_tuple(args: cast<VarDecl>(Val: VD->getCanonicalDecl())), |
| 4408 | args: std::make_tuple(args: static_cast<llvm::Metadata *>(GV))); |
| 4409 | return GV; |
| 4410 | } |
| 4411 | |
| 4412 | llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { |
| 4413 | // We only need a declaration (not a definition) of the type - so use whatever |
| 4414 | // we would otherwise do to get a type for a pointee. (forward declarations in |
| 4415 | // limited debug info, full definitions (if the type definition is available) |
| 4416 | // in unlimited debug info) |
| 4417 | if (const auto *TD = dyn_cast<TypeDecl>(Val: D)) |
| 4418 | return getOrCreateType(Ty: CGM.getContext().getTypeDeclType(Decl: TD), |
| 4419 | Unit: getOrCreateFile(Loc: TD->getLocation())); |
| 4420 | auto I = DeclCache.find(Val: D->getCanonicalDecl()); |
| 4421 | |
| 4422 | if (I != DeclCache.end()) { |
| 4423 | auto N = I->second; |
| 4424 | if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Val&: N)) |
| 4425 | return GVE->getVariable(); |
| 4426 | return cast<llvm::DINode>(Val&: N); |
| 4427 | } |
| 4428 | |
| 4429 | // Search imported declaration cache if it is already defined |
| 4430 | // as imported declaration. |
| 4431 | auto IE = ImportedDeclCache.find(Val: D->getCanonicalDecl()); |
| 4432 | |
| 4433 | if (IE != ImportedDeclCache.end()) { |
| 4434 | auto N = IE->second; |
| 4435 | if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(Val&: N)) |
| 4436 | return cast<llvm::DINode>(Val: GVE); |
| 4437 | return dyn_cast_or_null<llvm::DINode>(Val&: N); |
| 4438 | } |
| 4439 | |
| 4440 | // No definition for now. Emit a forward definition that might be |
| 4441 | // merged with a potential upcoming definition. |
| 4442 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
| 4443 | return getFunctionForwardDeclaration(GD: FD); |
| 4444 | else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
| 4445 | return getGlobalVariableForwardDeclaration(VD); |
| 4446 | |
| 4447 | return nullptr; |
| 4448 | } |
| 4449 | |
| 4450 | llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) { |
| 4451 | if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
| 4452 | return nullptr; |
| 4453 | |
| 4454 | const auto *FD = dyn_cast<FunctionDecl>(Val: D); |
| 4455 | if (!FD) |
| 4456 | return nullptr; |
| 4457 | |
| 4458 | // Setup context. |
| 4459 | auto *S = getDeclContextDescriptor(D); |
| 4460 | |
| 4461 | auto MI = SPCache.find(Val: FD->getCanonicalDecl()); |
| 4462 | if (MI == SPCache.end()) { |
| 4463 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD->getCanonicalDecl())) { |
| 4464 | return CreateCXXMemberFunction(Method: MD, Unit: getOrCreateFile(Loc: MD->getLocation()), |
| 4465 | RecordTy: cast<llvm::DICompositeType>(Val: S)); |
| 4466 | } |
| 4467 | } |
| 4468 | if (MI != SPCache.end()) { |
| 4469 | auto *SP = dyn_cast_or_null<llvm::DISubprogram>(Val&: MI->second); |
| 4470 | if (SP && !SP->isDefinition()) |
| 4471 | return SP; |
| 4472 | } |
| 4473 | |
| 4474 | for (auto *NextFD : FD->redecls()) { |
| 4475 | auto MI = SPCache.find(Val: NextFD->getCanonicalDecl()); |
| 4476 | if (MI != SPCache.end()) { |
| 4477 | auto *SP = dyn_cast_or_null<llvm::DISubprogram>(Val&: MI->second); |
| 4478 | if (SP && !SP->isDefinition()) |
| 4479 | return SP; |
| 4480 | } |
| 4481 | } |
| 4482 | return nullptr; |
| 4483 | } |
| 4484 | |
| 4485 | llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration( |
| 4486 | const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo, |
| 4487 | llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) { |
| 4488 | if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
| 4489 | return nullptr; |
| 4490 | |
| 4491 | const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D); |
| 4492 | if (!OMD) |
| 4493 | return nullptr; |
| 4494 | |
| 4495 | if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod()) |
| 4496 | return nullptr; |
| 4497 | |
| 4498 | if (OMD->isDirectMethod()) |
| 4499 | SPFlags |= llvm::DISubprogram::SPFlagObjCDirect; |
| 4500 | |
| 4501 | // Starting with DWARF V5 method declarations are emitted as children of |
| 4502 | // the interface type. |
| 4503 | auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(Val: D->getDeclContext()); |
| 4504 | if (!ID) |
| 4505 | ID = OMD->getClassInterface(); |
| 4506 | if (!ID) |
| 4507 | return nullptr; |
| 4508 | QualType QTy(ID->getTypeForDecl(), 0); |
| 4509 | auto It = TypeCache.find(Val: QTy.getAsOpaquePtr()); |
| 4510 | if (It == TypeCache.end()) |
| 4511 | return nullptr; |
| 4512 | auto *InterfaceType = cast<llvm::DICompositeType>(Val&: It->second); |
| 4513 | llvm::DISubprogram *FD = DBuilder.createFunction( |
| 4514 | Scope: InterfaceType, Name: getObjCMethodName(OMD), LinkageName: StringRef(), |
| 4515 | File: InterfaceType->getFile(), LineNo, Ty: FnType, ScopeLine: LineNo, Flags, SPFlags); |
| 4516 | DBuilder.finalizeSubprogram(SP: FD); |
| 4517 | ObjCMethodCache[ID].push_back(x: {FD, OMD->isDirectMethod()}); |
| 4518 | return FD; |
| 4519 | } |
| 4520 | |
| 4521 | // getOrCreateFunctionType - Construct type. If it is a c++ method, include |
| 4522 | // implicit parameter "this". |
| 4523 | llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D, |
| 4524 | QualType FnType, |
| 4525 | llvm::DIFile *F) { |
| 4526 | // In CodeView, we emit the function types in line tables only because the |
| 4527 | // only way to distinguish between functions is by display name and type. |
| 4528 | if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly && |
| 4529 | !CGM.getCodeGenOpts().EmitCodeView)) |
| 4530 | // Create fake but valid subroutine type. Otherwise -verify would fail, and |
| 4531 | // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields. |
| 4532 | return DBuilder.createSubroutineType(ParameterTypes: DBuilder.getOrCreateTypeArray(Elements: {})); |
| 4533 | |
| 4534 | if (const auto *Method = dyn_cast<CXXDestructorDecl>(Val: D)) { |
| 4535 | // Read method type from 'FnType' because 'D.getType()' does not cover |
| 4536 | // implicit arguments for destructors. |
| 4537 | return getOrCreateMethodTypeForDestructor(Method, Unit: F, FNType: FnType); |
| 4538 | } |
| 4539 | |
| 4540 | if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: D)) |
| 4541 | return getOrCreateMethodType(Method, Unit: F); |
| 4542 | |
| 4543 | const auto *FTy = FnType->getAs<FunctionType>(); |
| 4544 | CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C; |
| 4545 | |
| 4546 | if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(Val: D)) { |
| 4547 | // Add "self" and "_cmd" |
| 4548 | SmallVector<llvm::Metadata *, 16> Elts; |
| 4549 | |
| 4550 | // First element is always return type. For 'void' functions it is NULL. |
| 4551 | QualType ResultTy = OMethod->getReturnType(); |
| 4552 | |
| 4553 | // Replace the instancetype keyword with the actual type. |
| 4554 | if (ResultTy == CGM.getContext().getObjCInstanceType()) |
| 4555 | ResultTy = CGM.getContext().getPointerType( |
| 4556 | T: QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); |
| 4557 | |
| 4558 | Elts.push_back(Elt: getOrCreateType(Ty: ResultTy, Unit: F)); |
| 4559 | // "self" pointer is always first argument. |
| 4560 | QualType SelfDeclTy; |
| 4561 | if (auto *SelfDecl = OMethod->getSelfDecl()) |
| 4562 | SelfDeclTy = SelfDecl->getType(); |
| 4563 | else if (auto *FPT = dyn_cast<FunctionProtoType>(Val&: FnType)) |
| 4564 | if (FPT->getNumParams() > 1) |
| 4565 | SelfDeclTy = FPT->getParamType(i: 0); |
| 4566 | if (!SelfDeclTy.isNull()) |
| 4567 | Elts.push_back( |
| 4568 | Elt: CreateSelfType(QualTy: SelfDeclTy, Ty: getOrCreateType(Ty: SelfDeclTy, Unit: F))); |
| 4569 | // "_cmd" pointer is always second argument. |
| 4570 | Elts.push_back(Elt: DBuilder.createArtificialType( |
| 4571 | Ty: getOrCreateType(Ty: CGM.getContext().getObjCSelType(), Unit: F))); |
| 4572 | // Get rest of the arguments. |
| 4573 | for (const auto *PI : OMethod->parameters()) |
| 4574 | Elts.push_back(Elt: getOrCreateType(Ty: PI->getType(), Unit: F)); |
| 4575 | // Variadic methods need a special marker at the end of the type list. |
| 4576 | if (OMethod->isVariadic()) |
| 4577 | Elts.push_back(Elt: DBuilder.createUnspecifiedParameter()); |
| 4578 | |
| 4579 | llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elements: Elts); |
| 4580 | return DBuilder.createSubroutineType(ParameterTypes: EltTypeArray, Flags: llvm::DINode::FlagZero, |
| 4581 | CC: getDwarfCC(CC)); |
| 4582 | } |
| 4583 | |
| 4584 | // Handle variadic function types; they need an additional |
| 4585 | // unspecified parameter. |
| 4586 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
| 4587 | if (FD->isVariadic()) { |
| 4588 | SmallVector<llvm::Metadata *, 16> EltTys; |
| 4589 | EltTys.push_back(Elt: getOrCreateType(Ty: FD->getReturnType(), Unit: F)); |
| 4590 | if (const auto *FPT = dyn_cast<FunctionProtoType>(Val&: FnType)) |
| 4591 | for (QualType ParamType : FPT->param_types()) |
| 4592 | EltTys.push_back(Elt: getOrCreateType(Ty: ParamType, Unit: F)); |
| 4593 | EltTys.push_back(Elt: DBuilder.createUnspecifiedParameter()); |
| 4594 | llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elements: EltTys); |
| 4595 | return DBuilder.createSubroutineType(ParameterTypes: EltTypeArray, Flags: llvm::DINode::FlagZero, |
| 4596 | CC: getDwarfCC(CC)); |
| 4597 | } |
| 4598 | |
| 4599 | return cast<llvm::DISubroutineType>(Val: getOrCreateType(Ty: FnType, Unit: F)); |
| 4600 | } |
| 4601 | |
| 4602 | QualType |
| 4603 | CGDebugInfo::getFunctionType(const FunctionDecl *FD, QualType RetTy, |
| 4604 | const SmallVectorImpl<const VarDecl *> &Args) { |
| 4605 | CallingConv CC = CallingConv::CC_C; |
| 4606 | if (FD) |
| 4607 | if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>()) |
| 4608 | CC = SrcFnTy->getCallConv(); |
| 4609 | SmallVector<QualType, 16> ArgTypes; |
| 4610 | for (const VarDecl *VD : Args) |
| 4611 | ArgTypes.push_back(Elt: VD->getType()); |
| 4612 | return CGM.getContext().getFunctionType(ResultTy: RetTy, Args: ArgTypes, |
| 4613 | EPI: FunctionProtoType::ExtProtoInfo(CC)); |
| 4614 | } |
| 4615 | |
| 4616 | void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc, |
| 4617 | SourceLocation ScopeLoc, QualType FnType, |
| 4618 | llvm::Function *Fn, bool CurFuncIsThunk) { |
| 4619 | StringRef Name; |
| 4620 | StringRef LinkageName; |
| 4621 | |
| 4622 | FnBeginRegionCount.push_back(x: LexicalBlockStack.size()); |
| 4623 | |
| 4624 | const Decl *D = GD.getDecl(); |
| 4625 | bool HasDecl = (D != nullptr); |
| 4626 | |
| 4627 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 4628 | llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; |
| 4629 | llvm::DIFile *Unit = getOrCreateFile(Loc); |
| 4630 | llvm::DIScope *FDContext = Unit; |
| 4631 | llvm::DINodeArray TParamsArray; |
| 4632 | if (!HasDecl) { |
| 4633 | // Use llvm function name. |
| 4634 | LinkageName = Fn->getName(); |
| 4635 | } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 4636 | // If there is a subprogram for this function available then use it. |
| 4637 | auto FI = SPCache.find(Val: FD->getCanonicalDecl()); |
| 4638 | if (FI != SPCache.end()) { |
| 4639 | auto *SP = dyn_cast_or_null<llvm::DISubprogram>(Val&: FI->second); |
| 4640 | if (SP && SP->isDefinition()) { |
| 4641 | LexicalBlockStack.emplace_back(args&: SP); |
| 4642 | RegionMap[D].reset(MD: SP); |
| 4643 | return; |
| 4644 | } |
| 4645 | } |
| 4646 | collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, |
| 4647 | TParamsArray, Flags); |
| 4648 | } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D)) { |
| 4649 | Name = getObjCMethodName(OMD); |
| 4650 | Flags |= llvm::DINode::FlagPrototyped; |
| 4651 | } else if (isa<VarDecl>(Val: D) && |
| 4652 | GD.getDynamicInitKind() != DynamicInitKind::NoStub) { |
| 4653 | // This is a global initializer or atexit destructor for a global variable. |
| 4654 | Name = getDynamicInitializerName(VD: cast<VarDecl>(Val: D), StubKind: GD.getDynamicInitKind(), |
| 4655 | InitFn: Fn); |
| 4656 | } else { |
| 4657 | Name = Fn->getName(); |
| 4658 | |
| 4659 | if (isa<BlockDecl>(Val: D)) |
| 4660 | LinkageName = Name; |
| 4661 | |
| 4662 | Flags |= llvm::DINode::FlagPrototyped; |
| 4663 | } |
| 4664 | Name.consume_front(Prefix: "\01" ); |
| 4665 | |
| 4666 | assert((!D || !isa<VarDecl>(D) || |
| 4667 | GD.getDynamicInitKind() != DynamicInitKind::NoStub) && |
| 4668 | "Unexpected DynamicInitKind !" ); |
| 4669 | |
| 4670 | if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() || |
| 4671 | isa<VarDecl>(Val: D) || isa<CapturedDecl>(Val: D)) { |
| 4672 | Flags |= llvm::DINode::FlagArtificial; |
| 4673 | // Artificial functions should not silently reuse CurLoc. |
| 4674 | CurLoc = SourceLocation(); |
| 4675 | } |
| 4676 | |
| 4677 | if (CurFuncIsThunk) |
| 4678 | Flags |= llvm::DINode::FlagThunk; |
| 4679 | |
| 4680 | if (Fn->hasLocalLinkage()) |
| 4681 | SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; |
| 4682 | if (CGM.getLangOpts().Optimize) |
| 4683 | SPFlags |= llvm::DISubprogram::SPFlagOptimized; |
| 4684 | |
| 4685 | llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs(); |
| 4686 | llvm::DISubprogram::DISPFlags SPFlagsForDef = |
| 4687 | SPFlags | llvm::DISubprogram::SPFlagDefinition; |
| 4688 | |
| 4689 | const unsigned LineNo = getLineNumber(Loc: Loc.isValid() ? Loc : CurLoc); |
| 4690 | unsigned ScopeLine = getLineNumber(Loc: ScopeLoc); |
| 4691 | llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, F: Unit); |
| 4692 | llvm::DISubprogram *Decl = nullptr; |
| 4693 | llvm::DINodeArray Annotations = nullptr; |
| 4694 | if (D) { |
| 4695 | Decl = isa<ObjCMethodDecl>(Val: D) |
| 4696 | ? getObjCMethodDeclaration(D, FnType: DIFnType, LineNo, Flags, SPFlags) |
| 4697 | : getFunctionDeclaration(D); |
| 4698 | Annotations = CollectBTFDeclTagAnnotations(D); |
| 4699 | } |
| 4700 | |
| 4701 | // FIXME: The function declaration we're constructing here is mostly reusing |
| 4702 | // declarations from CXXMethodDecl and not constructing new ones for arbitrary |
| 4703 | // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for |
| 4704 | // all subprograms instead of the actual context since subprogram definitions |
| 4705 | // are emitted as CU level entities by the backend. |
| 4706 | llvm::DISubprogram *SP = DBuilder.createFunction( |
| 4707 | Scope: FDContext, Name, LinkageName, File: Unit, LineNo, Ty: DIFnType, ScopeLine, |
| 4708 | Flags: FlagsForDef, SPFlags: SPFlagsForDef, TParams: TParamsArray.get(), Decl, ThrownTypes: nullptr, |
| 4709 | Annotations, TargetFuncName: "" , UseKeyInstructions: CGM.getCodeGenOpts().DebugKeyInstructions); |
| 4710 | Fn->setSubprogram(SP); |
| 4711 | |
| 4712 | // We might get here with a VarDecl in the case we're generating |
| 4713 | // code for the initialization of globals. Do not record these decls |
| 4714 | // as they will overwrite the actual VarDecl Decl in the cache. |
| 4715 | if (HasDecl && isa<FunctionDecl>(Val: D)) |
| 4716 | DeclCache[D->getCanonicalDecl()].reset(MD: SP); |
| 4717 | |
| 4718 | // Push the function onto the lexical block stack. |
| 4719 | LexicalBlockStack.emplace_back(args&: SP); |
| 4720 | |
| 4721 | if (HasDecl) |
| 4722 | RegionMap[D].reset(MD: SP); |
| 4723 | } |
| 4724 | |
| 4725 | void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, |
| 4726 | QualType FnType, llvm::Function *Fn) { |
| 4727 | StringRef Name; |
| 4728 | StringRef LinkageName; |
| 4729 | |
| 4730 | const Decl *D = GD.getDecl(); |
| 4731 | if (!D) |
| 4732 | return; |
| 4733 | |
| 4734 | llvm::TimeTraceScope TimeScope("DebugFunction" , [&]() { |
| 4735 | return GetName(D, Qualified: true); |
| 4736 | }); |
| 4737 | |
| 4738 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 4739 | llvm::DIFile *Unit = getOrCreateFile(Loc); |
| 4740 | bool IsDeclForCallSite = Fn ? true : false; |
| 4741 | llvm::DIScope *FDContext = |
| 4742 | IsDeclForCallSite ? Unit : getDeclContextDescriptor(D); |
| 4743 | llvm::DINodeArray TParamsArray; |
| 4744 | if (isa<FunctionDecl>(Val: D)) { |
| 4745 | // If there is a DISubprogram for this function available then use it. |
| 4746 | collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, |
| 4747 | TParamsArray, Flags); |
| 4748 | } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D)) { |
| 4749 | Name = getObjCMethodName(OMD); |
| 4750 | Flags |= llvm::DINode::FlagPrototyped; |
| 4751 | } else { |
| 4752 | llvm_unreachable("not a function or ObjC method" ); |
| 4753 | } |
| 4754 | Name.consume_front(Prefix: "\01" ); |
| 4755 | |
| 4756 | if (D->isImplicit()) { |
| 4757 | Flags |= llvm::DINode::FlagArtificial; |
| 4758 | // Artificial functions without a location should not silently reuse CurLoc. |
| 4759 | if (Loc.isInvalid()) |
| 4760 | CurLoc = SourceLocation(); |
| 4761 | } |
| 4762 | unsigned LineNo = getLineNumber(Loc); |
| 4763 | unsigned ScopeLine = 0; |
| 4764 | llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; |
| 4765 | if (CGM.getLangOpts().Optimize) |
| 4766 | SPFlags |= llvm::DISubprogram::SPFlagOptimized; |
| 4767 | |
| 4768 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D); |
| 4769 | llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, F: Unit); |
| 4770 | // Key Instructions: Don't set flag on declarations. |
| 4771 | assert(~SPFlags & llvm::DISubprogram::SPFlagDefinition); |
| 4772 | llvm::DISubprogram *SP = DBuilder.createFunction( |
| 4773 | Scope: FDContext, Name, LinkageName, File: Unit, LineNo, Ty: STy, ScopeLine, Flags, |
| 4774 | SPFlags, TParams: TParamsArray.get(), Decl: nullptr, ThrownTypes: nullptr, Annotations, |
| 4775 | /*TargetFunctionName*/ TargetFuncName: "" , /*UseKeyInstructions*/ false); |
| 4776 | |
| 4777 | // Preserve btf_decl_tag attributes for parameters of extern functions |
| 4778 | // for BPF target. The parameters created in this loop are attached as |
| 4779 | // DISubprogram's retainedNodes in the DIBuilder::finalize() call. |
| 4780 | if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) { |
| 4781 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 4782 | llvm::DITypeRefArray ParamTypes = STy->getTypeArray(); |
| 4783 | unsigned ArgNo = 1; |
| 4784 | for (ParmVarDecl *PD : FD->parameters()) { |
| 4785 | llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(D: PD); |
| 4786 | DBuilder.createParameterVariable( |
| 4787 | Scope: SP, Name: PD->getName(), ArgNo, File: Unit, LineNo, Ty: ParamTypes[ArgNo], AlwaysPreserve: true, |
| 4788 | Flags: llvm::DINode::FlagZero, Annotations: ParamAnnotations); |
| 4789 | ++ArgNo; |
| 4790 | } |
| 4791 | } |
| 4792 | } |
| 4793 | |
| 4794 | if (IsDeclForCallSite) |
| 4795 | Fn->setSubprogram(SP); |
| 4796 | } |
| 4797 | |
| 4798 | void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke, |
| 4799 | QualType CalleeType, |
| 4800 | const FunctionDecl *CalleeDecl) { |
| 4801 | if (!CallOrInvoke) |
| 4802 | return; |
| 4803 | auto *Func = CallOrInvoke->getCalledFunction(); |
| 4804 | if (!Func) |
| 4805 | return; |
| 4806 | if (Func->getSubprogram()) |
| 4807 | return; |
| 4808 | |
| 4809 | // Do not emit a declaration subprogram for a function with nodebug |
| 4810 | // attribute, or if call site info isn't required. |
| 4811 | if (CalleeDecl->hasAttr<NoDebugAttr>() || |
| 4812 | getCallSiteRelatedAttrs() == llvm::DINode::FlagZero) |
| 4813 | return; |
| 4814 | |
| 4815 | // If there is no DISubprogram attached to the function being called, |
| 4816 | // create the one describing the function in order to have complete |
| 4817 | // call site debug info. |
| 4818 | if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined()) |
| 4819 | EmitFunctionDecl(GD: CalleeDecl, Loc: CalleeDecl->getLocation(), FnType: CalleeType, Fn: Func); |
| 4820 | } |
| 4821 | |
| 4822 | void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) { |
| 4823 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
| 4824 | // If there is a subprogram for this function available then use it. |
| 4825 | auto FI = SPCache.find(Val: FD->getCanonicalDecl()); |
| 4826 | llvm::DISubprogram *SP = nullptr; |
| 4827 | if (FI != SPCache.end()) |
| 4828 | SP = dyn_cast_or_null<llvm::DISubprogram>(Val&: FI->second); |
| 4829 | if (!SP || !SP->isDefinition()) |
| 4830 | SP = getFunctionStub(GD); |
| 4831 | FnBeginRegionCount.push_back(x: LexicalBlockStack.size()); |
| 4832 | LexicalBlockStack.emplace_back(args&: SP); |
| 4833 | setInlinedAt(Builder.getCurrentDebugLocation()); |
| 4834 | EmitLocation(Builder, Loc: FD->getLocation()); |
| 4835 | } |
| 4836 | |
| 4837 | void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) { |
| 4838 | assert(CurInlinedAt && "unbalanced inline scope stack" ); |
| 4839 | EmitFunctionEnd(Builder, Fn: nullptr); |
| 4840 | setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt()); |
| 4841 | } |
| 4842 | |
| 4843 | void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) { |
| 4844 | // Update our current location |
| 4845 | setLocation(Loc); |
| 4846 | |
| 4847 | if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty()) |
| 4848 | return; |
| 4849 | |
| 4850 | llvm::MDNode *Scope = LexicalBlockStack.back(); |
| 4851 | Builder.SetCurrentDebugLocation( |
| 4852 | llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line: getLineNumber(Loc: CurLoc), |
| 4853 | Column: getColumnNumber(Loc: CurLoc), Scope, InlinedAt: CurInlinedAt)); |
| 4854 | } |
| 4855 | |
| 4856 | void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { |
| 4857 | llvm::MDNode *Back = nullptr; |
| 4858 | if (!LexicalBlockStack.empty()) |
| 4859 | Back = LexicalBlockStack.back().get(); |
| 4860 | LexicalBlockStack.emplace_back(args: DBuilder.createLexicalBlock( |
| 4861 | Scope: cast<llvm::DIScope>(Val: Back), File: getOrCreateFile(Loc: CurLoc), Line: getLineNumber(Loc: CurLoc), |
| 4862 | Col: getColumnNumber(Loc: CurLoc))); |
| 4863 | } |
| 4864 | |
| 4865 | void CGDebugInfo::AppendAddressSpaceXDeref( |
| 4866 | unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const { |
| 4867 | std::optional<unsigned> DWARFAddressSpace = |
| 4868 | CGM.getTarget().getDWARFAddressSpace(AddressSpace); |
| 4869 | if (!DWARFAddressSpace) |
| 4870 | return; |
| 4871 | |
| 4872 | Expr.push_back(Elt: llvm::dwarf::DW_OP_constu); |
| 4873 | Expr.push_back(Elt: *DWARFAddressSpace); |
| 4874 | Expr.push_back(Elt: llvm::dwarf::DW_OP_swap); |
| 4875 | Expr.push_back(Elt: llvm::dwarf::DW_OP_xderef); |
| 4876 | } |
| 4877 | |
| 4878 | void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, |
| 4879 | SourceLocation Loc) { |
| 4880 | // Set our current location. |
| 4881 | setLocation(Loc); |
| 4882 | |
| 4883 | // Emit a line table change for the current location inside the new scope. |
| 4884 | Builder.SetCurrentDebugLocation(llvm::DILocation::get( |
| 4885 | Context&: CGM.getLLVMContext(), Line: getLineNumber(Loc), Column: getColumnNumber(Loc), |
| 4886 | Scope: LexicalBlockStack.back(), InlinedAt: CurInlinedAt)); |
| 4887 | |
| 4888 | if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
| 4889 | return; |
| 4890 | |
| 4891 | // Create a new lexical block and push it on the stack. |
| 4892 | CreateLexicalBlock(Loc); |
| 4893 | } |
| 4894 | |
| 4895 | void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, |
| 4896 | SourceLocation Loc) { |
| 4897 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
| 4898 | |
| 4899 | // Provide an entry in the line table for the end of the block. |
| 4900 | EmitLocation(Builder, Loc); |
| 4901 | |
| 4902 | if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
| 4903 | return; |
| 4904 | |
| 4905 | LexicalBlockStack.pop_back(); |
| 4906 | } |
| 4907 | |
| 4908 | void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) { |
| 4909 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
| 4910 | unsigned RCount = FnBeginRegionCount.back(); |
| 4911 | assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch" ); |
| 4912 | |
| 4913 | // Pop all regions for this function. |
| 4914 | while (LexicalBlockStack.size() != RCount) { |
| 4915 | // Provide an entry in the line table for the end of the block. |
| 4916 | EmitLocation(Builder, Loc: CurLoc); |
| 4917 | LexicalBlockStack.pop_back(); |
| 4918 | } |
| 4919 | FnBeginRegionCount.pop_back(); |
| 4920 | |
| 4921 | if (Fn && Fn->getSubprogram()) |
| 4922 | DBuilder.finalizeSubprogram(SP: Fn->getSubprogram()); |
| 4923 | } |
| 4924 | |
| 4925 | CGDebugInfo::BlockByRefType |
| 4926 | CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, |
| 4927 | uint64_t *XOffset) { |
| 4928 | SmallVector<llvm::Metadata *, 5> EltTys; |
| 4929 | QualType FType; |
| 4930 | uint64_t FieldSize, FieldOffset; |
| 4931 | uint32_t FieldAlign; |
| 4932 | |
| 4933 | llvm::DIFile *Unit = getOrCreateFile(Loc: VD->getLocation()); |
| 4934 | QualType Type = VD->getType(); |
| 4935 | |
| 4936 | FieldOffset = 0; |
| 4937 | FType = CGM.getContext().getPointerType(T: CGM.getContext().VoidTy); |
| 4938 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__isa" , Offset: &FieldOffset)); |
| 4939 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__forwarding" , Offset: &FieldOffset)); |
| 4940 | FType = CGM.getContext().IntTy; |
| 4941 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__flags" , Offset: &FieldOffset)); |
| 4942 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__size" , Offset: &FieldOffset)); |
| 4943 | |
| 4944 | bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Ty: Type, D: VD); |
| 4945 | if (HasCopyAndDispose) { |
| 4946 | FType = CGM.getContext().getPointerType(T: CGM.getContext().VoidTy); |
| 4947 | EltTys.push_back( |
| 4948 | Elt: CreateMemberType(Unit, FType, Name: "__copy_helper" , Offset: &FieldOffset)); |
| 4949 | EltTys.push_back( |
| 4950 | Elt: CreateMemberType(Unit, FType, Name: "__destroy_helper" , Offset: &FieldOffset)); |
| 4951 | } |
| 4952 | bool HasByrefExtendedLayout; |
| 4953 | Qualifiers::ObjCLifetime Lifetime; |
| 4954 | if (CGM.getContext().getByrefLifetime(Ty: Type, Lifetime, |
| 4955 | HasByrefExtendedLayout) && |
| 4956 | HasByrefExtendedLayout) { |
| 4957 | FType = CGM.getContext().getPointerType(T: CGM.getContext().VoidTy); |
| 4958 | EltTys.push_back( |
| 4959 | Elt: CreateMemberType(Unit, FType, Name: "__byref_variable_layout" , Offset: &FieldOffset)); |
| 4960 | } |
| 4961 | |
| 4962 | CharUnits Align = CGM.getContext().getDeclAlign(D: VD); |
| 4963 | if (Align > CGM.getContext().toCharUnitsFromBits( |
| 4964 | BitSize: CGM.getTarget().getPointerAlign(AddrSpace: LangAS::Default))) { |
| 4965 | CharUnits FieldOffsetInBytes = |
| 4966 | CGM.getContext().toCharUnitsFromBits(BitSize: FieldOffset); |
| 4967 | CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align); |
| 4968 | CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes; |
| 4969 | |
| 4970 | if (NumPaddingBytes.isPositive()) { |
| 4971 | llvm::APInt pad(32, NumPaddingBytes.getQuantity()); |
| 4972 | FType = CGM.getContext().getConstantArrayType( |
| 4973 | EltTy: CGM.getContext().CharTy, ArySize: pad, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 4974 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "" , Offset: &FieldOffset)); |
| 4975 | } |
| 4976 | } |
| 4977 | |
| 4978 | FType = Type; |
| 4979 | llvm::DIType *WrappedTy = getOrCreateType(Ty: FType, Unit); |
| 4980 | FieldSize = CGM.getContext().getTypeSize(T: FType); |
| 4981 | FieldAlign = CGM.getContext().toBits(CharSize: Align); |
| 4982 | |
| 4983 | *XOffset = FieldOffset; |
| 4984 | llvm::DIType *FieldTy = DBuilder.createMemberType( |
| 4985 | Scope: Unit, Name: VD->getName(), File: Unit, LineNo: 0, SizeInBits: FieldSize, AlignInBits: FieldAlign, OffsetInBits: FieldOffset, |
| 4986 | Flags: llvm::DINode::FlagZero, Ty: WrappedTy); |
| 4987 | EltTys.push_back(Elt: FieldTy); |
| 4988 | FieldOffset += FieldSize; |
| 4989 | |
| 4990 | llvm::DINodeArray Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
| 4991 | return {.BlockByRefWrapper: DBuilder.createStructType(Scope: Unit, Name: "" , File: Unit, LineNumber: 0, SizeInBits: FieldOffset, AlignInBits: 0, |
| 4992 | Flags: llvm::DINode::FlagZero, DerivedFrom: nullptr, Elements), |
| 4993 | .WrappedType: WrappedTy}; |
| 4994 | } |
| 4995 | |
| 4996 | llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD, |
| 4997 | llvm::Value *Storage, |
| 4998 | std::optional<unsigned> ArgNo, |
| 4999 | CGBuilderTy &Builder, |
| 5000 | const bool UsePointerValue) { |
| 5001 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 5002 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
| 5003 | if (VD->hasAttr<NoDebugAttr>()) |
| 5004 | return nullptr; |
| 5005 | |
| 5006 | const bool VarIsArtificial = IsArtificial(VD); |
| 5007 | |
| 5008 | llvm::DIFile *Unit = nullptr; |
| 5009 | if (!VarIsArtificial) |
| 5010 | Unit = getOrCreateFile(Loc: VD->getLocation()); |
| 5011 | llvm::DIType *Ty; |
| 5012 | uint64_t XOffset = 0; |
| 5013 | if (VD->hasAttr<BlocksAttr>()) |
| 5014 | Ty = EmitTypeForVarWithBlocksAttr(VD, XOffset: &XOffset).WrappedType; |
| 5015 | else |
| 5016 | Ty = getOrCreateType(Ty: VD->getType(), Unit); |
| 5017 | |
| 5018 | // If there is no debug info for this type then do not emit debug info |
| 5019 | // for this variable. |
| 5020 | if (!Ty) |
| 5021 | return nullptr; |
| 5022 | |
| 5023 | // Get location information. |
| 5024 | unsigned Line = 0; |
| 5025 | unsigned Column = 0; |
| 5026 | if (!VarIsArtificial) { |
| 5027 | Line = getLineNumber(Loc: VD->getLocation()); |
| 5028 | Column = getColumnNumber(Loc: VD->getLocation()); |
| 5029 | } |
| 5030 | SmallVector<uint64_t, 13> Expr; |
| 5031 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
| 5032 | if (VarIsArtificial) |
| 5033 | Flags |= llvm::DINode::FlagArtificial; |
| 5034 | |
| 5035 | auto Align = getDeclAlignIfRequired(D: VD, Ctx: CGM.getContext()); |
| 5036 | |
| 5037 | unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(T: VD->getType()); |
| 5038 | AppendAddressSpaceXDeref(AddressSpace, Expr); |
| 5039 | |
| 5040 | // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an |
| 5041 | // object pointer flag. |
| 5042 | if (const auto *IPD = dyn_cast<ImplicitParamDecl>(Val: VD)) { |
| 5043 | if (IPD->getParameterKind() == ImplicitParamKind::CXXThis || |
| 5044 | IPD->getParameterKind() == ImplicitParamKind::ObjCSelf) |
| 5045 | Flags |= llvm::DINode::FlagObjectPointer; |
| 5046 | } else if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: VD)) { |
| 5047 | if (PVD->isExplicitObjectParameter()) |
| 5048 | Flags |= llvm::DINode::FlagObjectPointer; |
| 5049 | } |
| 5050 | |
| 5051 | // Note: Older versions of clang used to emit byval references with an extra |
| 5052 | // DW_OP_deref, because they referenced the IR arg directly instead of |
| 5053 | // referencing an alloca. Newer versions of LLVM don't treat allocas |
| 5054 | // differently from other function arguments when used in a dbg.declare. |
| 5055 | auto *Scope = cast<llvm::DIScope>(Val&: LexicalBlockStack.back()); |
| 5056 | StringRef Name = VD->getName(); |
| 5057 | if (!Name.empty()) { |
| 5058 | // __block vars are stored on the heap if they are captured by a block that |
| 5059 | // can escape the local scope. |
| 5060 | if (VD->isEscapingByref()) { |
| 5061 | // Here, we need an offset *into* the alloca. |
| 5062 | CharUnits offset = CharUnits::fromQuantity(Quantity: 32); |
| 5063 | Expr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
| 5064 | // offset of __forwarding field |
| 5065 | offset = CGM.getContext().toCharUnitsFromBits( |
| 5066 | BitSize: CGM.getTarget().getPointerWidth(AddrSpace: LangAS::Default)); |
| 5067 | Expr.push_back(Elt: offset.getQuantity()); |
| 5068 | Expr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
| 5069 | Expr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
| 5070 | // offset of x field |
| 5071 | offset = CGM.getContext().toCharUnitsFromBits(BitSize: XOffset); |
| 5072 | Expr.push_back(Elt: offset.getQuantity()); |
| 5073 | } |
| 5074 | } else if (const auto *RT = dyn_cast<RecordType>(Val: VD->getType())) { |
| 5075 | // If VD is an anonymous union then Storage represents value for |
| 5076 | // all union fields. |
| 5077 | const RecordDecl *RD = RT->getDecl(); |
| 5078 | if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { |
| 5079 | // GDB has trouble finding local variables in anonymous unions, so we emit |
| 5080 | // artificial local variables for each of the members. |
| 5081 | // |
| 5082 | // FIXME: Remove this code as soon as GDB supports this. |
| 5083 | // The debug info verifier in LLVM operates based on the assumption that a |
| 5084 | // variable has the same size as its storage and we had to disable the |
| 5085 | // check for artificial variables. |
| 5086 | for (const auto *Field : RD->fields()) { |
| 5087 | llvm::DIType *FieldTy = getOrCreateType(Ty: Field->getType(), Unit); |
| 5088 | StringRef FieldName = Field->getName(); |
| 5089 | |
| 5090 | // Ignore unnamed fields. Do not ignore unnamed records. |
| 5091 | if (FieldName.empty() && !isa<RecordType>(Val: Field->getType())) |
| 5092 | continue; |
| 5093 | |
| 5094 | // Use VarDecl's Tag, Scope and Line number. |
| 5095 | auto FieldAlign = getDeclAlignIfRequired(D: Field, Ctx: CGM.getContext()); |
| 5096 | auto *D = DBuilder.createAutoVariable( |
| 5097 | Scope, Name: FieldName, File: Unit, LineNo: Line, Ty: FieldTy, AlwaysPreserve: CGM.getLangOpts().Optimize, |
| 5098 | Flags: Flags | llvm::DINode::FlagArtificial, AlignInBits: FieldAlign); |
| 5099 | |
| 5100 | // Insert an llvm.dbg.declare into the current block. |
| 5101 | DBuilder.insertDeclare(Storage, VarInfo: D, Expr: DBuilder.createExpression(Addr: Expr), |
| 5102 | DL: llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line, |
| 5103 | Column, Scope, |
| 5104 | InlinedAt: CurInlinedAt), |
| 5105 | InsertAtEnd: Builder.GetInsertBlock()); |
| 5106 | } |
| 5107 | } |
| 5108 | } |
| 5109 | |
| 5110 | // Clang stores the sret pointer provided by the caller in a static alloca. |
| 5111 | // Use DW_OP_deref to tell the debugger to load the pointer and treat it as |
| 5112 | // the address of the variable. |
| 5113 | if (UsePointerValue) { |
| 5114 | assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) && |
| 5115 | "Debug info already contains DW_OP_deref." ); |
| 5116 | Expr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
| 5117 | } |
| 5118 | |
| 5119 | // Create the descriptor for the variable. |
| 5120 | llvm::DILocalVariable *D = nullptr; |
| 5121 | if (ArgNo) { |
| 5122 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D: VD); |
| 5123 | D = DBuilder.createParameterVariable(Scope, Name, ArgNo: *ArgNo, File: Unit, LineNo: Line, Ty, |
| 5124 | AlwaysPreserve: CGM.getLangOpts().Optimize, Flags, |
| 5125 | Annotations); |
| 5126 | } else { |
| 5127 | // For normal local variable, we will try to find out whether 'VD' is the |
| 5128 | // copy parameter of coroutine. |
| 5129 | // If yes, we are going to use DIVariable of the origin parameter instead |
| 5130 | // of creating the new one. |
| 5131 | // If no, it might be a normal alloc, we just create a new one for it. |
| 5132 | |
| 5133 | // Check whether the VD is move parameters. |
| 5134 | auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * { |
| 5135 | // The scope of parameter and move-parameter should be distinct |
| 5136 | // DISubprogram. |
| 5137 | if (!isa<llvm::DISubprogram>(Val: Scope) || !Scope->isDistinct()) |
| 5138 | return nullptr; |
| 5139 | |
| 5140 | auto Iter = llvm::find_if(Range&: CoroutineParameterMappings, P: [&](auto &Pair) { |
| 5141 | Stmt *StmtPtr = const_cast<Stmt *>(Pair.second); |
| 5142 | if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(Val: StmtPtr)) { |
| 5143 | DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup(); |
| 5144 | Decl *Decl = DeclGroup.getSingleDecl(); |
| 5145 | if (VD == dyn_cast_or_null<VarDecl>(Val: Decl)) |
| 5146 | return true; |
| 5147 | } |
| 5148 | return false; |
| 5149 | }); |
| 5150 | |
| 5151 | if (Iter != CoroutineParameterMappings.end()) { |
| 5152 | ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first); |
| 5153 | auto Iter2 = llvm::find_if(Range&: ParamDbgMappings, P: [&](auto &DbgPair) { |
| 5154 | return DbgPair.first == PD && DbgPair.second->getScope() == Scope; |
| 5155 | }); |
| 5156 | if (Iter2 != ParamDbgMappings.end()) |
| 5157 | return const_cast<llvm::DILocalVariable *>(Iter2->second); |
| 5158 | } |
| 5159 | return nullptr; |
| 5160 | }; |
| 5161 | |
| 5162 | // If we couldn't find a move param DIVariable, create a new one. |
| 5163 | D = RemapCoroArgToLocalVar(); |
| 5164 | // Or we will create a new DIVariable for this Decl if D dose not exists. |
| 5165 | if (!D) |
| 5166 | D = DBuilder.createAutoVariable(Scope, Name, File: Unit, LineNo: Line, Ty, |
| 5167 | AlwaysPreserve: CGM.getLangOpts().Optimize, Flags, AlignInBits: Align); |
| 5168 | } |
| 5169 | // Insert an llvm.dbg.declare into the current block. |
| 5170 | DBuilder.insertDeclare(Storage, VarInfo: D, Expr: DBuilder.createExpression(Addr: Expr), |
| 5171 | DL: llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line, |
| 5172 | Column, Scope, InlinedAt: CurInlinedAt), |
| 5173 | InsertAtEnd: Builder.GetInsertBlock()); |
| 5174 | |
| 5175 | return D; |
| 5176 | } |
| 5177 | |
| 5178 | llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD, |
| 5179 | llvm::Value *Storage, |
| 5180 | std::optional<unsigned> ArgNo, |
| 5181 | CGBuilderTy &Builder, |
| 5182 | const bool UsePointerValue) { |
| 5183 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 5184 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
| 5185 | if (BD->hasAttr<NoDebugAttr>()) |
| 5186 | return nullptr; |
| 5187 | |
| 5188 | // Skip the tuple like case, we don't handle that here |
| 5189 | if (isa<DeclRefExpr>(Val: BD->getBinding())) |
| 5190 | return nullptr; |
| 5191 | |
| 5192 | llvm::DIFile *Unit = getOrCreateFile(Loc: BD->getLocation()); |
| 5193 | llvm::DIType *Ty = getOrCreateType(Ty: BD->getType(), Unit); |
| 5194 | |
| 5195 | // If there is no debug info for this type then do not emit debug info |
| 5196 | // for this variable. |
| 5197 | if (!Ty) |
| 5198 | return nullptr; |
| 5199 | |
| 5200 | auto Align = getDeclAlignIfRequired(D: BD, Ctx: CGM.getContext()); |
| 5201 | unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(T: BD->getType()); |
| 5202 | |
| 5203 | SmallVector<uint64_t, 3> Expr; |
| 5204 | AppendAddressSpaceXDeref(AddressSpace, Expr); |
| 5205 | |
| 5206 | // Clang stores the sret pointer provided by the caller in a static alloca. |
| 5207 | // Use DW_OP_deref to tell the debugger to load the pointer and treat it as |
| 5208 | // the address of the variable. |
| 5209 | if (UsePointerValue) { |
| 5210 | assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) && |
| 5211 | "Debug info already contains DW_OP_deref." ); |
| 5212 | Expr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
| 5213 | } |
| 5214 | |
| 5215 | unsigned Line = getLineNumber(Loc: BD->getLocation()); |
| 5216 | unsigned Column = getColumnNumber(Loc: BD->getLocation()); |
| 5217 | StringRef Name = BD->getName(); |
| 5218 | auto *Scope = cast<llvm::DIScope>(Val&: LexicalBlockStack.back()); |
| 5219 | // Create the descriptor for the variable. |
| 5220 | llvm::DILocalVariable *D = DBuilder.createAutoVariable( |
| 5221 | Scope, Name, File: Unit, LineNo: Line, Ty, AlwaysPreserve: CGM.getLangOpts().Optimize, |
| 5222 | Flags: llvm::DINode::FlagZero, AlignInBits: Align); |
| 5223 | |
| 5224 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: BD->getBinding())) { |
| 5225 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl())) { |
| 5226 | const unsigned fieldIndex = FD->getFieldIndex(); |
| 5227 | const clang::CXXRecordDecl *parent = |
| 5228 | (const CXXRecordDecl *)FD->getParent(); |
| 5229 | const ASTRecordLayout &layout = |
| 5230 | CGM.getContext().getASTRecordLayout(D: parent); |
| 5231 | const uint64_t fieldOffset = layout.getFieldOffset(FieldNo: fieldIndex); |
| 5232 | if (FD->isBitField()) { |
| 5233 | const CGRecordLayout &RL = |
| 5234 | CGM.getTypes().getCGRecordLayout(FD->getParent()); |
| 5235 | const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD); |
| 5236 | // Use DW_OP_plus_uconst to adjust to the start of the bitfield |
| 5237 | // storage. |
| 5238 | if (!Info.StorageOffset.isZero()) { |
| 5239 | Expr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
| 5240 | Expr.push_back(Elt: Info.StorageOffset.getQuantity()); |
| 5241 | } |
| 5242 | // Use LLVM_extract_bits to extract the appropriate bits from this |
| 5243 | // bitfield. |
| 5244 | Expr.push_back(Elt: Info.IsSigned |
| 5245 | ? llvm::dwarf::DW_OP_LLVM_extract_bits_sext |
| 5246 | : llvm::dwarf::DW_OP_LLVM_extract_bits_zext); |
| 5247 | Expr.push_back(Elt: Info.Offset); |
| 5248 | // If we have an oversized bitfield then the value won't be more than |
| 5249 | // the size of the type. |
| 5250 | const uint64_t TypeSize = CGM.getContext().getTypeSize(T: BD->getType()); |
| 5251 | Expr.push_back(Elt: std::min(a: (uint64_t)Info.Size, b: TypeSize)); |
| 5252 | } else if (fieldOffset != 0) { |
| 5253 | assert(fieldOffset % CGM.getContext().getCharWidth() == 0 && |
| 5254 | "Unexpected non-bitfield with non-byte-aligned offset" ); |
| 5255 | Expr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
| 5256 | Expr.push_back( |
| 5257 | Elt: CGM.getContext().toCharUnitsFromBits(BitSize: fieldOffset).getQuantity()); |
| 5258 | } |
| 5259 | } |
| 5260 | } else if (const ArraySubscriptExpr *ASE = |
| 5261 | dyn_cast<ArraySubscriptExpr>(Val: BD->getBinding())) { |
| 5262 | if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: ASE->getIdx())) { |
| 5263 | const uint64_t value = IL->getValue().getZExtValue(); |
| 5264 | const uint64_t typeSize = CGM.getContext().getTypeSize(T: BD->getType()); |
| 5265 | |
| 5266 | if (value != 0) { |
| 5267 | Expr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
| 5268 | Expr.push_back(Elt: CGM.getContext() |
| 5269 | .toCharUnitsFromBits(BitSize: value * typeSize) |
| 5270 | .getQuantity()); |
| 5271 | } |
| 5272 | } |
| 5273 | } |
| 5274 | |
| 5275 | // Insert an llvm.dbg.declare into the current block. |
| 5276 | DBuilder.insertDeclare(Storage, VarInfo: D, Expr: DBuilder.createExpression(Addr: Expr), |
| 5277 | DL: llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line, |
| 5278 | Column, Scope, InlinedAt: CurInlinedAt), |
| 5279 | InsertAtEnd: Builder.GetInsertBlock()); |
| 5280 | |
| 5281 | return D; |
| 5282 | } |
| 5283 | |
| 5284 | llvm::DILocalVariable * |
| 5285 | CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage, |
| 5286 | CGBuilderTy &Builder, |
| 5287 | const bool UsePointerValue) { |
| 5288 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 5289 | |
| 5290 | if (auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) { |
| 5291 | for (BindingDecl *B : DD->flat_bindings()) |
| 5292 | EmitDeclare(BD: B, Storage, ArgNo: std::nullopt, Builder, |
| 5293 | UsePointerValue: VD->getType()->isReferenceType()); |
| 5294 | // Don't emit an llvm.dbg.declare for the composite storage as it doesn't |
| 5295 | // correspond to a user variable. |
| 5296 | return nullptr; |
| 5297 | } |
| 5298 | |
| 5299 | return EmitDeclare(VD, Storage, ArgNo: std::nullopt, Builder, UsePointerValue); |
| 5300 | } |
| 5301 | |
| 5302 | void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) { |
| 5303 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 5304 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
| 5305 | |
| 5306 | if (D->hasAttr<NoDebugAttr>()) |
| 5307 | return; |
| 5308 | |
| 5309 | auto *Scope = cast<llvm::DIScope>(Val&: LexicalBlockStack.back()); |
| 5310 | llvm::DIFile *Unit = getOrCreateFile(Loc: D->getLocation()); |
| 5311 | |
| 5312 | // Get location information. |
| 5313 | unsigned Line = getLineNumber(Loc: D->getLocation()); |
| 5314 | unsigned Column = getColumnNumber(Loc: D->getLocation()); |
| 5315 | |
| 5316 | StringRef Name = D->getName(); |
| 5317 | |
| 5318 | // Create the descriptor for the label. |
| 5319 | auto *L = DBuilder.createLabel( |
| 5320 | Scope, Name, File: Unit, LineNo: Line, Column, /*IsArtificial=*/false, |
| 5321 | /*CoroSuspendIdx=*/std::nullopt, AlwaysPreserve: CGM.getLangOpts().Optimize); |
| 5322 | |
| 5323 | // Insert an llvm.dbg.label into the current block. |
| 5324 | DBuilder.insertLabel(LabelInfo: L, |
| 5325 | DL: llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line, Column, |
| 5326 | Scope, InlinedAt: CurInlinedAt), |
| 5327 | InsertPt: Builder.GetInsertBlock()->end()); |
| 5328 | } |
| 5329 | |
| 5330 | llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy, |
| 5331 | llvm::DIType *Ty) { |
| 5332 | llvm::DIType *CachedTy = getTypeOrNull(Ty: QualTy); |
| 5333 | if (CachedTy) |
| 5334 | Ty = CachedTy; |
| 5335 | return DBuilder.createObjectPointerType(Ty, /*Implicit=*/true); |
| 5336 | } |
| 5337 | |
| 5338 | void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( |
| 5339 | const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder, |
| 5340 | const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) { |
| 5341 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 5342 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
| 5343 | |
| 5344 | if (Builder.GetInsertBlock() == nullptr) |
| 5345 | return; |
| 5346 | if (VD->hasAttr<NoDebugAttr>()) |
| 5347 | return; |
| 5348 | |
| 5349 | bool isByRef = VD->hasAttr<BlocksAttr>(); |
| 5350 | |
| 5351 | uint64_t XOffset = 0; |
| 5352 | llvm::DIFile *Unit = getOrCreateFile(Loc: VD->getLocation()); |
| 5353 | llvm::DIType *Ty; |
| 5354 | if (isByRef) |
| 5355 | Ty = EmitTypeForVarWithBlocksAttr(VD, XOffset: &XOffset).WrappedType; |
| 5356 | else |
| 5357 | Ty = getOrCreateType(Ty: VD->getType(), Unit); |
| 5358 | |
| 5359 | // Self is passed along as an implicit non-arg variable in a |
| 5360 | // block. Mark it as the object pointer. |
| 5361 | if (const auto *IPD = dyn_cast<ImplicitParamDecl>(Val: VD)) |
| 5362 | if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf) |
| 5363 | Ty = CreateSelfType(QualTy: VD->getType(), Ty); |
| 5364 | |
| 5365 | // Get location information. |
| 5366 | const unsigned Line = |
| 5367 | getLineNumber(Loc: VD->getLocation().isValid() ? VD->getLocation() : CurLoc); |
| 5368 | unsigned Column = getColumnNumber(Loc: VD->getLocation()); |
| 5369 | |
| 5370 | const llvm::DataLayout &target = CGM.getDataLayout(); |
| 5371 | |
| 5372 | CharUnits offset = CharUnits::fromQuantity( |
| 5373 | Quantity: target.getStructLayout(Ty: blockInfo.StructureType) |
| 5374 | ->getElementOffset(Idx: blockInfo.getCapture(var: VD).getIndex())); |
| 5375 | |
| 5376 | SmallVector<uint64_t, 9> addr; |
| 5377 | addr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
| 5378 | addr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
| 5379 | addr.push_back(Elt: offset.getQuantity()); |
| 5380 | if (isByRef) { |
| 5381 | addr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
| 5382 | addr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
| 5383 | // offset of __forwarding field |
| 5384 | offset = |
| 5385 | CGM.getContext().toCharUnitsFromBits(BitSize: target.getPointerSizeInBits(AS: 0)); |
| 5386 | addr.push_back(Elt: offset.getQuantity()); |
| 5387 | addr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
| 5388 | addr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
| 5389 | // offset of x field |
| 5390 | offset = CGM.getContext().toCharUnitsFromBits(BitSize: XOffset); |
| 5391 | addr.push_back(Elt: offset.getQuantity()); |
| 5392 | } |
| 5393 | |
| 5394 | // Create the descriptor for the variable. |
| 5395 | auto Align = getDeclAlignIfRequired(D: VD, Ctx: CGM.getContext()); |
| 5396 | auto *D = DBuilder.createAutoVariable( |
| 5397 | Scope: cast<llvm::DILocalScope>(Val&: LexicalBlockStack.back()), Name: VD->getName(), File: Unit, |
| 5398 | LineNo: Line, Ty, AlwaysPreserve: false, Flags: llvm::DINode::FlagZero, AlignInBits: Align); |
| 5399 | |
| 5400 | // Insert an llvm.dbg.declare into the current block. |
| 5401 | auto DL = llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line, Column, |
| 5402 | Scope: LexicalBlockStack.back(), InlinedAt: CurInlinedAt); |
| 5403 | auto *Expr = DBuilder.createExpression(Addr: addr); |
| 5404 | if (InsertPoint) |
| 5405 | DBuilder.insertDeclare(Storage, VarInfo: D, Expr, DL, InsertPt: InsertPoint->getIterator()); |
| 5406 | else |
| 5407 | DBuilder.insertDeclare(Storage, VarInfo: D, Expr, DL, InsertAtEnd: Builder.GetInsertBlock()); |
| 5408 | } |
| 5409 | |
| 5410 | llvm::DILocalVariable * |
| 5411 | CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, |
| 5412 | unsigned ArgNo, CGBuilderTy &Builder, |
| 5413 | bool UsePointerValue) { |
| 5414 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 5415 | return EmitDeclare(VD, Storage: AI, ArgNo, Builder, UsePointerValue); |
| 5416 | } |
| 5417 | |
| 5418 | namespace { |
| 5419 | struct BlockLayoutChunk { |
| 5420 | uint64_t OffsetInBits; |
| 5421 | const BlockDecl::Capture *Capture; |
| 5422 | }; |
| 5423 | bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { |
| 5424 | return l.OffsetInBits < r.OffsetInBits; |
| 5425 | } |
| 5426 | } // namespace |
| 5427 | |
| 5428 | void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare( |
| 5429 | const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc, |
| 5430 | const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit, |
| 5431 | SmallVectorImpl<llvm::Metadata *> &Fields) { |
| 5432 | // Blocks in OpenCL have unique constraints which make the standard fields |
| 5433 | // redundant while requiring size and align fields for enqueue_kernel. See |
| 5434 | // initializeForBlockHeader in CGBlocks.cpp |
| 5435 | if (CGM.getLangOpts().OpenCL) { |
| 5436 | Fields.push_back(Elt: createFieldType(name: "__size" , type: Context.IntTy, loc: Loc, AS: AS_public, |
| 5437 | offsetInBits: BlockLayout.getElementOffsetInBits(Idx: 0), |
| 5438 | tunit: Unit, scope: Unit)); |
| 5439 | Fields.push_back(Elt: createFieldType(name: "__align" , type: Context.IntTy, loc: Loc, AS: AS_public, |
| 5440 | offsetInBits: BlockLayout.getElementOffsetInBits(Idx: 1), |
| 5441 | tunit: Unit, scope: Unit)); |
| 5442 | } else { |
| 5443 | Fields.push_back(Elt: createFieldType(name: "__isa" , type: Context.VoidPtrTy, loc: Loc, AS: AS_public, |
| 5444 | offsetInBits: BlockLayout.getElementOffsetInBits(Idx: 0), |
| 5445 | tunit: Unit, scope: Unit)); |
| 5446 | Fields.push_back(Elt: createFieldType(name: "__flags" , type: Context.IntTy, loc: Loc, AS: AS_public, |
| 5447 | offsetInBits: BlockLayout.getElementOffsetInBits(Idx: 1), |
| 5448 | tunit: Unit, scope: Unit)); |
| 5449 | Fields.push_back( |
| 5450 | Elt: createFieldType(name: "__reserved" , type: Context.IntTy, loc: Loc, AS: AS_public, |
| 5451 | offsetInBits: BlockLayout.getElementOffsetInBits(Idx: 2), tunit: Unit, scope: Unit)); |
| 5452 | auto *FnTy = Block.getBlockExpr()->getFunctionType(); |
| 5453 | auto FnPtrType = CGM.getContext().getPointerType(T: FnTy->desugar()); |
| 5454 | Fields.push_back(Elt: createFieldType(name: "__FuncPtr" , type: FnPtrType, loc: Loc, AS: AS_public, |
| 5455 | offsetInBits: BlockLayout.getElementOffsetInBits(Idx: 3), |
| 5456 | tunit: Unit, scope: Unit)); |
| 5457 | Fields.push_back(Elt: createFieldType( |
| 5458 | name: "__descriptor" , |
| 5459 | type: Context.getPointerType(T: Block.NeedsCopyDispose |
| 5460 | ? Context.getBlockDescriptorExtendedType() |
| 5461 | : Context.getBlockDescriptorType()), |
| 5462 | loc: Loc, AS: AS_public, offsetInBits: BlockLayout.getElementOffsetInBits(Idx: 4), tunit: Unit, scope: Unit)); |
| 5463 | } |
| 5464 | } |
| 5465 | |
| 5466 | void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, |
| 5467 | StringRef Name, |
| 5468 | unsigned ArgNo, |
| 5469 | llvm::AllocaInst *Alloca, |
| 5470 | CGBuilderTy &Builder) { |
| 5471 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 5472 | ASTContext &C = CGM.getContext(); |
| 5473 | const BlockDecl *blockDecl = block.getBlockDecl(); |
| 5474 | |
| 5475 | // Collect some general information about the block's location. |
| 5476 | SourceLocation loc = blockDecl->getCaretLocation(); |
| 5477 | llvm::DIFile *tunit = getOrCreateFile(Loc: loc); |
| 5478 | unsigned line = getLineNumber(Loc: loc); |
| 5479 | unsigned column = getColumnNumber(Loc: loc); |
| 5480 | |
| 5481 | // Build the debug-info type for the block literal. |
| 5482 | getDeclContextDescriptor(D: blockDecl); |
| 5483 | |
| 5484 | const llvm::StructLayout *blockLayout = |
| 5485 | CGM.getDataLayout().getStructLayout(Ty: block.StructureType); |
| 5486 | |
| 5487 | SmallVector<llvm::Metadata *, 16> fields; |
| 5488 | collectDefaultFieldsForBlockLiteralDeclare(Block: block, Context: C, Loc: loc, BlockLayout: *blockLayout, Unit: tunit, |
| 5489 | Fields&: fields); |
| 5490 | |
| 5491 | // We want to sort the captures by offset, not because DWARF |
| 5492 | // requires this, but because we're paranoid about debuggers. |
| 5493 | SmallVector<BlockLayoutChunk, 8> chunks; |
| 5494 | |
| 5495 | // 'this' capture. |
| 5496 | if (blockDecl->capturesCXXThis()) { |
| 5497 | BlockLayoutChunk chunk; |
| 5498 | chunk.OffsetInBits = |
| 5499 | blockLayout->getElementOffsetInBits(Idx: block.CXXThisIndex); |
| 5500 | chunk.Capture = nullptr; |
| 5501 | chunks.push_back(Elt: chunk); |
| 5502 | } |
| 5503 | |
| 5504 | // Variable captures. |
| 5505 | for (const auto &capture : blockDecl->captures()) { |
| 5506 | const VarDecl *variable = capture.getVariable(); |
| 5507 | const CGBlockInfo::Capture &captureInfo = block.getCapture(var: variable); |
| 5508 | |
| 5509 | // Ignore constant captures. |
| 5510 | if (captureInfo.isConstant()) |
| 5511 | continue; |
| 5512 | |
| 5513 | BlockLayoutChunk chunk; |
| 5514 | chunk.OffsetInBits = |
| 5515 | blockLayout->getElementOffsetInBits(Idx: captureInfo.getIndex()); |
| 5516 | chunk.Capture = &capture; |
| 5517 | chunks.push_back(Elt: chunk); |
| 5518 | } |
| 5519 | |
| 5520 | // Sort by offset. |
| 5521 | llvm::array_pod_sort(Start: chunks.begin(), End: chunks.end()); |
| 5522 | |
| 5523 | for (const BlockLayoutChunk &Chunk : chunks) { |
| 5524 | uint64_t offsetInBits = Chunk.OffsetInBits; |
| 5525 | const BlockDecl::Capture *capture = Chunk.Capture; |
| 5526 | |
| 5527 | // If we have a null capture, this must be the C++ 'this' capture. |
| 5528 | if (!capture) { |
| 5529 | QualType type; |
| 5530 | if (auto *Method = |
| 5531 | cast_or_null<CXXMethodDecl>(Val: blockDecl->getNonClosureContext())) |
| 5532 | type = Method->getThisType(); |
| 5533 | else if (auto *RDecl = dyn_cast<CXXRecordDecl>(Val: blockDecl->getParent())) |
| 5534 | type = QualType(RDecl->getTypeForDecl(), 0); |
| 5535 | else |
| 5536 | llvm_unreachable("unexpected block declcontext" ); |
| 5537 | |
| 5538 | fields.push_back(Elt: createFieldType(name: "this" , type, loc, AS: AS_public, |
| 5539 | offsetInBits, tunit, scope: tunit)); |
| 5540 | continue; |
| 5541 | } |
| 5542 | |
| 5543 | const VarDecl *variable = capture->getVariable(); |
| 5544 | StringRef name = variable->getName(); |
| 5545 | |
| 5546 | llvm::DIType *fieldType; |
| 5547 | if (capture->isByRef()) { |
| 5548 | TypeInfo PtrInfo = C.getTypeInfo(T: C.VoidPtrTy); |
| 5549 | auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0; |
| 5550 | // FIXME: This recomputes the layout of the BlockByRefWrapper. |
| 5551 | uint64_t xoffset; |
| 5552 | fieldType = |
| 5553 | EmitTypeForVarWithBlocksAttr(VD: variable, XOffset: &xoffset).BlockByRefWrapper; |
| 5554 | fieldType = DBuilder.createPointerType(PointeeTy: fieldType, SizeInBits: PtrInfo.Width); |
| 5555 | fieldType = DBuilder.createMemberType(Scope: tunit, Name: name, File: tunit, LineNo: line, |
| 5556 | SizeInBits: PtrInfo.Width, AlignInBits: Align, OffsetInBits: offsetInBits, |
| 5557 | Flags: llvm::DINode::FlagZero, Ty: fieldType); |
| 5558 | } else { |
| 5559 | auto Align = getDeclAlignIfRequired(D: variable, Ctx: CGM.getContext()); |
| 5560 | fieldType = createFieldType(name, type: variable->getType(), loc, AS: AS_public, |
| 5561 | offsetInBits, AlignInBits: Align, tunit, scope: tunit); |
| 5562 | } |
| 5563 | fields.push_back(Elt: fieldType); |
| 5564 | } |
| 5565 | |
| 5566 | SmallString<36> typeName; |
| 5567 | llvm::raw_svector_ostream(typeName) |
| 5568 | << "__block_literal_" << CGM.getUniqueBlockCount(); |
| 5569 | |
| 5570 | llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(Elements: fields); |
| 5571 | |
| 5572 | llvm::DIType *type = |
| 5573 | DBuilder.createStructType(Scope: tunit, Name: typeName.str(), File: tunit, LineNumber: line, |
| 5574 | SizeInBits: CGM.getContext().toBits(CharSize: block.BlockSize), AlignInBits: 0, |
| 5575 | Flags: llvm::DINode::FlagZero, DerivedFrom: nullptr, Elements: fieldsArray); |
| 5576 | type = DBuilder.createPointerType(PointeeTy: type, SizeInBits: CGM.PointerWidthInBits); |
| 5577 | |
| 5578 | // Get overall information about the block. |
| 5579 | llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial; |
| 5580 | auto *scope = cast<llvm::DILocalScope>(Val&: LexicalBlockStack.back()); |
| 5581 | |
| 5582 | // Create the descriptor for the parameter. |
| 5583 | auto *debugVar = DBuilder.createParameterVariable( |
| 5584 | Scope: scope, Name, ArgNo, File: tunit, LineNo: line, Ty: type, AlwaysPreserve: CGM.getLangOpts().Optimize, Flags: flags); |
| 5585 | |
| 5586 | // Insert an llvm.dbg.declare into the current block. |
| 5587 | DBuilder.insertDeclare(Storage: Alloca, VarInfo: debugVar, Expr: DBuilder.createExpression(), |
| 5588 | DL: llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line: line, |
| 5589 | Column: column, Scope: scope, InlinedAt: CurInlinedAt), |
| 5590 | InsertAtEnd: Builder.GetInsertBlock()); |
| 5591 | } |
| 5592 | |
| 5593 | llvm::DIDerivedType * |
| 5594 | CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) { |
| 5595 | if (!D || !D->isStaticDataMember()) |
| 5596 | return nullptr; |
| 5597 | |
| 5598 | auto MI = StaticDataMemberCache.find(Val: D->getCanonicalDecl()); |
| 5599 | if (MI != StaticDataMemberCache.end()) { |
| 5600 | assert(MI->second && "Static data member declaration should still exist" ); |
| 5601 | return MI->second; |
| 5602 | } |
| 5603 | |
| 5604 | // If the member wasn't found in the cache, lazily construct and add it to the |
| 5605 | // type (used when a limited form of the type is emitted). |
| 5606 | auto DC = D->getDeclContext(); |
| 5607 | auto *Ctxt = cast<llvm::DICompositeType>(Val: getDeclContextDescriptor(D)); |
| 5608 | return CreateRecordStaticField(Var: D, RecordTy: Ctxt, RD: cast<RecordDecl>(Val: DC)); |
| 5609 | } |
| 5610 | |
| 5611 | llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls( |
| 5612 | const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo, |
| 5613 | StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) { |
| 5614 | llvm::DIGlobalVariableExpression *GVE = nullptr; |
| 5615 | |
| 5616 | for (const auto *Field : RD->fields()) { |
| 5617 | llvm::DIType *FieldTy = getOrCreateType(Ty: Field->getType(), Unit); |
| 5618 | StringRef FieldName = Field->getName(); |
| 5619 | |
| 5620 | // Ignore unnamed fields, but recurse into anonymous records. |
| 5621 | if (FieldName.empty()) { |
| 5622 | if (const auto *RT = dyn_cast<RecordType>(Val: Field->getType())) |
| 5623 | GVE = CollectAnonRecordDecls(RD: RT->getDecl(), Unit, LineNo, LinkageName, |
| 5624 | Var, DContext); |
| 5625 | continue; |
| 5626 | } |
| 5627 | // Use VarDecl's Tag, Scope and Line number. |
| 5628 | GVE = DBuilder.createGlobalVariableExpression( |
| 5629 | Context: DContext, Name: FieldName, LinkageName, File: Unit, LineNo, Ty: FieldTy, |
| 5630 | IsLocalToUnit: Var->hasLocalLinkage()); |
| 5631 | Var->addDebugInfo(GV: GVE); |
| 5632 | } |
| 5633 | return GVE; |
| 5634 | } |
| 5635 | |
| 5636 | static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args); |
| 5637 | static bool ReferencesAnonymousEntity(RecordType *RT) { |
| 5638 | // Unnamed classes/lambdas can't be reconstituted due to a lack of column |
| 5639 | // info we produce in the DWARF, so we can't get Clang's full name back. |
| 5640 | // But so long as it's not one of those, it doesn't matter if some sub-type |
| 5641 | // of the record (a template parameter) can't be reconstituted - because the |
| 5642 | // un-reconstitutable type itself will carry its own name. |
| 5643 | const auto *RD = dyn_cast<CXXRecordDecl>(Val: RT->getDecl()); |
| 5644 | if (!RD) |
| 5645 | return false; |
| 5646 | if (!RD->getIdentifier()) |
| 5647 | return true; |
| 5648 | auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD); |
| 5649 | if (!TSpecial) |
| 5650 | return false; |
| 5651 | return ReferencesAnonymousEntity(Args: TSpecial->getTemplateArgs().asArray()); |
| 5652 | } |
| 5653 | static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args) { |
| 5654 | return llvm::any_of(Range&: Args, P: [&](const TemplateArgument &TA) { |
| 5655 | switch (TA.getKind()) { |
| 5656 | case TemplateArgument::Pack: |
| 5657 | return ReferencesAnonymousEntity(Args: TA.getPackAsArray()); |
| 5658 | case TemplateArgument::Type: { |
| 5659 | struct ReferencesAnonymous |
| 5660 | : public RecursiveASTVisitor<ReferencesAnonymous> { |
| 5661 | bool RefAnon = false; |
| 5662 | bool VisitRecordType(RecordType *RT) { |
| 5663 | if (ReferencesAnonymousEntity(RT)) { |
| 5664 | RefAnon = true; |
| 5665 | return false; |
| 5666 | } |
| 5667 | return true; |
| 5668 | } |
| 5669 | }; |
| 5670 | ReferencesAnonymous RT; |
| 5671 | RT.TraverseType(T: TA.getAsType()); |
| 5672 | if (RT.RefAnon) |
| 5673 | return true; |
| 5674 | break; |
| 5675 | } |
| 5676 | default: |
| 5677 | break; |
| 5678 | } |
| 5679 | return false; |
| 5680 | }); |
| 5681 | } |
| 5682 | namespace { |
| 5683 | struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> { |
| 5684 | bool Reconstitutable = true; |
| 5685 | bool VisitVectorType(VectorType *FT) { |
| 5686 | Reconstitutable = false; |
| 5687 | return false; |
| 5688 | } |
| 5689 | bool VisitAtomicType(AtomicType *FT) { |
| 5690 | Reconstitutable = false; |
| 5691 | return false; |
| 5692 | } |
| 5693 | bool VisitType(Type *T) { |
| 5694 | // _BitInt(N) isn't reconstitutable because the bit width isn't encoded in |
| 5695 | // the DWARF, only the byte width. |
| 5696 | if (T->isBitIntType()) { |
| 5697 | Reconstitutable = false; |
| 5698 | return false; |
| 5699 | } |
| 5700 | return true; |
| 5701 | } |
| 5702 | bool TraverseEnumType(EnumType *ET) { |
| 5703 | // Unnamed enums can't be reconstituted due to a lack of column info we |
| 5704 | // produce in the DWARF, so we can't get Clang's full name back. |
| 5705 | if (const auto *ED = dyn_cast<EnumDecl>(Val: ET->getDecl())) { |
| 5706 | if (!ED->getIdentifier()) { |
| 5707 | Reconstitutable = false; |
| 5708 | return false; |
| 5709 | } |
| 5710 | if (!ED->isExternallyVisible()) { |
| 5711 | Reconstitutable = false; |
| 5712 | return false; |
| 5713 | } |
| 5714 | } |
| 5715 | return true; |
| 5716 | } |
| 5717 | bool VisitFunctionProtoType(FunctionProtoType *FT) { |
| 5718 | // noexcept is not encoded in DWARF, so the reversi |
| 5719 | Reconstitutable &= !isNoexceptExceptionSpec(ESpecType: FT->getExceptionSpecType()); |
| 5720 | Reconstitutable &= !FT->getNoReturnAttr(); |
| 5721 | return Reconstitutable; |
| 5722 | } |
| 5723 | bool VisitRecordType(RecordType *RT) { |
| 5724 | if (ReferencesAnonymousEntity(RT)) { |
| 5725 | Reconstitutable = false; |
| 5726 | return false; |
| 5727 | } |
| 5728 | return true; |
| 5729 | } |
| 5730 | }; |
| 5731 | } // anonymous namespace |
| 5732 | |
| 5733 | // Test whether a type name could be rebuilt from emitted debug info. |
| 5734 | static bool IsReconstitutableType(QualType QT) { |
| 5735 | ReconstitutableType T; |
| 5736 | T.TraverseType(T: QT); |
| 5737 | return T.Reconstitutable; |
| 5738 | } |
| 5739 | |
| 5740 | bool CGDebugInfo::HasReconstitutableArgs( |
| 5741 | ArrayRef<TemplateArgument> Args) const { |
| 5742 | return llvm::all_of(Range&: Args, P: [&](const TemplateArgument &TA) { |
| 5743 | switch (TA.getKind()) { |
| 5744 | case TemplateArgument::Template: |
| 5745 | // Easy to reconstitute - the value of the parameter in the debug |
| 5746 | // info is the string name of the template. The template name |
| 5747 | // itself won't benefit from any name rebuilding, but that's a |
| 5748 | // representational limitation - maybe DWARF could be |
| 5749 | // changed/improved to use some more structural representation. |
| 5750 | return true; |
| 5751 | case TemplateArgument::Declaration: |
| 5752 | // Reference and pointer non-type template parameters point to |
| 5753 | // variables, functions, etc and their value is, at best (for |
| 5754 | // variables) represented as an address - not a reference to the |
| 5755 | // DWARF describing the variable/function/etc. This makes it hard, |
| 5756 | // possibly impossible to rebuild the original name - looking up |
| 5757 | // the address in the executable file's symbol table would be |
| 5758 | // needed. |
| 5759 | return false; |
| 5760 | case TemplateArgument::NullPtr: |
| 5761 | // These could be rebuilt, but figured they're close enough to the |
| 5762 | // declaration case, and not worth rebuilding. |
| 5763 | return false; |
| 5764 | case TemplateArgument::Pack: |
| 5765 | // A pack is invalid if any of the elements of the pack are |
| 5766 | // invalid. |
| 5767 | return HasReconstitutableArgs(Args: TA.getPackAsArray()); |
| 5768 | case TemplateArgument::Integral: |
| 5769 | // Larger integers get encoded as DWARF blocks which are a bit |
| 5770 | // harder to parse back into a large integer, etc - so punting on |
| 5771 | // this for now. Re-parsing the integers back into APInt is |
| 5772 | // probably feasible some day. |
| 5773 | return TA.getAsIntegral().getBitWidth() <= 64 && |
| 5774 | IsReconstitutableType(QT: TA.getIntegralType()); |
| 5775 | case TemplateArgument::StructuralValue: |
| 5776 | return false; |
| 5777 | case TemplateArgument::Type: |
| 5778 | return IsReconstitutableType(QT: TA.getAsType()); |
| 5779 | case TemplateArgument::Expression: |
| 5780 | return IsReconstitutableType(QT: TA.getAsExpr()->getType()); |
| 5781 | default: |
| 5782 | llvm_unreachable("Other, unresolved, template arguments should " |
| 5783 | "not be seen here" ); |
| 5784 | } |
| 5785 | }); |
| 5786 | } |
| 5787 | |
| 5788 | std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const { |
| 5789 | std::string Name; |
| 5790 | llvm::raw_string_ostream OS(Name); |
| 5791 | const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D); |
| 5792 | if (!ND) |
| 5793 | return Name; |
| 5794 | llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind = |
| 5795 | CGM.getCodeGenOpts().getDebugSimpleTemplateNames(); |
| 5796 | |
| 5797 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
| 5798 | TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full; |
| 5799 | |
| 5800 | std::optional<TemplateArgs> Args; |
| 5801 | |
| 5802 | bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND); |
| 5803 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND)) { |
| 5804 | Args = GetTemplateArgs(RD); |
| 5805 | } else if (auto *FD = dyn_cast<FunctionDecl>(Val: ND)) { |
| 5806 | Args = GetTemplateArgs(FD); |
| 5807 | auto NameKind = ND->getDeclName().getNameKind(); |
| 5808 | IsOperatorOverload |= |
| 5809 | NameKind == DeclarationName::CXXOperatorName || |
| 5810 | NameKind == DeclarationName::CXXConversionFunctionName; |
| 5811 | } else if (auto *VD = dyn_cast<VarDecl>(Val: ND)) { |
| 5812 | Args = GetTemplateArgs(VD); |
| 5813 | } |
| 5814 | |
| 5815 | // A conversion operator presents complications/ambiguity if there's a |
| 5816 | // conversion to class template that is itself a template, eg: |
| 5817 | // template<typename T> |
| 5818 | // operator ns::t1<T, int>(); |
| 5819 | // This should be named, eg: "operator ns::t1<float, int><float>" |
| 5820 | // (ignoring clang bug that means this is currently "operator t1<float>") |
| 5821 | // but if the arguments were stripped, the consumer couldn't differentiate |
| 5822 | // whether the template argument list for the conversion type was the |
| 5823 | // function's argument list (& no reconstitution was needed) or not. |
| 5824 | // This could be handled if reconstitutable names had a separate attribute |
| 5825 | // annotating them as such - this would remove the ambiguity. |
| 5826 | // |
| 5827 | // Alternatively the template argument list could be parsed enough to check |
| 5828 | // whether there's one list or two, then compare that with the DWARF |
| 5829 | // description of the return type and the template argument lists to determine |
| 5830 | // how many lists there should be and if one is missing it could be assumed(?) |
| 5831 | // to be the function's template argument list & then be rebuilt. |
| 5832 | // |
| 5833 | // Other operator overloads that aren't conversion operators could be |
| 5834 | // reconstituted but would require a bit more nuance about detecting the |
| 5835 | // difference between these different operators during that rebuilding. |
| 5836 | bool Reconstitutable = |
| 5837 | Args && HasReconstitutableArgs(Args: Args->Args) && !IsOperatorOverload; |
| 5838 | |
| 5839 | PrintingPolicy PP = getPrintingPolicy(); |
| 5840 | |
| 5841 | if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full || |
| 5842 | !Reconstitutable) { |
| 5843 | ND->getNameForDiagnostic(OS, Policy: PP, Qualified); |
| 5844 | } else { |
| 5845 | bool Mangled = TemplateNamesKind == |
| 5846 | llvm::codegenoptions::DebugTemplateNamesKind::Mangled; |
| 5847 | // check if it's a template |
| 5848 | if (Mangled) |
| 5849 | OS << "_STN|" ; |
| 5850 | |
| 5851 | OS << ND->getDeclName(); |
| 5852 | std::string EncodedOriginalName; |
| 5853 | llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName); |
| 5854 | EncodedOriginalNameOS << ND->getDeclName(); |
| 5855 | |
| 5856 | if (Mangled) { |
| 5857 | OS << "|" ; |
| 5858 | printTemplateArgumentList(OS, Args: Args->Args, Policy: PP); |
| 5859 | printTemplateArgumentList(OS&: EncodedOriginalNameOS, Args: Args->Args, Policy: PP); |
| 5860 | #ifndef NDEBUG |
| 5861 | std::string CanonicalOriginalName; |
| 5862 | llvm::raw_string_ostream OriginalOS(CanonicalOriginalName); |
| 5863 | ND->getNameForDiagnostic(OriginalOS, PP, Qualified); |
| 5864 | assert(EncodedOriginalName == CanonicalOriginalName); |
| 5865 | #endif |
| 5866 | } |
| 5867 | } |
| 5868 | return Name; |
| 5869 | } |
| 5870 | |
| 5871 | void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, |
| 5872 | const VarDecl *D) { |
| 5873 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 5874 | if (D->hasAttr<NoDebugAttr>()) |
| 5875 | return; |
| 5876 | |
| 5877 | llvm::TimeTraceScope TimeScope("DebugGlobalVariable" , [&]() { |
| 5878 | return GetName(D, Qualified: true); |
| 5879 | }); |
| 5880 | |
| 5881 | // If we already created a DIGlobalVariable for this declaration, just attach |
| 5882 | // it to the llvm::GlobalVariable. |
| 5883 | auto Cached = DeclCache.find(Val: D->getCanonicalDecl()); |
| 5884 | if (Cached != DeclCache.end()) |
| 5885 | return Var->addDebugInfo( |
| 5886 | GV: cast<llvm::DIGlobalVariableExpression>(Val&: Cached->second)); |
| 5887 | |
| 5888 | // Create global variable debug descriptor. |
| 5889 | llvm::DIFile *Unit = nullptr; |
| 5890 | llvm::DIScope *DContext = nullptr; |
| 5891 | unsigned LineNo; |
| 5892 | StringRef DeclName, LinkageName; |
| 5893 | QualType T; |
| 5894 | llvm::MDTuple *TemplateParameters = nullptr; |
| 5895 | collectVarDeclProps(VD: D, Unit, LineNo, T, Name&: DeclName, LinkageName, |
| 5896 | TemplateParameters, VDContext&: DContext); |
| 5897 | |
| 5898 | // Attempt to store one global variable for the declaration - even if we |
| 5899 | // emit a lot of fields. |
| 5900 | llvm::DIGlobalVariableExpression *GVE = nullptr; |
| 5901 | |
| 5902 | // If this is an anonymous union then we'll want to emit a global |
| 5903 | // variable for each member of the anonymous union so that it's possible |
| 5904 | // to find the name of any field in the union. |
| 5905 | if (T->isUnionType() && DeclName.empty()) { |
| 5906 | const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); |
| 5907 | assert(RD->isAnonymousStructOrUnion() && |
| 5908 | "unnamed non-anonymous struct or union?" ); |
| 5909 | GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext); |
| 5910 | } else { |
| 5911 | auto Align = getDeclAlignIfRequired(D, Ctx: CGM.getContext()); |
| 5912 | |
| 5913 | SmallVector<uint64_t, 4> Expr; |
| 5914 | unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(T: D->getType()); |
| 5915 | if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) { |
| 5916 | if (D->hasAttr<CUDASharedAttr>()) |
| 5917 | AddressSpace = |
| 5918 | CGM.getContext().getTargetAddressSpace(AS: LangAS::cuda_shared); |
| 5919 | else if (D->hasAttr<CUDAConstantAttr>()) |
| 5920 | AddressSpace = |
| 5921 | CGM.getContext().getTargetAddressSpace(AS: LangAS::cuda_constant); |
| 5922 | } |
| 5923 | AppendAddressSpaceXDeref(AddressSpace, Expr); |
| 5924 | |
| 5925 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D); |
| 5926 | GVE = DBuilder.createGlobalVariableExpression( |
| 5927 | Context: DContext, Name: DeclName, LinkageName, File: Unit, LineNo, Ty: getOrCreateType(Ty: T, Unit), |
| 5928 | IsLocalToUnit: Var->hasLocalLinkage(), isDefined: true, |
| 5929 | Expr: Expr.empty() ? nullptr : DBuilder.createExpression(Addr: Expr), |
| 5930 | Decl: getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParams: TemplateParameters, |
| 5931 | AlignInBits: Align, Annotations); |
| 5932 | Var->addDebugInfo(GV: GVE); |
| 5933 | } |
| 5934 | DeclCache[D->getCanonicalDecl()].reset(MD: GVE); |
| 5935 | } |
| 5936 | |
| 5937 | void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) { |
| 5938 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 5939 | if (VD->hasAttr<NoDebugAttr>()) |
| 5940 | return; |
| 5941 | llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable" , [&]() { |
| 5942 | return GetName(D: VD, Qualified: true); |
| 5943 | }); |
| 5944 | |
| 5945 | auto Align = getDeclAlignIfRequired(D: VD, Ctx: CGM.getContext()); |
| 5946 | // Create the descriptor for the variable. |
| 5947 | llvm::DIFile *Unit = getOrCreateFile(Loc: VD->getLocation()); |
| 5948 | StringRef Name = VD->getName(); |
| 5949 | llvm::DIType *Ty = getOrCreateType(Ty: VD->getType(), Unit); |
| 5950 | |
| 5951 | if (const auto *ECD = dyn_cast<EnumConstantDecl>(Val: VD)) { |
| 5952 | const auto *ED = cast<EnumDecl>(Val: ECD->getDeclContext()); |
| 5953 | assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?" ); |
| 5954 | |
| 5955 | if (CGM.getCodeGenOpts().EmitCodeView) { |
| 5956 | // If CodeView, emit enums as global variables, unless they are defined |
| 5957 | // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for |
| 5958 | // enums in classes, and because it is difficult to attach this scope |
| 5959 | // information to the global variable. |
| 5960 | if (isa<RecordDecl>(Val: ED->getDeclContext())) |
| 5961 | return; |
| 5962 | } else { |
| 5963 | // If not CodeView, emit DW_TAG_enumeration_type if necessary. For |
| 5964 | // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the |
| 5965 | // first time `ZERO` is referenced in a function. |
| 5966 | llvm::DIType *EDTy = |
| 5967 | getOrCreateType(Ty: QualType(ED->getTypeForDecl(), 0), Unit); |
| 5968 | assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type); |
| 5969 | (void)EDTy; |
| 5970 | return; |
| 5971 | } |
| 5972 | } |
| 5973 | |
| 5974 | // Do not emit separate definitions for function local consts. |
| 5975 | if (isa<FunctionDecl>(Val: VD->getDeclContext())) |
| 5976 | return; |
| 5977 | |
| 5978 | VD = cast<ValueDecl>(Val: VD->getCanonicalDecl()); |
| 5979 | auto *VarD = dyn_cast<VarDecl>(Val: VD); |
| 5980 | if (VarD && VarD->isStaticDataMember()) { |
| 5981 | auto *RD = cast<RecordDecl>(Val: VarD->getDeclContext()); |
| 5982 | getDeclContextDescriptor(D: VarD); |
| 5983 | // Ensure that the type is retained even though it's otherwise unreferenced. |
| 5984 | // |
| 5985 | // FIXME: This is probably unnecessary, since Ty should reference RD |
| 5986 | // through its scope. |
| 5987 | RetainedTypes.push_back( |
| 5988 | x: CGM.getContext().getRecordType(Decl: RD).getAsOpaquePtr()); |
| 5989 | |
| 5990 | return; |
| 5991 | } |
| 5992 | llvm::DIScope *DContext = getDeclContextDescriptor(D: VD); |
| 5993 | |
| 5994 | auto &GV = DeclCache[VD]; |
| 5995 | if (GV) |
| 5996 | return; |
| 5997 | |
| 5998 | llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Val: Init); |
| 5999 | llvm::MDTuple *TemplateParameters = nullptr; |
| 6000 | |
| 6001 | if (isa<VarTemplateSpecializationDecl>(Val: VD)) |
| 6002 | if (VarD) { |
| 6003 | llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VL: VarD, Unit: &*Unit); |
| 6004 | TemplateParameters = parameterNodes.get(); |
| 6005 | } |
| 6006 | |
| 6007 | GV.reset(MD: DBuilder.createGlobalVariableExpression( |
| 6008 | Context: DContext, Name, LinkageName: StringRef(), File: Unit, LineNo: getLineNumber(Loc: VD->getLocation()), Ty, |
| 6009 | IsLocalToUnit: true, isDefined: true, Expr: InitExpr, Decl: getOrCreateStaticDataMemberDeclarationOrNull(D: VarD), |
| 6010 | TemplateParams: TemplateParameters, AlignInBits: Align)); |
| 6011 | } |
| 6012 | |
| 6013 | void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var, |
| 6014 | const VarDecl *D) { |
| 6015 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
| 6016 | if (D->hasAttr<NoDebugAttr>()) |
| 6017 | return; |
| 6018 | |
| 6019 | auto Align = getDeclAlignIfRequired(D, Ctx: CGM.getContext()); |
| 6020 | llvm::DIFile *Unit = getOrCreateFile(Loc: D->getLocation()); |
| 6021 | StringRef Name = D->getName(); |
| 6022 | llvm::DIType *Ty = getOrCreateType(Ty: D->getType(), Unit); |
| 6023 | |
| 6024 | llvm::DIScope *DContext = getDeclContextDescriptor(D); |
| 6025 | llvm::DIGlobalVariableExpression *GVE = |
| 6026 | DBuilder.createGlobalVariableExpression( |
| 6027 | Context: DContext, Name, LinkageName: StringRef(), File: Unit, LineNo: getLineNumber(Loc: D->getLocation()), |
| 6028 | Ty, IsLocalToUnit: false, isDefined: false, Expr: nullptr, Decl: nullptr, TemplateParams: nullptr, AlignInBits: Align); |
| 6029 | Var->addDebugInfo(GV: GVE); |
| 6030 | } |
| 6031 | |
| 6032 | void CGDebugInfo::EmitPseudoVariable(CGBuilderTy &Builder, |
| 6033 | llvm::Instruction *Value, QualType Ty) { |
| 6034 | // Only when -g2 or above is specified, debug info for variables will be |
| 6035 | // generated. |
| 6036 | if (CGM.getCodeGenOpts().getDebugInfo() <= |
| 6037 | llvm::codegenoptions::DebugLineTablesOnly) |
| 6038 | return; |
| 6039 | |
| 6040 | llvm::DILocation *DIL = Value->getDebugLoc().get(); |
| 6041 | if (!DIL) |
| 6042 | return; |
| 6043 | |
| 6044 | llvm::DIFile *Unit = DIL->getFile(); |
| 6045 | llvm::DIType *Type = getOrCreateType(Ty, Unit); |
| 6046 | |
| 6047 | // Check if Value is already a declared variable and has debug info, in this |
| 6048 | // case we have nothing to do. Clang emits a declared variable as alloca, and |
| 6049 | // it is loaded upon use, so we identify such pattern here. |
| 6050 | if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Val: Value)) { |
| 6051 | llvm::Value *Var = Load->getPointerOperand(); |
| 6052 | // There can be implicit type cast applied on a variable if it is an opaque |
| 6053 | // ptr, in this case its debug info may not match the actual type of object |
| 6054 | // being used as in the next instruction, so we will need to emit a pseudo |
| 6055 | // variable for type-casted value. |
| 6056 | auto DeclareTypeMatches = [&](auto *DbgDeclare) { |
| 6057 | return DbgDeclare->getVariable()->getType() == Type; |
| 6058 | }; |
| 6059 | if (any_of(Range: llvm::findDbgDeclares(V: Var), P: DeclareTypeMatches) || |
| 6060 | any_of(Range: llvm::findDVRDeclares(V: Var), P: DeclareTypeMatches)) |
| 6061 | return; |
| 6062 | } |
| 6063 | |
| 6064 | llvm::DILocalVariable *D = |
| 6065 | DBuilder.createAutoVariable(Scope: LexicalBlockStack.back(), Name: "" , File: nullptr, LineNo: 0, |
| 6066 | Ty: Type, AlwaysPreserve: false, Flags: llvm::DINode::FlagArtificial); |
| 6067 | |
| 6068 | if (auto InsertPoint = Value->getInsertionPointAfterDef()) { |
| 6069 | DBuilder.insertDbgValueIntrinsic(Val: Value, VarInfo: D, Expr: DBuilder.createExpression(), DL: DIL, |
| 6070 | InsertPt: *InsertPoint); |
| 6071 | } |
| 6072 | } |
| 6073 | |
| 6074 | void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV, |
| 6075 | const GlobalDecl GD) { |
| 6076 | |
| 6077 | assert(GV); |
| 6078 | |
| 6079 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
| 6080 | return; |
| 6081 | |
| 6082 | const auto *D = cast<ValueDecl>(Val: GD.getDecl()); |
| 6083 | if (D->hasAttr<NoDebugAttr>()) |
| 6084 | return; |
| 6085 | |
| 6086 | auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName()); |
| 6087 | llvm::DINode *DI; |
| 6088 | |
| 6089 | if (!AliaseeDecl) |
| 6090 | // FIXME: Aliasee not declared yet - possibly declared later |
| 6091 | // For example, |
| 6092 | // |
| 6093 | // 1 extern int newname __attribute__((alias("oldname"))); |
| 6094 | // 2 int oldname = 1; |
| 6095 | // |
| 6096 | // No debug info would be generated for 'newname' in this case. |
| 6097 | // |
| 6098 | // Fix compiler to generate "newname" as imported_declaration |
| 6099 | // pointing to the DIE of "oldname". |
| 6100 | return; |
| 6101 | if (!(DI = getDeclarationOrDefinition( |
| 6102 | D: AliaseeDecl.getCanonicalDecl().getDecl()))) |
| 6103 | return; |
| 6104 | |
| 6105 | llvm::DIScope *DContext = getDeclContextDescriptor(D); |
| 6106 | auto Loc = D->getLocation(); |
| 6107 | |
| 6108 | llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration( |
| 6109 | Context: DContext, Decl: DI, File: getOrCreateFile(Loc), Line: getLineNumber(Loc), Name: D->getName()); |
| 6110 | |
| 6111 | // Record this DIE in the cache for nested declaration reference. |
| 6112 | ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(MD: ImportDI); |
| 6113 | } |
| 6114 | |
| 6115 | void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV, |
| 6116 | const StringLiteral *S) { |
| 6117 | SourceLocation Loc = S->getStrTokenLoc(TokNum: 0); |
| 6118 | PresumedLoc PLoc = CGM.getContext().getSourceManager().getPresumedLoc(Loc); |
| 6119 | if (!PLoc.isValid()) |
| 6120 | return; |
| 6121 | |
| 6122 | llvm::DIFile *File = getOrCreateFile(Loc); |
| 6123 | llvm::DIGlobalVariableExpression *Debug = |
| 6124 | DBuilder.createGlobalVariableExpression( |
| 6125 | Context: nullptr, Name: StringRef(), LinkageName: StringRef(), File: getOrCreateFile(Loc), |
| 6126 | LineNo: getLineNumber(Loc), Ty: getOrCreateType(Ty: S->getType(), Unit: File), IsLocalToUnit: true); |
| 6127 | GV->addDebugInfo(GV: Debug); |
| 6128 | } |
| 6129 | |
| 6130 | llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { |
| 6131 | if (!LexicalBlockStack.empty()) |
| 6132 | return LexicalBlockStack.back(); |
| 6133 | llvm::DIScope *Mod = getParentModuleOrNull(D); |
| 6134 | return getContextDescriptor(Context: D, Default: Mod ? Mod : TheCU); |
| 6135 | } |
| 6136 | |
| 6137 | void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { |
| 6138 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
| 6139 | return; |
| 6140 | const NamespaceDecl *NSDecl = UD.getNominatedNamespace(); |
| 6141 | if (!NSDecl->isAnonymousNamespace() || |
| 6142 | CGM.getCodeGenOpts().DebugExplicitImport) { |
| 6143 | auto Loc = UD.getLocation(); |
| 6144 | if (!Loc.isValid()) |
| 6145 | Loc = CurLoc; |
| 6146 | DBuilder.createImportedModule( |
| 6147 | Context: getCurrentContextDescriptor(D: cast<Decl>(Val: UD.getDeclContext())), |
| 6148 | NS: getOrCreateNamespace(N: NSDecl), File: getOrCreateFile(Loc), Line: getLineNumber(Loc)); |
| 6149 | } |
| 6150 | } |
| 6151 | |
| 6152 | void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl &USD) { |
| 6153 | if (llvm::DINode *Target = |
| 6154 | getDeclarationOrDefinition(D: USD.getUnderlyingDecl())) { |
| 6155 | auto Loc = USD.getLocation(); |
| 6156 | DBuilder.createImportedDeclaration( |
| 6157 | Context: getCurrentContextDescriptor(D: cast<Decl>(Val: USD.getDeclContext())), Decl: Target, |
| 6158 | File: getOrCreateFile(Loc), Line: getLineNumber(Loc)); |
| 6159 | } |
| 6160 | } |
| 6161 | |
| 6162 | void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { |
| 6163 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
| 6164 | return; |
| 6165 | assert(UD.shadow_size() && |
| 6166 | "We shouldn't be codegening an invalid UsingDecl containing no decls" ); |
| 6167 | |
| 6168 | for (const auto *USD : UD.shadows()) { |
| 6169 | // FIXME: Skip functions with undeduced auto return type for now since we |
| 6170 | // don't currently have the plumbing for separate declarations & definitions |
| 6171 | // of free functions and mismatched types (auto in the declaration, concrete |
| 6172 | // return type in the definition) |
| 6173 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: USD->getUnderlyingDecl())) |
| 6174 | if (const auto *AT = FD->getType() |
| 6175 | ->castAs<FunctionProtoType>() |
| 6176 | ->getContainedAutoType()) |
| 6177 | if (AT->getDeducedType().isNull()) |
| 6178 | continue; |
| 6179 | |
| 6180 | EmitUsingShadowDecl(USD: *USD); |
| 6181 | // Emitting one decl is sufficient - debuggers can detect that this is an |
| 6182 | // overloaded name & provide lookup for all the overloads. |
| 6183 | break; |
| 6184 | } |
| 6185 | } |
| 6186 | |
| 6187 | void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) { |
| 6188 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
| 6189 | return; |
| 6190 | assert(UD.shadow_size() && |
| 6191 | "We shouldn't be codegening an invalid UsingEnumDecl" |
| 6192 | " containing no decls" ); |
| 6193 | |
| 6194 | for (const auto *USD : UD.shadows()) |
| 6195 | EmitUsingShadowDecl(USD: *USD); |
| 6196 | } |
| 6197 | |
| 6198 | void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) { |
| 6199 | if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB) |
| 6200 | return; |
| 6201 | if (Module *M = ID.getImportedModule()) { |
| 6202 | auto Info = ASTSourceDescriptor(*M); |
| 6203 | auto Loc = ID.getLocation(); |
| 6204 | DBuilder.createImportedDeclaration( |
| 6205 | Context: getCurrentContextDescriptor(D: cast<Decl>(Val: ID.getDeclContext())), |
| 6206 | Decl: getOrCreateModuleRef(Mod: Info, CreateSkeletonCU: DebugTypeExtRefs), File: getOrCreateFile(Loc), |
| 6207 | Line: getLineNumber(Loc)); |
| 6208 | } |
| 6209 | } |
| 6210 | |
| 6211 | llvm::DIImportedEntity * |
| 6212 | CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { |
| 6213 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
| 6214 | return nullptr; |
| 6215 | auto &VH = NamespaceAliasCache[&NA]; |
| 6216 | if (VH) |
| 6217 | return cast<llvm::DIImportedEntity>(Val&: VH); |
| 6218 | llvm::DIImportedEntity *R; |
| 6219 | auto Loc = NA.getLocation(); |
| 6220 | if (const auto *Underlying = |
| 6221 | dyn_cast<NamespaceAliasDecl>(Val: NA.getAliasedNamespace())) |
| 6222 | // This could cache & dedup here rather than relying on metadata deduping. |
| 6223 | R = DBuilder.createImportedDeclaration( |
| 6224 | Context: getCurrentContextDescriptor(D: cast<Decl>(Val: NA.getDeclContext())), |
| 6225 | Decl: EmitNamespaceAlias(NA: *Underlying), File: getOrCreateFile(Loc), |
| 6226 | Line: getLineNumber(Loc), Name: NA.getName()); |
| 6227 | else |
| 6228 | R = DBuilder.createImportedDeclaration( |
| 6229 | Context: getCurrentContextDescriptor(D: cast<Decl>(Val: NA.getDeclContext())), |
| 6230 | Decl: getOrCreateNamespace(N: cast<NamespaceDecl>(Val: NA.getAliasedNamespace())), |
| 6231 | File: getOrCreateFile(Loc), Line: getLineNumber(Loc), Name: NA.getName()); |
| 6232 | VH.reset(MD: R); |
| 6233 | return R; |
| 6234 | } |
| 6235 | |
| 6236 | llvm::DINamespace * |
| 6237 | CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) { |
| 6238 | // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued |
| 6239 | // if necessary, and this way multiple declarations of the same namespace in |
| 6240 | // different parent modules stay distinct. |
| 6241 | auto I = NamespaceCache.find(Val: NSDecl); |
| 6242 | if (I != NamespaceCache.end()) |
| 6243 | return cast<llvm::DINamespace>(Val&: I->second); |
| 6244 | |
| 6245 | llvm::DIScope *Context = getDeclContextDescriptor(D: NSDecl); |
| 6246 | // Don't trust the context if it is a DIModule (see comment above). |
| 6247 | llvm::DINamespace *NS = |
| 6248 | DBuilder.createNameSpace(Scope: Context, Name: NSDecl->getName(), ExportSymbols: NSDecl->isInline()); |
| 6249 | NamespaceCache[NSDecl].reset(MD: NS); |
| 6250 | return NS; |
| 6251 | } |
| 6252 | |
| 6253 | void CGDebugInfo::setDwoId(uint64_t Signature) { |
| 6254 | assert(TheCU && "no main compile unit" ); |
| 6255 | TheCU->setDWOId(Signature); |
| 6256 | } |
| 6257 | |
| 6258 | void CGDebugInfo::finalize() { |
| 6259 | // Creating types might create further types - invalidating the current |
| 6260 | // element and the size(), so don't cache/reference them. |
| 6261 | for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) { |
| 6262 | ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i]; |
| 6263 | llvm::DIType *Ty = E.Type->getDecl()->getDefinition() |
| 6264 | ? CreateTypeDefinition(Ty: E.Type, Unit: E.Unit) |
| 6265 | : E.Decl; |
| 6266 | DBuilder.replaceTemporary(N: llvm::TempDIType(E.Decl), Replacement: Ty); |
| 6267 | } |
| 6268 | |
| 6269 | // Add methods to interface. |
| 6270 | for (const auto &P : ObjCMethodCache) { |
| 6271 | if (P.second.empty()) |
| 6272 | continue; |
| 6273 | |
| 6274 | QualType QTy(P.first->getTypeForDecl(), 0); |
| 6275 | auto It = TypeCache.find(Val: QTy.getAsOpaquePtr()); |
| 6276 | assert(It != TypeCache.end()); |
| 6277 | |
| 6278 | llvm::DICompositeType *InterfaceDecl = |
| 6279 | cast<llvm::DICompositeType>(Val&: It->second); |
| 6280 | |
| 6281 | auto CurElts = InterfaceDecl->getElements(); |
| 6282 | SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end()); |
| 6283 | |
| 6284 | // For DWARF v4 or earlier, only add objc_direct methods. |
| 6285 | for (auto &SubprogramDirect : P.second) |
| 6286 | if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt()) |
| 6287 | EltTys.push_back(Elt: SubprogramDirect.getPointer()); |
| 6288 | |
| 6289 | llvm::DINodeArray Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
| 6290 | DBuilder.replaceArrays(T&: InterfaceDecl, Elements); |
| 6291 | } |
| 6292 | |
| 6293 | for (const auto &P : ReplaceMap) { |
| 6294 | assert(P.second); |
| 6295 | auto *Ty = cast<llvm::DIType>(Val: P.second); |
| 6296 | assert(Ty->isForwardDecl()); |
| 6297 | |
| 6298 | auto It = TypeCache.find(Val: P.first); |
| 6299 | assert(It != TypeCache.end()); |
| 6300 | assert(It->second); |
| 6301 | |
| 6302 | DBuilder.replaceTemporary(N: llvm::TempDIType(Ty), |
| 6303 | Replacement: cast<llvm::DIType>(Val&: It->second)); |
| 6304 | } |
| 6305 | |
| 6306 | for (const auto &P : FwdDeclReplaceMap) { |
| 6307 | assert(P.second); |
| 6308 | llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(Val: P.second)); |
| 6309 | llvm::Metadata *Repl; |
| 6310 | |
| 6311 | auto It = DeclCache.find(Val: P.first); |
| 6312 | // If there has been no definition for the declaration, call RAUW |
| 6313 | // with ourselves, that will destroy the temporary MDNode and |
| 6314 | // replace it with a standard one, avoiding leaking memory. |
| 6315 | if (It == DeclCache.end()) |
| 6316 | Repl = P.second; |
| 6317 | else |
| 6318 | Repl = It->second; |
| 6319 | |
| 6320 | if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Val: Repl)) |
| 6321 | Repl = GVE->getVariable(); |
| 6322 | DBuilder.replaceTemporary(N: std::move(FwdDecl), Replacement: cast<llvm::MDNode>(Val: Repl)); |
| 6323 | } |
| 6324 | |
| 6325 | // We keep our own list of retained types, because we need to look |
| 6326 | // up the final type in the type cache. |
| 6327 | for (auto &RT : RetainedTypes) |
| 6328 | if (auto MD = TypeCache[RT]) |
| 6329 | DBuilder.retainType(T: cast<llvm::DIType>(Val&: MD)); |
| 6330 | |
| 6331 | DBuilder.finalize(); |
| 6332 | } |
| 6333 | |
| 6334 | // Don't ignore in case of explicit cast where it is referenced indirectly. |
| 6335 | void CGDebugInfo::EmitExplicitCastType(QualType Ty) { |
| 6336 | if (CGM.getCodeGenOpts().hasReducedDebugInfo()) |
| 6337 | if (auto *DieTy = getOrCreateType(Ty, Unit: TheCU->getFile())) |
| 6338 | DBuilder.retainType(T: DieTy); |
| 6339 | } |
| 6340 | |
| 6341 | void CGDebugInfo::EmitAndRetainType(QualType Ty) { |
| 6342 | if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo()) |
| 6343 | if (auto *DieTy = getOrCreateType(Ty, Unit: TheCU->getFile())) |
| 6344 | DBuilder.retainType(T: DieTy); |
| 6345 | } |
| 6346 | |
| 6347 | llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) { |
| 6348 | if (LexicalBlockStack.empty()) |
| 6349 | return llvm::DebugLoc(); |
| 6350 | |
| 6351 | llvm::MDNode *Scope = LexicalBlockStack.back(); |
| 6352 | return llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line: getLineNumber(Loc), |
| 6353 | Column: getColumnNumber(Loc), Scope); |
| 6354 | } |
| 6355 | |
| 6356 | llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const { |
| 6357 | // Call site-related attributes are only useful in optimized programs, and |
| 6358 | // when there's a possibility of debugging backtraces. |
| 6359 | if (!CGM.getLangOpts().Optimize || |
| 6360 | DebugKind == llvm::codegenoptions::NoDebugInfo || |
| 6361 | DebugKind == llvm::codegenoptions::LocTrackingOnly) |
| 6362 | return llvm::DINode::FlagZero; |
| 6363 | |
| 6364 | // Call site-related attributes are available in DWARF v5. Some debuggers, |
| 6365 | // while not fully DWARF v5-compliant, may accept these attributes as if they |
| 6366 | // were part of DWARF v4. |
| 6367 | bool SupportsDWARFv4Ext = |
| 6368 | CGM.getCodeGenOpts().DwarfVersion == 4 && |
| 6369 | (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB || |
| 6370 | CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB); |
| 6371 | |
| 6372 | if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5) |
| 6373 | return llvm::DINode::FlagZero; |
| 6374 | |
| 6375 | return llvm::DINode::FlagAllCallsDescribed; |
| 6376 | } |
| 6377 | |
| 6378 | llvm::DIExpression * |
| 6379 | CGDebugInfo::createConstantValueExpression(const clang::ValueDecl *VD, |
| 6380 | const APValue &Val) { |
| 6381 | // FIXME: Add a representation for integer constants wider than 64 bits. |
| 6382 | if (CGM.getContext().getTypeSize(T: VD->getType()) > 64) |
| 6383 | return nullptr; |
| 6384 | |
| 6385 | if (Val.isFloat()) |
| 6386 | return DBuilder.createConstantValueExpression( |
| 6387 | Val: Val.getFloat().bitcastToAPInt().getZExtValue()); |
| 6388 | |
| 6389 | if (!Val.isInt()) |
| 6390 | return nullptr; |
| 6391 | |
| 6392 | llvm::APSInt const &ValInt = Val.getInt(); |
| 6393 | std::optional<uint64_t> ValIntOpt; |
| 6394 | if (ValInt.isUnsigned()) |
| 6395 | ValIntOpt = ValInt.tryZExtValue(); |
| 6396 | else if (auto tmp = ValInt.trySExtValue()) |
| 6397 | // Transform a signed optional to unsigned optional. When cpp 23 comes, |
| 6398 | // use std::optional::transform |
| 6399 | ValIntOpt = static_cast<uint64_t>(*tmp); |
| 6400 | |
| 6401 | if (ValIntOpt) |
| 6402 | return DBuilder.createConstantValueExpression(Val: ValIntOpt.value()); |
| 6403 | |
| 6404 | return nullptr; |
| 6405 | } |
| 6406 | |
| 6407 | CodeGenFunction::LexicalScope::LexicalScope(CodeGenFunction &CGF, |
| 6408 | SourceRange Range) |
| 6409 | : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) { |
| 6410 | CGF.CurLexicalScope = this; |
| 6411 | if (CGDebugInfo *DI = CGF.getDebugInfo()) |
| 6412 | DI->EmitLexicalBlockStart(Builder&: CGF.Builder, Loc: Range.getBegin()); |
| 6413 | } |
| 6414 | |
| 6415 | CodeGenFunction::LexicalScope::~LexicalScope() { |
| 6416 | if (CGDebugInfo *DI = CGF.getDebugInfo()) |
| 6417 | DI->EmitLexicalBlockEnd(Builder&: CGF.Builder, Loc: Range.getEnd()); |
| 6418 | |
| 6419 | // If we should perform a cleanup, force them now. Note that |
| 6420 | // this ends the cleanup scope before rescoping any labels. |
| 6421 | if (PerformCleanup) { |
| 6422 | ApplyDebugLocation DL(CGF, Range.getEnd()); |
| 6423 | ForceCleanup(); |
| 6424 | } |
| 6425 | } |
| 6426 | |
| 6427 | static std::string SanitizerHandlerToCheckLabel(SanitizerHandler Handler) { |
| 6428 | std::string Label; |
| 6429 | switch (Handler) { |
| 6430 | #define SANITIZER_CHECK(Enum, Name, Version) \ |
| 6431 | case Enum: \ |
| 6432 | Label = "__ubsan_check_" #Name; \ |
| 6433 | break; |
| 6434 | |
| 6435 | LIST_SANITIZER_CHECKS |
| 6436 | #undef SANITIZER_CHECK |
| 6437 | }; |
| 6438 | |
| 6439 | // Label doesn't require sanitization |
| 6440 | return Label; |
| 6441 | } |
| 6442 | |
| 6443 | static std::string |
| 6444 | SanitizerOrdinalToCheckLabel(SanitizerKind::SanitizerOrdinal Ordinal) { |
| 6445 | std::string Label; |
| 6446 | switch (Ordinal) { |
| 6447 | #define SANITIZER(NAME, ID) \ |
| 6448 | case SanitizerKind::SO_##ID: \ |
| 6449 | Label = "__ubsan_check_" NAME; \ |
| 6450 | break; |
| 6451 | #include "clang/Basic/Sanitizers.def" |
| 6452 | default: |
| 6453 | llvm_unreachable("unexpected sanitizer kind" ); |
| 6454 | } |
| 6455 | |
| 6456 | // Sanitize label (convert hyphens to underscores; also futureproof against |
| 6457 | // non-alpha) |
| 6458 | for (unsigned int i = 0; i < Label.length(); i++) |
| 6459 | if (!std::isalpha(Label[i])) |
| 6460 | Label[i] = '_'; |
| 6461 | |
| 6462 | return Label; |
| 6463 | } |
| 6464 | |
| 6465 | llvm::DILocation *CodeGenFunction::SanitizerAnnotateDebugInfo( |
| 6466 | ArrayRef<SanitizerKind::SanitizerOrdinal> Ordinals, |
| 6467 | SanitizerHandler Handler) { |
| 6468 | std::string Label; |
| 6469 | if (Ordinals.size() == 1) |
| 6470 | Label = SanitizerOrdinalToCheckLabel(Ordinal: Ordinals[0]); |
| 6471 | else |
| 6472 | Label = SanitizerHandlerToCheckLabel(Handler); |
| 6473 | |
| 6474 | llvm::DILocation *CheckDI = Builder.getCurrentDebugLocation(); |
| 6475 | |
| 6476 | for (auto Ord : Ordinals) { |
| 6477 | // TODO: deprecate ClArrayBoundsPseudoFn |
| 6478 | if (((ClArrayBoundsPseudoFn && Ord == SanitizerKind::SO_ArrayBounds) || |
| 6479 | CGM.getCodeGenOpts().SanitizeAnnotateDebugInfo.has(O: Ord)) && |
| 6480 | CheckDI) { |
| 6481 | return getDebugInfo()->CreateSyntheticInlineAt(Location: CheckDI, FuncName: Label); |
| 6482 | } |
| 6483 | } |
| 6484 | |
| 6485 | return CheckDI; |
| 6486 | } |
| 6487 | |
| 6488 | SanitizerDebugLocation::SanitizerDebugLocation( |
| 6489 | CodeGenFunction *CGF, ArrayRef<SanitizerKind::SanitizerOrdinal> Ordinals, |
| 6490 | SanitizerHandler Handler) |
| 6491 | : CGF(CGF), |
| 6492 | Apply(*CGF, CGF->SanitizerAnnotateDebugInfo(Ordinals, Handler)) { |
| 6493 | assert(!CGF->IsSanitizerScope); |
| 6494 | CGF->IsSanitizerScope = true; |
| 6495 | } |
| 6496 | |
| 6497 | SanitizerDebugLocation::~SanitizerDebugLocation() { |
| 6498 | assert(CGF->IsSanitizerScope); |
| 6499 | CGF->IsSanitizerScope = false; |
| 6500 | } |
| 6501 | |