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