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