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.UseIntegerTypeSuffixesAlways = 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 int Idx = 0; 1445 for (const QualType &ParamType : FPT->param_types()) { 1446 TypeLoc ParamTL; 1447 if (ParmVarDecl *Param = FTL.getParam(Idx)) { 1448 if (const TypeSourceInfo *TSI = Param->getTypeSourceInfo()) 1449 ParamTL = TSI->getTypeLoc(); 1450 } 1451 EltTys.push_back(getOrCreateType(ParamType, Unit, ParamTL)); 1452 Idx++; 1453 } 1454 } 1455 } 1456 1457 if (!DoneWithTL) { 1458 for (const QualType &ParamType : FPT->param_types()) 1459 EltTys.push_back(getOrCreateType(ParamType, Unit)); 1460 } 1461 if (FPT->isVariadic()) 1462 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 1463 } 1464 1465 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 1466 llvm::DIType *F = DBuilder.createSubroutineType( 1467 EltTypeArray, Flags, getDwarfCC(Ty->getCallConv())); 1468 return F; 1469 } 1470 1471 /// Convert an AccessSpecifier into the corresponding DINode flag. 1472 /// As an optimization, return 0 if the access specifier equals the 1473 /// default for the containing type. 1474 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access, 1475 const RecordDecl *RD) { 1476 AccessSpecifier Default = clang::AS_none; 1477 if (RD && RD->isClass()) 1478 Default = clang::AS_private; 1479 else if (RD && (RD->isStruct() || RD->isUnion())) 1480 Default = clang::AS_public; 1481 1482 if (Access == Default) 1483 return llvm::DINode::FlagZero; 1484 1485 switch (Access) { 1486 case clang::AS_private: 1487 return llvm::DINode::FlagPrivate; 1488 case clang::AS_protected: 1489 return llvm::DINode::FlagProtected; 1490 case clang::AS_public: 1491 return llvm::DINode::FlagPublic; 1492 case clang::AS_none: 1493 return llvm::DINode::FlagZero; 1494 } 1495 llvm_unreachable("unexpected access enumerator"); 1496 } 1497 1498 llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl, 1499 llvm::DIScope *RecordTy, 1500 const RecordDecl *RD) { 1501 StringRef Name = BitFieldDecl->getName(); 1502 QualType Ty = BitFieldDecl->getType(); 1503 SourceLocation Loc = BitFieldDecl->getLocation(); 1504 llvm::DIFile *VUnit = getOrCreateFile(Loc); 1505 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit); 1506 1507 // Get the location for the field. 1508 llvm::DIFile *File = getOrCreateFile(Loc); 1509 unsigned Line = getLineNumber(Loc); 1510 1511 const CGBitFieldInfo &BitFieldInfo = 1512 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl); 1513 uint64_t SizeInBits = BitFieldInfo.Size; 1514 assert(SizeInBits > 0 && "found named 0-width bitfield"); 1515 uint64_t StorageOffsetInBits = 1516 CGM.getContext().toBits(BitFieldInfo.StorageOffset); 1517 uint64_t Offset = BitFieldInfo.Offset; 1518 // The bit offsets for big endian machines are reversed for big 1519 // endian target, compensate for that as the DIDerivedType requires 1520 // un-reversed offsets. 1521 if (CGM.getDataLayout().isBigEndian()) 1522 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset; 1523 uint64_t OffsetInBits = StorageOffsetInBits + Offset; 1524 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD); 1525 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl); 1526 return DBuilder.createBitFieldMemberType( 1527 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits, 1528 Flags, DebugType, Annotations); 1529 } 1530 1531 llvm::DIType * 1532 CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc, 1533 AccessSpecifier AS, uint64_t offsetInBits, 1534 uint32_t AlignInBits, llvm::DIFile *tunit, 1535 llvm::DIScope *scope, const RecordDecl *RD, 1536 llvm::DINodeArray Annotations, TypeLoc TL) { 1537 llvm::DIType *debugType = getOrCreateType(type, tunit, TL); 1538 1539 // Get the location for the field. 1540 llvm::DIFile *file = getOrCreateFile(loc); 1541 const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc); 1542 1543 uint64_t SizeInBits = 0; 1544 auto Align = AlignInBits; 1545 if (!type->isIncompleteArrayType()) { 1546 TypeInfo TI = CGM.getContext().getTypeInfo(type); 1547 SizeInBits = TI.Width; 1548 if (!Align) 1549 Align = getTypeAlignIfRequired(type, CGM.getContext()); 1550 } 1551 1552 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD); 1553 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align, 1554 offsetInBits, flags, debugType, Annotations); 1555 } 1556 1557 void CGDebugInfo::CollectRecordLambdaFields( 1558 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements, 1559 llvm::DIType *RecordTy) { 1560 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture 1561 // has the name and the location of the variable so we should iterate over 1562 // both concurrently. 1563 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl); 1564 RecordDecl::field_iterator Field = CXXDecl->field_begin(); 1565 unsigned fieldno = 0; 1566 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(), 1567 E = CXXDecl->captures_end(); 1568 I != E; ++I, ++Field, ++fieldno) { 1569 const LambdaCapture &C = *I; 1570 if (C.capturesVariable()) { 1571 SourceLocation Loc = C.getLocation(); 1572 assert(!Field->isBitField() && "lambdas don't have bitfield members!"); 1573 VarDecl *V = C.getCapturedVar(); 1574 StringRef VName = V->getName(); 1575 llvm::DIFile *VUnit = getOrCreateFile(Loc); 1576 auto Align = getDeclAlignIfRequired(V, CGM.getContext()); 1577 llvm::DIType *FieldType = createFieldType( 1578 VName, Field->getType(), Loc, Field->getAccess(), 1579 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl); 1580 elements.push_back(FieldType); 1581 } else if (C.capturesThis()) { 1582 // TODO: Need to handle 'this' in some way by probably renaming the 1583 // this of the lambda class and having a field member of 'this' or 1584 // by using AT_object_pointer for the function and having that be 1585 // used as 'this' for semantic references. 1586 FieldDecl *f = *Field; 1587 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation()); 1588 QualType type = f->getType(); 1589 llvm::DIType *fieldType = createFieldType( 1590 "this", type, f->getLocation(), f->getAccess(), 1591 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl); 1592 1593 elements.push_back(fieldType); 1594 } 1595 } 1596 } 1597 1598 llvm::DIDerivedType * 1599 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy, 1600 const RecordDecl *RD) { 1601 // Create the descriptor for the static variable, with or without 1602 // constant initializers. 1603 Var = Var->getCanonicalDecl(); 1604 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation()); 1605 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit); 1606 1607 unsigned LineNumber = getLineNumber(Var->getLocation()); 1608 StringRef VName = Var->getName(); 1609 llvm::Constant *C = nullptr; 1610 if (Var->getInit()) { 1611 const APValue *Value = Var->evaluateValue(); 1612 if (Value) { 1613 if (Value->isInt()) 1614 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt()); 1615 if (Value->isFloat()) 1616 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat()); 1617 } 1618 } 1619 1620 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD); 1621 auto Align = getDeclAlignIfRequired(Var, CGM.getContext()); 1622 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType( 1623 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align); 1624 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV); 1625 return GV; 1626 } 1627 1628 void CGDebugInfo::CollectRecordNormalField( 1629 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit, 1630 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy, 1631 const RecordDecl *RD) { 1632 StringRef name = field->getName(); 1633 QualType type = field->getType(); 1634 1635 // Ignore unnamed fields unless they're anonymous structs/unions. 1636 if (name.empty() && !type->isRecordType()) 1637 return; 1638 1639 llvm::DIType *FieldType; 1640 if (field->isBitField()) { 1641 FieldType = createBitFieldType(field, RecordTy, RD); 1642 } else { 1643 auto Align = getDeclAlignIfRequired(field, CGM.getContext()); 1644 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field); 1645 TypeLoc TL; 1646 if (const TypeSourceInfo *TSI = field->getTypeSourceInfo()) 1647 TL = TSI->getTypeLoc(); 1648 FieldType = createFieldType(name, type, field->getLocation(), 1649 field->getAccess(), OffsetInBits, Align, tunit, 1650 RecordTy, RD, Annotations, TL); 1651 } 1652 1653 elements.push_back(FieldType); 1654 } 1655 1656 void CGDebugInfo::CollectRecordNestedType( 1657 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) { 1658 QualType Ty = CGM.getContext().getTypeDeclType(TD); 1659 // Injected class names are not considered nested records. 1660 if (isa<InjectedClassNameType>(Ty)) 1661 return; 1662 SourceLocation Loc = TD->getLocation(); 1663 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc)); 1664 elements.push_back(nestedType); 1665 } 1666 1667 void CGDebugInfo::CollectRecordFields( 1668 const RecordDecl *record, llvm::DIFile *tunit, 1669 SmallVectorImpl<llvm::Metadata *> &elements, 1670 llvm::DICompositeType *RecordTy) { 1671 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record); 1672 1673 if (CXXDecl && CXXDecl->isLambda()) 1674 CollectRecordLambdaFields(CXXDecl, elements, RecordTy); 1675 else { 1676 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record); 1677 1678 // Field number for non-static fields. 1679 unsigned fieldNo = 0; 1680 1681 // Static and non-static members should appear in the same order as 1682 // the corresponding declarations in the source program. 1683 for (const auto *I : record->decls()) 1684 if (const auto *V = dyn_cast<VarDecl>(I)) { 1685 if (V->hasAttr<NoDebugAttr>()) 1686 continue; 1687 1688 // Skip variable template specializations when emitting CodeView. MSVC 1689 // doesn't emit them. 1690 if (CGM.getCodeGenOpts().EmitCodeView && 1691 isa<VarTemplateSpecializationDecl>(V)) 1692 continue; 1693 1694 if (isa<VarTemplatePartialSpecializationDecl>(V)) 1695 continue; 1696 1697 // Reuse the existing static member declaration if one exists 1698 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl()); 1699 if (MI != StaticDataMemberCache.end()) { 1700 assert(MI->second && 1701 "Static data member declaration should still exist"); 1702 elements.push_back(MI->second); 1703 } else { 1704 auto Field = CreateRecordStaticField(V, RecordTy, record); 1705 elements.push_back(Field); 1706 } 1707 } else if (const auto *field = dyn_cast<FieldDecl>(I)) { 1708 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit, 1709 elements, RecordTy, record); 1710 1711 // Bump field number for next field. 1712 ++fieldNo; 1713 } else if (CGM.getCodeGenOpts().EmitCodeView) { 1714 // Debug info for nested types is included in the member list only for 1715 // CodeView. 1716 if (const auto *nestedType = dyn_cast<TypeDecl>(I)) 1717 if (!nestedType->isImplicit() && 1718 nestedType->getDeclContext() == record) 1719 CollectRecordNestedType(nestedType, elements); 1720 } 1721 } 1722 } 1723 1724 llvm::DISubroutineType * 1725 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 1726 llvm::DIFile *Unit, bool decl) { 1727 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>(); 1728 if (Method->isStatic()) 1729 return cast_or_null<llvm::DISubroutineType>( 1730 getOrCreateType(QualType(Func, 0), Unit)); 1731 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, decl); 1732 } 1733 1734 llvm::DISubroutineType * 1735 CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr, 1736 const FunctionProtoType *Func, 1737 llvm::DIFile *Unit, bool decl) { 1738 FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo(); 1739 Qualifiers &Qc = EPI.TypeQuals; 1740 Qc.removeConst(); 1741 Qc.removeVolatile(); 1742 Qc.removeRestrict(); 1743 Qc.removeUnaligned(); 1744 // Keep the removed qualifiers in sync with 1745 // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit) 1746 // On a 'real' member function type, these qualifiers are carried on the type 1747 // of the first parameter, not as separate DW_TAG_const_type (etc) decorator 1748 // tags around them. (But, in the raw function types with qualifiers, they have 1749 // to use wrapper types.) 1750 1751 // Add "this" pointer. 1752 const auto *OriginalFunc = cast<llvm::DISubroutineType>( 1753 getOrCreateType(CGM.getContext().getFunctionType( 1754 Func->getReturnType(), Func->getParamTypes(), EPI), 1755 Unit)); 1756 llvm::DITypeRefArray Args = OriginalFunc->getTypeArray(); 1757 assert(Args.size() && "Invalid number of arguments!"); 1758 1759 SmallVector<llvm::Metadata *, 16> Elts; 1760 // First element is always return type. For 'void' functions it is NULL. 1761 QualType temp = Func->getReturnType(); 1762 if (temp->getTypeClass() == Type::Auto && decl) 1763 Elts.push_back(CreateType(cast<AutoType>(temp))); 1764 else 1765 Elts.push_back(Args[0]); 1766 1767 // "this" pointer is always first argument. 1768 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl(); 1769 if (isa<ClassTemplateSpecializationDecl>(RD)) { 1770 // Create pointer type directly in this case. 1771 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr); 1772 QualType PointeeTy = ThisPtrTy->getPointeeType(); 1773 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy); 1774 uint64_t Size = CGM.getTarget().getPointerWidth(AS); 1775 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext()); 1776 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit); 1777 llvm::DIType *ThisPtrType = 1778 DBuilder.createPointerType(PointeeType, Size, Align); 1779 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType); 1780 // TODO: This and the artificial type below are misleading, the 1781 // types aren't artificial the argument is, but the current 1782 // metadata doesn't represent that. 1783 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 1784 Elts.push_back(ThisPtrType); 1785 } else { 1786 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit); 1787 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType); 1788 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType); 1789 Elts.push_back(ThisPtrType); 1790 } 1791 1792 // Copy rest of the arguments. 1793 for (unsigned i = 1, e = Args.size(); i != e; ++i) 1794 Elts.push_back(Args[i]); 1795 1796 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 1797 1798 return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(), 1799 getDwarfCC(Func->getCallConv())); 1800 } 1801 1802 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined 1803 /// inside a function. 1804 static bool isFunctionLocalClass(const CXXRecordDecl *RD) { 1805 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext())) 1806 return isFunctionLocalClass(NRD); 1807 if (isa<FunctionDecl>(RD->getDeclContext())) 1808 return true; 1809 return false; 1810 } 1811 1812 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction( 1813 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) { 1814 bool IsCtorOrDtor = 1815 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 1816 1817 StringRef MethodName = getFunctionName(Method); 1818 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit, true); 1819 1820 // Since a single ctor/dtor corresponds to multiple functions, it doesn't 1821 // make sense to give a single ctor/dtor a linkage name. 1822 StringRef MethodLinkageName; 1823 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional 1824 // property to use here. It may've been intended to model "is non-external 1825 // type" but misses cases of non-function-local but non-external classes such 1826 // as those in anonymous namespaces as well as the reverse - external types 1827 // that are function local, such as those in (non-local) inline functions. 1828 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent())) 1829 MethodLinkageName = CGM.getMangledName(Method); 1830 1831 // Get the location for the method. 1832 llvm::DIFile *MethodDefUnit = nullptr; 1833 unsigned MethodLine = 0; 1834 if (!Method->isImplicit()) { 1835 MethodDefUnit = getOrCreateFile(Method->getLocation()); 1836 MethodLine = getLineNumber(Method->getLocation()); 1837 } 1838 1839 // Collect virtual method info. 1840 llvm::DIType *ContainingType = nullptr; 1841 unsigned VIndex = 0; 1842 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 1843 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 1844 int ThisAdjustment = 0; 1845 1846 if (Method->isVirtual()) { 1847 if (Method->isPure()) 1848 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual; 1849 else 1850 SPFlags |= llvm::DISubprogram::SPFlagVirtual; 1851 1852 if (CGM.getTarget().getCXXABI().isItaniumFamily()) { 1853 // It doesn't make sense to give a virtual destructor a vtable index, 1854 // since a single destructor has two entries in the vtable. 1855 if (!isa<CXXDestructorDecl>(Method)) 1856 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method); 1857 } else { 1858 // Emit MS ABI vftable information. There is only one entry for the 1859 // deleting dtor. 1860 const auto *DD = dyn_cast<CXXDestructorDecl>(Method); 1861 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method); 1862 MethodVFTableLocation ML = 1863 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); 1864 VIndex = ML.Index; 1865 1866 // CodeView only records the vftable offset in the class that introduces 1867 // the virtual method. This is possible because, unlike Itanium, the MS 1868 // C++ ABI does not include all virtual methods from non-primary bases in 1869 // the vtable for the most derived class. For example, if C inherits from 1870 // A and B, C's primary vftable will not include B's virtual methods. 1871 if (Method->size_overridden_methods() == 0) 1872 Flags |= llvm::DINode::FlagIntroducedVirtual; 1873 1874 // The 'this' adjustment accounts for both the virtual and non-virtual 1875 // portions of the adjustment. Presumably the debugger only uses it when 1876 // it knows the dynamic type of an object. 1877 ThisAdjustment = CGM.getCXXABI() 1878 .getVirtualFunctionPrologueThisAdjustment(GD) 1879 .getQuantity(); 1880 } 1881 ContainingType = RecordTy; 1882 } 1883 1884 // We're checking for deleted C++ special member functions 1885 // [Ctors,Dtors, Copy/Move] 1886 auto checkAttrDeleted = [&](const auto *Method) { 1887 if (Method->getCanonicalDecl()->isDeleted()) 1888 SPFlags |= llvm::DISubprogram::SPFlagDeleted; 1889 }; 1890 1891 switch (Method->getKind()) { 1892 1893 case Decl::CXXConstructor: 1894 case Decl::CXXDestructor: 1895 checkAttrDeleted(Method); 1896 break; 1897 case Decl::CXXMethod: 1898 if (Method->isCopyAssignmentOperator() || 1899 Method->isMoveAssignmentOperator()) 1900 checkAttrDeleted(Method); 1901 break; 1902 default: 1903 break; 1904 } 1905 1906 if (Method->isNoReturn()) 1907 Flags |= llvm::DINode::FlagNoReturn; 1908 1909 if (Method->isStatic()) 1910 Flags |= llvm::DINode::FlagStaticMember; 1911 if (Method->isImplicit()) 1912 Flags |= llvm::DINode::FlagArtificial; 1913 Flags |= getAccessFlag(Method->getAccess(), Method->getParent()); 1914 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 1915 if (CXXC->isExplicit()) 1916 Flags |= llvm::DINode::FlagExplicit; 1917 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) { 1918 if (CXXC->isExplicit()) 1919 Flags |= llvm::DINode::FlagExplicit; 1920 } 1921 if (Method->hasPrototype()) 1922 Flags |= llvm::DINode::FlagPrototyped; 1923 if (Method->getRefQualifier() == RQ_LValue) 1924 Flags |= llvm::DINode::FlagLValueReference; 1925 if (Method->getRefQualifier() == RQ_RValue) 1926 Flags |= llvm::DINode::FlagRValueReference; 1927 if (!Method->isExternallyVisible()) 1928 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; 1929 if (CGM.getLangOpts().Optimize) 1930 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 1931 1932 // In this debug mode, emit type info for a class when its constructor type 1933 // info is emitted. 1934 if (DebugKind == codegenoptions::DebugInfoConstructor) 1935 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 1936 completeUnusedClass(*CD->getParent()); 1937 1938 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit); 1939 llvm::DISubprogram *SP = DBuilder.createMethod( 1940 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine, 1941 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags, 1942 TParamsArray.get()); 1943 1944 SPCache[Method->getCanonicalDecl()].reset(SP); 1945 1946 return SP; 1947 } 1948 1949 void CGDebugInfo::CollectCXXMemberFunctions( 1950 const CXXRecordDecl *RD, llvm::DIFile *Unit, 1951 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) { 1952 1953 // Since we want more than just the individual member decls if we 1954 // have templated functions iterate over every declaration to gather 1955 // the functions. 1956 for (const auto *I : RD->decls()) { 1957 const auto *Method = dyn_cast<CXXMethodDecl>(I); 1958 // If the member is implicit, don't add it to the member list. This avoids 1959 // the member being added to type units by LLVM, while still allowing it 1960 // to be emitted into the type declaration/reference inside the compile 1961 // unit. 1962 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp. 1963 // FIXME: Handle Using(Shadow?)Decls here to create 1964 // DW_TAG_imported_declarations inside the class for base decls brought into 1965 // derived classes. GDB doesn't seem to notice/leverage these when I tried 1966 // it, so I'm not rushing to fix this. (GCC seems to produce them, if 1967 // referenced) 1968 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>()) 1969 continue; 1970 1971 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType()) 1972 continue; 1973 1974 // Reuse the existing member function declaration if it exists. 1975 // It may be associated with the declaration of the type & should be 1976 // reused as we're building the definition. 1977 // 1978 // This situation can arise in the vtable-based debug info reduction where 1979 // implicit members are emitted in a non-vtable TU. 1980 auto MI = SPCache.find(Method->getCanonicalDecl()); 1981 EltTys.push_back(MI == SPCache.end() 1982 ? CreateCXXMemberFunction(Method, Unit, RecordTy) 1983 : static_cast<llvm::Metadata *>(MI->second)); 1984 } 1985 } 1986 1987 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit, 1988 SmallVectorImpl<llvm::Metadata *> &EltTys, 1989 llvm::DIType *RecordTy) { 1990 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes; 1991 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes, 1992 llvm::DINode::FlagZero); 1993 1994 // If we are generating CodeView debug info, we also need to emit records for 1995 // indirect virtual base classes. 1996 if (CGM.getCodeGenOpts().EmitCodeView) { 1997 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes, 1998 llvm::DINode::FlagIndirectVirtualBase); 1999 } 2000 } 2001 2002 void CGDebugInfo::CollectCXXBasesAux( 2003 const CXXRecordDecl *RD, llvm::DIFile *Unit, 2004 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy, 2005 const CXXRecordDecl::base_class_const_range &Bases, 2006 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes, 2007 llvm::DINode::DIFlags StartingFlags) { 2008 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 2009 for (const auto &BI : Bases) { 2010 const auto *Base = 2011 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl()); 2012 if (!SeenTypes.insert(Base).second) 2013 continue; 2014 auto *BaseTy = getOrCreateType(BI.getType(), Unit); 2015 llvm::DINode::DIFlags BFlags = StartingFlags; 2016 uint64_t BaseOffset; 2017 uint32_t VBPtrOffset = 0; 2018 2019 if (BI.isVirtual()) { 2020 if (CGM.getTarget().getCXXABI().isItaniumFamily()) { 2021 // virtual base offset offset is -ve. The code generator emits dwarf 2022 // expression where it expects +ve number. 2023 BaseOffset = 0 - CGM.getItaniumVTableContext() 2024 .getVirtualBaseOffsetOffset(RD, Base) 2025 .getQuantity(); 2026 } else { 2027 // In the MS ABI, store the vbtable offset, which is analogous to the 2028 // vbase offset offset in Itanium. 2029 BaseOffset = 2030 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base); 2031 VBPtrOffset = CGM.getContext() 2032 .getASTRecordLayout(RD) 2033 .getVBPtrOffset() 2034 .getQuantity(); 2035 } 2036 BFlags |= llvm::DINode::FlagVirtual; 2037 } else 2038 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base)); 2039 // FIXME: Inconsistent units for BaseOffset. It is in bytes when 2040 // BI->isVirtual() and bits when not. 2041 2042 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD); 2043 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset, 2044 VBPtrOffset, BFlags); 2045 EltTys.push_back(DTy); 2046 } 2047 } 2048 2049 llvm::DINodeArray 2050 CGDebugInfo::CollectTemplateParams(Optional<TemplateArgs> OArgs, 2051 llvm::DIFile *Unit) { 2052 if (!OArgs) 2053 return llvm::DINodeArray(); 2054 TemplateArgs &Args = *OArgs; 2055 SmallVector<llvm::Metadata *, 16> TemplateParams; 2056 for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) { 2057 const TemplateArgument &TA = Args.Args[i]; 2058 StringRef Name; 2059 bool defaultParameter = false; 2060 if (Args.TList) 2061 Name = Args.TList->getParam(i)->getName(); 2062 switch (TA.getKind()) { 2063 case TemplateArgument::Type: { 2064 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit); 2065 2066 if (Args.TList) 2067 if (auto *templateType = 2068 dyn_cast_or_null<TemplateTypeParmDecl>(Args.TList->getParam(i))) 2069 if (templateType->hasDefaultArgument()) 2070 defaultParameter = 2071 templateType->getDefaultArgument() == TA.getAsType(); 2072 2073 TemplateParams.push_back(DBuilder.createTemplateTypeParameter( 2074 TheCU, Name, TTy, defaultParameter)); 2075 2076 } break; 2077 case TemplateArgument::Integral: { 2078 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit); 2079 if (Args.TList && CGM.getCodeGenOpts().DwarfVersion >= 5) 2080 if (auto *templateType = dyn_cast_or_null<NonTypeTemplateParmDecl>( 2081 Args.TList->getParam(i))) 2082 if (templateType->hasDefaultArgument() && 2083 !templateType->getDefaultArgument()->isValueDependent()) 2084 defaultParameter = llvm::APSInt::isSameValue( 2085 templateType->getDefaultArgument()->EvaluateKnownConstInt( 2086 CGM.getContext()), 2087 TA.getAsIntegral()); 2088 2089 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 2090 TheCU, Name, TTy, defaultParameter, 2091 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()))); 2092 } break; 2093 case TemplateArgument::Declaration: { 2094 const ValueDecl *D = TA.getAsDecl(); 2095 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext()); 2096 llvm::DIType *TTy = getOrCreateType(T, Unit); 2097 llvm::Constant *V = nullptr; 2098 // Skip retrieve the value if that template parameter has cuda device 2099 // attribute, i.e. that value is not available at the host side. 2100 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice || 2101 !D->hasAttr<CUDADeviceAttr>()) { 2102 const CXXMethodDecl *MD; 2103 // Variable pointer template parameters have a value that is the address 2104 // of the variable. 2105 if (const auto *VD = dyn_cast<VarDecl>(D)) 2106 V = CGM.GetAddrOfGlobalVar(VD); 2107 // Member function pointers have special support for building them, 2108 // though this is currently unsupported in LLVM CodeGen. 2109 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance()) 2110 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD); 2111 else if (const auto *FD = dyn_cast<FunctionDecl>(D)) 2112 V = CGM.GetAddrOfFunction(FD); 2113 // Member data pointers have special handling too to compute the fixed 2114 // offset within the object. 2115 else if (const auto *MPT = 2116 dyn_cast<MemberPointerType>(T.getTypePtr())) { 2117 // These five lines (& possibly the above member function pointer 2118 // handling) might be able to be refactored to use similar code in 2119 // CodeGenModule::getMemberPointerConstant 2120 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D); 2121 CharUnits chars = 2122 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset); 2123 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars); 2124 } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) { 2125 V = CGM.GetAddrOfMSGuidDecl(GD).getPointer(); 2126 } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 2127 if (T->isRecordType()) 2128 V = ConstantEmitter(CGM).emitAbstract( 2129 SourceLocation(), TPO->getValue(), TPO->getType()); 2130 else 2131 V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer(); 2132 } 2133 assert(V && "Failed to find template parameter pointer"); 2134 V = V->stripPointerCasts(); 2135 } 2136 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 2137 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V))); 2138 } break; 2139 case TemplateArgument::NullPtr: { 2140 QualType T = TA.getNullPtrType(); 2141 llvm::DIType *TTy = getOrCreateType(T, Unit); 2142 llvm::Constant *V = nullptr; 2143 // Special case member data pointer null values since they're actually -1 2144 // instead of zero. 2145 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) 2146 // But treat member function pointers as simple zero integers because 2147 // it's easier than having a special case in LLVM's CodeGen. If LLVM 2148 // CodeGen grows handling for values of non-null member function 2149 // pointers then perhaps we could remove this special case and rely on 2150 // EmitNullMemberPointer for member function pointers. 2151 if (MPT->isMemberDataPointer()) 2152 V = CGM.getCXXABI().EmitNullMemberPointer(MPT); 2153 if (!V) 2154 V = llvm::ConstantInt::get(CGM.Int8Ty, 0); 2155 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 2156 TheCU, Name, TTy, defaultParameter, V)); 2157 } break; 2158 case TemplateArgument::Template: { 2159 std::string QualName; 2160 llvm::raw_string_ostream OS(QualName); 2161 TA.getAsTemplate().getAsTemplateDecl()->printQualifiedName( 2162 OS, getPrintingPolicy()); 2163 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter( 2164 TheCU, Name, nullptr, OS.str())); 2165 break; 2166 } 2167 case TemplateArgument::Pack: 2168 TemplateParams.push_back(DBuilder.createTemplateParameterPack( 2169 TheCU, Name, nullptr, 2170 CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit))); 2171 break; 2172 case TemplateArgument::Expression: { 2173 const Expr *E = TA.getAsExpr(); 2174 QualType T = E->getType(); 2175 if (E->isGLValue()) 2176 T = CGM.getContext().getLValueReferenceType(T); 2177 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T); 2178 assert(V && "Expression in template argument isn't constant"); 2179 llvm::DIType *TTy = getOrCreateType(T, Unit); 2180 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 2181 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts())); 2182 } break; 2183 // And the following should never occur: 2184 case TemplateArgument::TemplateExpansion: 2185 case TemplateArgument::Null: 2186 llvm_unreachable( 2187 "These argument types shouldn't exist in concrete types"); 2188 } 2189 } 2190 return DBuilder.getOrCreateArray(TemplateParams); 2191 } 2192 2193 Optional<CGDebugInfo::TemplateArgs> 2194 CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const { 2195 if (FD->getTemplatedKind() == 2196 FunctionDecl::TK_FunctionTemplateSpecialization) { 2197 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo() 2198 ->getTemplate() 2199 ->getTemplateParameters(); 2200 return {{TList, FD->getTemplateSpecializationArgs()->asArray()}}; 2201 } 2202 return None; 2203 } 2204 Optional<CGDebugInfo::TemplateArgs> 2205 CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const { 2206 // Always get the full list of parameters, not just the ones from the 2207 // specialization. A partial specialization may have fewer parameters than 2208 // there are arguments. 2209 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD); 2210 if (!TS) 2211 return None; 2212 VarTemplateDecl *T = TS->getSpecializedTemplate(); 2213 const TemplateParameterList *TList = T->getTemplateParameters(); 2214 auto TA = TS->getTemplateArgs().asArray(); 2215 return {{TList, TA}}; 2216 } 2217 Optional<CGDebugInfo::TemplateArgs> 2218 CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const { 2219 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 2220 // Always get the full list of parameters, not just the ones from the 2221 // specialization. A partial specialization may have fewer parameters than 2222 // there are arguments. 2223 TemplateParameterList *TPList = 2224 TSpecial->getSpecializedTemplate()->getTemplateParameters(); 2225 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs(); 2226 return {{TPList, TAList.asArray()}}; 2227 } 2228 return None; 2229 } 2230 2231 llvm::DINodeArray 2232 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD, 2233 llvm::DIFile *Unit) { 2234 return CollectTemplateParams(GetTemplateArgs(FD), Unit); 2235 } 2236 2237 llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL, 2238 llvm::DIFile *Unit) { 2239 return CollectTemplateParams(GetTemplateArgs(VL), Unit); 2240 } 2241 2242 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD, 2243 llvm::DIFile *Unit) { 2244 return CollectTemplateParams(GetTemplateArgs(RD), Unit); 2245 } 2246 2247 llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) { 2248 if (!D->hasAttr<BTFDeclTagAttr>()) 2249 return nullptr; 2250 2251 SmallVector<llvm::Metadata *, 4> Annotations; 2252 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) { 2253 llvm::Metadata *Ops[2] = { 2254 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")), 2255 llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())}; 2256 Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2257 } 2258 return DBuilder.getOrCreateArray(Annotations); 2259 } 2260 2261 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) { 2262 if (VTablePtrType) 2263 return VTablePtrType; 2264 2265 ASTContext &Context = CGM.getContext(); 2266 2267 /* Function type */ 2268 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit); 2269 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy); 2270 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements); 2271 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 2272 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace(); 2273 Optional<unsigned> DWARFAddressSpace = 2274 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace); 2275 2276 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType( 2277 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type"); 2278 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 2279 return VTablePtrType; 2280 } 2281 2282 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 2283 // Copy the gdb compatible name on the side and use its reference. 2284 return internString("_vptr$", RD->getNameAsString()); 2285 } 2286 2287 StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD, 2288 DynamicInitKind StubKind, 2289 llvm::Function *InitFn) { 2290 // If we're not emitting codeview, use the mangled name. For Itanium, this is 2291 // arbitrary. 2292 if (!CGM.getCodeGenOpts().EmitCodeView || 2293 StubKind == DynamicInitKind::GlobalArrayDestructor) 2294 return InitFn->getName(); 2295 2296 // Print the normal qualified name for the variable, then break off the last 2297 // NNS, and add the appropriate other text. Clang always prints the global 2298 // variable name without template arguments, so we can use rsplit("::") and 2299 // then recombine the pieces. 2300 SmallString<128> QualifiedGV; 2301 StringRef Quals; 2302 StringRef GVName; 2303 { 2304 llvm::raw_svector_ostream OS(QualifiedGV); 2305 VD->printQualifiedName(OS, getPrintingPolicy()); 2306 std::tie(Quals, GVName) = OS.str().rsplit("::"); 2307 if (GVName.empty()) 2308 std::swap(Quals, GVName); 2309 } 2310 2311 SmallString<128> InitName; 2312 llvm::raw_svector_ostream OS(InitName); 2313 if (!Quals.empty()) 2314 OS << Quals << "::"; 2315 2316 switch (StubKind) { 2317 case DynamicInitKind::NoStub: 2318 case DynamicInitKind::GlobalArrayDestructor: 2319 llvm_unreachable("not an initializer"); 2320 case DynamicInitKind::Initializer: 2321 OS << "`dynamic initializer for '"; 2322 break; 2323 case DynamicInitKind::AtExit: 2324 OS << "`dynamic atexit destructor for '"; 2325 break; 2326 } 2327 2328 OS << GVName; 2329 2330 // Add any template specialization args. 2331 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) { 2332 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(), 2333 getPrintingPolicy()); 2334 } 2335 2336 OS << '\''; 2337 2338 return internString(OS.str()); 2339 } 2340 2341 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit, 2342 SmallVectorImpl<llvm::Metadata *> &EltTys) { 2343 // If this class is not dynamic then there is not any vtable info to collect. 2344 if (!RD->isDynamicClass()) 2345 return; 2346 2347 // Don't emit any vtable shape or vptr info if this class doesn't have an 2348 // extendable vfptr. This can happen if the class doesn't have virtual 2349 // methods, or in the MS ABI if those virtual methods only come from virtually 2350 // inherited bases. 2351 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 2352 if (!RL.hasExtendableVFPtr()) 2353 return; 2354 2355 // CodeView needs to know how large the vtable of every dynamic class is, so 2356 // emit a special named pointer type into the element list. The vptr type 2357 // points to this type as well. 2358 llvm::DIType *VPtrTy = nullptr; 2359 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView && 2360 CGM.getTarget().getCXXABI().isMicrosoft(); 2361 if (NeedVTableShape) { 2362 uint64_t PtrWidth = 2363 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 2364 const VTableLayout &VFTLayout = 2365 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero()); 2366 unsigned VSlotCount = 2367 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData; 2368 unsigned VTableWidth = PtrWidth * VSlotCount; 2369 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace(); 2370 Optional<unsigned> DWARFAddressSpace = 2371 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace); 2372 2373 // Create a very wide void* type and insert it directly in the element list. 2374 llvm::DIType *VTableType = DBuilder.createPointerType( 2375 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type"); 2376 EltTys.push_back(VTableType); 2377 2378 // The vptr is a pointer to this special vtable type. 2379 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth); 2380 } 2381 2382 // If there is a primary base then the artificial vptr member lives there. 2383 if (RL.getPrimaryBase()) 2384 return; 2385 2386 if (!VPtrTy) 2387 VPtrTy = getOrCreateVTablePtrType(Unit); 2388 2389 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 2390 llvm::DIType *VPtrMember = 2391 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0, 2392 llvm::DINode::FlagArtificial, VPtrTy); 2393 EltTys.push_back(VPtrMember); 2394 } 2395 2396 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy, 2397 SourceLocation Loc) { 2398 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 2399 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc)); 2400 return T; 2401 } 2402 2403 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D, 2404 SourceLocation Loc) { 2405 return getOrCreateStandaloneType(D, Loc); 2406 } 2407 2408 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D, 2409 SourceLocation Loc) { 2410 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 2411 assert(!D.isNull() && "null type"); 2412 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc)); 2413 assert(T && "could not create debug info for type"); 2414 2415 RetainedTypes.push_back(D.getAsOpaquePtr()); 2416 return T; 2417 } 2418 2419 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI, 2420 QualType AllocatedTy, 2421 SourceLocation Loc) { 2422 if (CGM.getCodeGenOpts().getDebugInfo() <= 2423 codegenoptions::DebugLineTablesOnly) 2424 return; 2425 llvm::MDNode *node; 2426 if (AllocatedTy->isVoidType()) 2427 node = llvm::MDNode::get(CGM.getLLVMContext(), None); 2428 else 2429 node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc)); 2430 2431 CI->setMetadata("heapallocsite", node); 2432 } 2433 2434 void CGDebugInfo::completeType(const EnumDecl *ED) { 2435 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 2436 return; 2437 QualType Ty = CGM.getContext().getEnumType(ED); 2438 void *TyPtr = Ty.getAsOpaquePtr(); 2439 auto I = TypeCache.find(TyPtr); 2440 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl()) 2441 return; 2442 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>()); 2443 assert(!Res->isForwardDecl()); 2444 TypeCache[TyPtr].reset(Res); 2445 } 2446 2447 void CGDebugInfo::completeType(const RecordDecl *RD) { 2448 if (DebugKind > codegenoptions::LimitedDebugInfo || 2449 !CGM.getLangOpts().CPlusPlus) 2450 completeRequiredType(RD); 2451 } 2452 2453 /// Return true if the class or any of its methods are marked dllimport. 2454 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) { 2455 if (RD->hasAttr<DLLImportAttr>()) 2456 return true; 2457 for (const CXXMethodDecl *MD : RD->methods()) 2458 if (MD->hasAttr<DLLImportAttr>()) 2459 return true; 2460 return false; 2461 } 2462 2463 /// Does a type definition exist in an imported clang module? 2464 static bool isDefinedInClangModule(const RecordDecl *RD) { 2465 // Only definitions that where imported from an AST file come from a module. 2466 if (!RD || !RD->isFromASTFile()) 2467 return false; 2468 // Anonymous entities cannot be addressed. Treat them as not from module. 2469 if (!RD->isExternallyVisible() && RD->getName().empty()) 2470 return false; 2471 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) { 2472 if (!CXXDecl->isCompleteDefinition()) 2473 return false; 2474 // Check wether RD is a template. 2475 auto TemplateKind = CXXDecl->getTemplateSpecializationKind(); 2476 if (TemplateKind != TSK_Undeclared) { 2477 // Unfortunately getOwningModule() isn't accurate enough to find the 2478 // owning module of a ClassTemplateSpecializationDecl that is inside a 2479 // namespace spanning multiple modules. 2480 bool Explicit = false; 2481 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl)) 2482 Explicit = TD->isExplicitInstantiationOrSpecialization(); 2483 if (!Explicit && CXXDecl->getEnclosingNamespaceContext()) 2484 return false; 2485 // This is a template, check the origin of the first member. 2486 if (CXXDecl->field_begin() == CXXDecl->field_end()) 2487 return TemplateKind == TSK_ExplicitInstantiationDeclaration; 2488 if (!CXXDecl->field_begin()->isFromASTFile()) 2489 return false; 2490 } 2491 } 2492 return true; 2493 } 2494 2495 void CGDebugInfo::completeClassData(const RecordDecl *RD) { 2496 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 2497 if (CXXRD->isDynamicClass() && 2498 CGM.getVTableLinkage(CXXRD) == 2499 llvm::GlobalValue::AvailableExternallyLinkage && 2500 !isClassOrMethodDLLImport(CXXRD)) 2501 return; 2502 2503 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition())) 2504 return; 2505 2506 completeClass(RD); 2507 } 2508 2509 void CGDebugInfo::completeClass(const RecordDecl *RD) { 2510 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 2511 return; 2512 QualType Ty = CGM.getContext().getRecordType(RD); 2513 void *TyPtr = Ty.getAsOpaquePtr(); 2514 auto I = TypeCache.find(TyPtr); 2515 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl()) 2516 return; 2517 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>()); 2518 assert(!Res->isForwardDecl()); 2519 TypeCache[TyPtr].reset(Res); 2520 } 2521 2522 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, 2523 CXXRecordDecl::method_iterator End) { 2524 for (CXXMethodDecl *MD : llvm::make_range(I, End)) 2525 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction()) 2526 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() && 2527 !MD->getMemberSpecializationInfo()->isExplicitSpecialization()) 2528 return true; 2529 return false; 2530 } 2531 2532 static bool canUseCtorHoming(const CXXRecordDecl *RD) { 2533 // Constructor homing can be used for classes that cannnot be constructed 2534 // without emitting code for one of their constructors. This is classes that 2535 // don't have trivial or constexpr constructors, or can be created from 2536 // aggregate initialization. Also skip lambda objects because they don't call 2537 // constructors. 2538 2539 // Skip this optimization if the class or any of its methods are marked 2540 // dllimport. 2541 if (isClassOrMethodDLLImport(RD)) 2542 return false; 2543 2544 return !RD->isLambda() && !RD->isAggregate() && 2545 !RD->hasTrivialDefaultConstructor() && 2546 !RD->hasConstexprNonCopyMoveConstructor(); 2547 } 2548 2549 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind, 2550 bool DebugTypeExtRefs, const RecordDecl *RD, 2551 const LangOptions &LangOpts) { 2552 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition())) 2553 return true; 2554 2555 if (auto *ES = RD->getASTContext().getExternalSource()) 2556 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always) 2557 return true; 2558 2559 // Only emit forward declarations in line tables only to keep debug info size 2560 // small. This only applies to CodeView, since we don't emit types in DWARF 2561 // line tables only. 2562 if (DebugKind == codegenoptions::DebugLineTablesOnly) 2563 return true; 2564 2565 if (DebugKind > codegenoptions::LimitedDebugInfo || 2566 RD->hasAttr<StandaloneDebugAttr>()) 2567 return false; 2568 2569 if (!LangOpts.CPlusPlus) 2570 return false; 2571 2572 if (!RD->isCompleteDefinitionRequired()) 2573 return true; 2574 2575 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 2576 2577 if (!CXXDecl) 2578 return false; 2579 2580 // Only emit complete debug info for a dynamic class when its vtable is 2581 // emitted. However, Microsoft debuggers don't resolve type information 2582 // across DLL boundaries, so skip this optimization if the class or any of its 2583 // methods are marked dllimport. This isn't a complete solution, since objects 2584 // without any dllimport methods can be used in one DLL and constructed in 2585 // another, but it is the current behavior of LimitedDebugInfo. 2586 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() && 2587 !isClassOrMethodDLLImport(CXXDecl)) 2588 return true; 2589 2590 TemplateSpecializationKind Spec = TSK_Undeclared; 2591 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 2592 Spec = SD->getSpecializationKind(); 2593 2594 if (Spec == TSK_ExplicitInstantiationDeclaration && 2595 hasExplicitMemberDefinition(CXXDecl->method_begin(), 2596 CXXDecl->method_end())) 2597 return true; 2598 2599 // In constructor homing mode, only emit complete debug info for a class 2600 // when its constructor is emitted. 2601 if ((DebugKind == codegenoptions::DebugInfoConstructor) && 2602 canUseCtorHoming(CXXDecl)) 2603 return true; 2604 2605 return false; 2606 } 2607 2608 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) { 2609 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts())) 2610 return; 2611 2612 QualType Ty = CGM.getContext().getRecordType(RD); 2613 llvm::DIType *T = getTypeOrNull(Ty); 2614 if (T && T->isForwardDecl()) 2615 completeClassData(RD); 2616 } 2617 2618 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) { 2619 RecordDecl *RD = Ty->getDecl(); 2620 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0))); 2621 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, 2622 CGM.getLangOpts())) { 2623 if (!T) 2624 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD)); 2625 return T; 2626 } 2627 2628 return CreateTypeDefinition(Ty); 2629 } 2630 2631 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) { 2632 RecordDecl *RD = Ty->getDecl(); 2633 2634 // Get overall information about the record type for the debug info. 2635 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 2636 2637 // Records and classes and unions can all be recursive. To handle them, we 2638 // first generate a debug descriptor for the struct as a forward declaration. 2639 // Then (if it is a definition) we go through and get debug info for all of 2640 // its members. Finally, we create a descriptor for the complete type (which 2641 // may refer to the forward decl if the struct is recursive) and replace all 2642 // uses of the forward declaration with the final definition. 2643 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty); 2644 2645 const RecordDecl *D = RD->getDefinition(); 2646 if (!D || !D->isCompleteDefinition()) 2647 return FwdDecl; 2648 2649 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) 2650 CollectContainingType(CXXDecl, FwdDecl); 2651 2652 // Push the struct on region stack. 2653 LexicalBlockStack.emplace_back(&*FwdDecl); 2654 RegionMap[Ty->getDecl()].reset(FwdDecl); 2655 2656 // Convert all the elements. 2657 SmallVector<llvm::Metadata *, 16> EltTys; 2658 // what about nested types? 2659 2660 // Note: The split of CXXDecl information here is intentional, the 2661 // gdb tests will depend on a certain ordering at printout. The debug 2662 // information offsets are still correct if we merge them all together 2663 // though. 2664 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 2665 if (CXXDecl) { 2666 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl); 2667 CollectVTableInfo(CXXDecl, DefUnit, EltTys); 2668 } 2669 2670 // Collect data fields (including static variables and any initializers). 2671 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl); 2672 if (CXXDecl) 2673 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl); 2674 2675 LexicalBlockStack.pop_back(); 2676 RegionMap.erase(Ty->getDecl()); 2677 2678 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 2679 DBuilder.replaceArrays(FwdDecl, Elements); 2680 2681 if (FwdDecl->isTemporary()) 2682 FwdDecl = 2683 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl)); 2684 2685 RegionMap[Ty->getDecl()].reset(FwdDecl); 2686 return FwdDecl; 2687 } 2688 2689 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty, 2690 llvm::DIFile *Unit) { 2691 // Ignore protocols. 2692 return getOrCreateType(Ty->getBaseType(), Unit); 2693 } 2694 2695 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty, 2696 llvm::DIFile *Unit) { 2697 // Ignore protocols. 2698 SourceLocation Loc = Ty->getDecl()->getLocation(); 2699 2700 // Use Typedefs to represent ObjCTypeParamType. 2701 return DBuilder.createTypedef( 2702 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit), 2703 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc), 2704 getDeclContextDescriptor(Ty->getDecl())); 2705 } 2706 2707 /// \return true if Getter has the default name for the property PD. 2708 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, 2709 const ObjCMethodDecl *Getter) { 2710 assert(PD); 2711 if (!Getter) 2712 return true; 2713 2714 assert(Getter->getDeclName().isObjCZeroArgSelector()); 2715 return PD->getName() == 2716 Getter->getDeclName().getObjCSelector().getNameForSlot(0); 2717 } 2718 2719 /// \return true if Setter has the default name for the property PD. 2720 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, 2721 const ObjCMethodDecl *Setter) { 2722 assert(PD); 2723 if (!Setter) 2724 return true; 2725 2726 assert(Setter->getDeclName().isObjCOneArgSelector()); 2727 return SelectorTable::constructSetterName(PD->getName()) == 2728 Setter->getDeclName().getObjCSelector().getNameForSlot(0); 2729 } 2730 2731 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 2732 llvm::DIFile *Unit) { 2733 ObjCInterfaceDecl *ID = Ty->getDecl(); 2734 if (!ID) 2735 return nullptr; 2736 2737 // Return a forward declaration if this type was imported from a clang module, 2738 // and this is not the compile unit with the implementation of the type (which 2739 // may contain hidden ivars). 2740 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() && 2741 !ID->getImplementation()) 2742 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, 2743 ID->getName(), 2744 getDeclContextDescriptor(ID), Unit, 0); 2745 2746 // Get overall information about the record type for the debug info. 2747 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation()); 2748 unsigned Line = getLineNumber(ID->getLocation()); 2749 auto RuntimeLang = 2750 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage()); 2751 2752 // If this is just a forward declaration return a special forward-declaration 2753 // debug type since we won't be able to lay out the entire type. 2754 ObjCInterfaceDecl *Def = ID->getDefinition(); 2755 if (!Def || !Def->getImplementation()) { 2756 llvm::DIScope *Mod = getParentModuleOrNull(ID); 2757 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType( 2758 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU, 2759 DefUnit, Line, RuntimeLang); 2760 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit)); 2761 return FwdDecl; 2762 } 2763 2764 return CreateTypeDefinition(Ty, Unit); 2765 } 2766 2767 llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod, 2768 bool CreateSkeletonCU) { 2769 // Use the Module pointer as the key into the cache. This is a 2770 // nullptr if the "Module" is a PCH, which is safe because we don't 2771 // support chained PCH debug info, so there can only be a single PCH. 2772 const Module *M = Mod.getModuleOrNull(); 2773 auto ModRef = ModuleCache.find(M); 2774 if (ModRef != ModuleCache.end()) 2775 return cast<llvm::DIModule>(ModRef->second); 2776 2777 // Macro definitions that were defined with "-D" on the command line. 2778 SmallString<128> ConfigMacros; 2779 { 2780 llvm::raw_svector_ostream OS(ConfigMacros); 2781 const auto &PPOpts = CGM.getPreprocessorOpts(); 2782 unsigned I = 0; 2783 // Translate the macro definitions back into a command line. 2784 for (auto &M : PPOpts.Macros) { 2785 if (++I > 1) 2786 OS << " "; 2787 const std::string &Macro = M.first; 2788 bool Undef = M.second; 2789 OS << "\"-" << (Undef ? 'U' : 'D'); 2790 for (char c : Macro) 2791 switch (c) { 2792 case '\\': 2793 OS << "\\\\"; 2794 break; 2795 case '"': 2796 OS << "\\\""; 2797 break; 2798 default: 2799 OS << c; 2800 } 2801 OS << '\"'; 2802 } 2803 } 2804 2805 bool IsRootModule = M ? !M->Parent : true; 2806 // When a module name is specified as -fmodule-name, that module gets a 2807 // clang::Module object, but it won't actually be built or imported; it will 2808 // be textual. 2809 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M) 2810 assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) && 2811 "clang module without ASTFile must be specified by -fmodule-name"); 2812 2813 // Return a StringRef to the remapped Path. 2814 auto RemapPath = [this](StringRef Path) -> std::string { 2815 std::string Remapped = remapDIPath(Path); 2816 StringRef Relative(Remapped); 2817 StringRef CompDir = TheCU->getDirectory(); 2818 if (Relative.consume_front(CompDir)) 2819 Relative.consume_front(llvm::sys::path::get_separator()); 2820 2821 return Relative.str(); 2822 }; 2823 2824 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) { 2825 // PCH files don't have a signature field in the control block, 2826 // but LLVM detects skeleton CUs by looking for a non-zero DWO id. 2827 // We use the lower 64 bits for debug info. 2828 2829 uint64_t Signature = 0; 2830 if (const auto &ModSig = Mod.getSignature()) 2831 Signature = ModSig.truncatedValue(); 2832 else 2833 Signature = ~1ULL; 2834 2835 llvm::DIBuilder DIB(CGM.getModule()); 2836 SmallString<0> PCM; 2837 if (!llvm::sys::path::is_absolute(Mod.getASTFile())) 2838 PCM = Mod.getPath(); 2839 llvm::sys::path::append(PCM, Mod.getASTFile()); 2840 DIB.createCompileUnit( 2841 TheCU->getSourceLanguage(), 2842 // TODO: Support "Source" from external AST providers? 2843 DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()), 2844 TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM), 2845 llvm::DICompileUnit::FullDebug, Signature); 2846 DIB.finalize(); 2847 } 2848 2849 llvm::DIModule *Parent = 2850 IsRootModule ? nullptr 2851 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent), 2852 CreateSkeletonCU); 2853 std::string IncludePath = Mod.getPath().str(); 2854 llvm::DIModule *DIMod = 2855 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros, 2856 RemapPath(IncludePath)); 2857 ModuleCache[M].reset(DIMod); 2858 return DIMod; 2859 } 2860 2861 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty, 2862 llvm::DIFile *Unit) { 2863 ObjCInterfaceDecl *ID = Ty->getDecl(); 2864 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation()); 2865 unsigned Line = getLineNumber(ID->getLocation()); 2866 unsigned RuntimeLang = TheCU->getSourceLanguage(); 2867 2868 // Bit size, align and offset of the type. 2869 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2870 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext()); 2871 2872 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 2873 if (ID->getImplementation()) 2874 Flags |= llvm::DINode::FlagObjcClassComplete; 2875 2876 llvm::DIScope *Mod = getParentModuleOrNull(ID); 2877 llvm::DICompositeType *RealDecl = DBuilder.createStructType( 2878 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags, 2879 nullptr, llvm::DINodeArray(), RuntimeLang); 2880 2881 QualType QTy(Ty, 0); 2882 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl); 2883 2884 // Push the struct on region stack. 2885 LexicalBlockStack.emplace_back(RealDecl); 2886 RegionMap[Ty->getDecl()].reset(RealDecl); 2887 2888 // Convert all the elements. 2889 SmallVector<llvm::Metadata *, 16> EltTys; 2890 2891 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 2892 if (SClass) { 2893 llvm::DIType *SClassTy = 2894 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 2895 if (!SClassTy) 2896 return nullptr; 2897 2898 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0, 2899 llvm::DINode::FlagZero); 2900 EltTys.push_back(InhTag); 2901 } 2902 2903 // Create entries for all of the properties. 2904 auto AddProperty = [&](const ObjCPropertyDecl *PD) { 2905 SourceLocation Loc = PD->getLocation(); 2906 llvm::DIFile *PUnit = getOrCreateFile(Loc); 2907 unsigned PLine = getLineNumber(Loc); 2908 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 2909 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 2910 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty( 2911 PD->getName(), PUnit, PLine, 2912 hasDefaultGetterName(PD, Getter) ? "" 2913 : getSelectorName(PD->getGetterName()), 2914 hasDefaultSetterName(PD, Setter) ? "" 2915 : getSelectorName(PD->getSetterName()), 2916 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit)); 2917 EltTys.push_back(PropertyNode); 2918 }; 2919 { 2920 // Use 'char' for the isClassProperty bit as DenseSet requires space for 2921 // empty/tombstone keys in the data type (and bool is too small for that). 2922 typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent; 2923 /// List of already emitted properties. Two distinct class and instance 2924 /// properties can share the same identifier (but not two instance 2925 /// properties or two class properties). 2926 llvm::DenseSet<IsClassAndIdent> PropertySet; 2927 /// Returns the IsClassAndIdent key for the given property. 2928 auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) { 2929 return std::make_pair(PD->isClassProperty(), PD->getIdentifier()); 2930 }; 2931 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions()) 2932 for (auto *PD : ClassExt->properties()) { 2933 PropertySet.insert(GetIsClassAndIdent(PD)); 2934 AddProperty(PD); 2935 } 2936 for (const auto *PD : ID->properties()) { 2937 // Don't emit duplicate metadata for properties that were already in a 2938 // class extension. 2939 if (!PropertySet.insert(GetIsClassAndIdent(PD)).second) 2940 continue; 2941 AddProperty(PD); 2942 } 2943 } 2944 2945 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 2946 unsigned FieldNo = 0; 2947 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 2948 Field = Field->getNextIvar(), ++FieldNo) { 2949 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 2950 if (!FieldTy) 2951 return nullptr; 2952 2953 StringRef FieldName = Field->getName(); 2954 2955 // Ignore unnamed fields. 2956 if (FieldName.empty()) 2957 continue; 2958 2959 // Get the location for the field. 2960 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation()); 2961 unsigned FieldLine = getLineNumber(Field->getLocation()); 2962 QualType FType = Field->getType(); 2963 uint64_t FieldSize = 0; 2964 uint32_t FieldAlign = 0; 2965 2966 if (!FType->isIncompleteArrayType()) { 2967 2968 // Bit size, align and offset of the type. 2969 FieldSize = Field->isBitField() 2970 ? Field->getBitWidthValue(CGM.getContext()) 2971 : CGM.getContext().getTypeSize(FType); 2972 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext()); 2973 } 2974 2975 uint64_t FieldOffset; 2976 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 2977 // We don't know the runtime offset of an ivar if we're using the 2978 // non-fragile ABI. For bitfields, use the bit offset into the first 2979 // byte of storage of the bitfield. For other fields, use zero. 2980 if (Field->isBitField()) { 2981 FieldOffset = 2982 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field); 2983 FieldOffset %= CGM.getContext().getCharWidth(); 2984 } else { 2985 FieldOffset = 0; 2986 } 2987 } else { 2988 FieldOffset = RL.getFieldOffset(FieldNo); 2989 } 2990 2991 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 2992 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 2993 Flags = llvm::DINode::FlagProtected; 2994 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 2995 Flags = llvm::DINode::FlagPrivate; 2996 else if (Field->getAccessControl() == ObjCIvarDecl::Public) 2997 Flags = llvm::DINode::FlagPublic; 2998 2999 llvm::MDNode *PropertyNode = nullptr; 3000 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { 3001 if (ObjCPropertyImplDecl *PImpD = 3002 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) { 3003 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { 3004 SourceLocation Loc = PD->getLocation(); 3005 llvm::DIFile *PUnit = getOrCreateFile(Loc); 3006 unsigned PLine = getLineNumber(Loc); 3007 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl(); 3008 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl(); 3009 PropertyNode = DBuilder.createObjCProperty( 3010 PD->getName(), PUnit, PLine, 3011 hasDefaultGetterName(PD, Getter) 3012 ? "" 3013 : getSelectorName(PD->getGetterName()), 3014 hasDefaultSetterName(PD, Setter) 3015 ? "" 3016 : getSelectorName(PD->getSetterName()), 3017 PD->getPropertyAttributes(), 3018 getOrCreateType(PD->getType(), PUnit)); 3019 } 3020 } 3021 } 3022 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine, 3023 FieldSize, FieldAlign, FieldOffset, Flags, 3024 FieldTy, PropertyNode); 3025 EltTys.push_back(FieldTy); 3026 } 3027 3028 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 3029 DBuilder.replaceArrays(RealDecl, Elements); 3030 3031 LexicalBlockStack.pop_back(); 3032 return RealDecl; 3033 } 3034 3035 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty, 3036 llvm::DIFile *Unit) { 3037 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit); 3038 int64_t Count = Ty->getNumElements(); 3039 3040 llvm::Metadata *Subscript; 3041 QualType QTy(Ty, 0); 3042 auto SizeExpr = SizeExprCache.find(QTy); 3043 if (SizeExpr != SizeExprCache.end()) 3044 Subscript = DBuilder.getOrCreateSubrange( 3045 SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/, 3046 nullptr /*upperBound*/, nullptr /*stride*/); 3047 else { 3048 auto *CountNode = 3049 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned( 3050 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1)); 3051 Subscript = DBuilder.getOrCreateSubrange( 3052 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/, 3053 nullptr /*stride*/); 3054 } 3055 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript); 3056 3057 uint64_t Size = CGM.getContext().getTypeSize(Ty); 3058 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext()); 3059 3060 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 3061 } 3062 3063 llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty, 3064 llvm::DIFile *Unit) { 3065 // FIXME: Create another debug type for matrices 3066 // For the time being, it treats it like a nested ArrayType. 3067 3068 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit); 3069 uint64_t Size = CGM.getContext().getTypeSize(Ty); 3070 uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext()); 3071 3072 // Create ranges for both dimensions. 3073 llvm::SmallVector<llvm::Metadata *, 2> Subscripts; 3074 auto *ColumnCountNode = 3075 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned( 3076 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns())); 3077 auto *RowCountNode = 3078 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned( 3079 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows())); 3080 Subscripts.push_back(DBuilder.getOrCreateSubrange( 3081 ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/, 3082 nullptr /*stride*/)); 3083 Subscripts.push_back(DBuilder.getOrCreateSubrange( 3084 RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/, 3085 nullptr /*stride*/)); 3086 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 3087 return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray); 3088 } 3089 3090 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) { 3091 uint64_t Size; 3092 uint32_t Align; 3093 3094 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 3095 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) { 3096 Size = 0; 3097 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT), 3098 CGM.getContext()); 3099 } else if (Ty->isIncompleteArrayType()) { 3100 Size = 0; 3101 if (Ty->getElementType()->isIncompleteType()) 3102 Align = 0; 3103 else 3104 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext()); 3105 } else if (Ty->isIncompleteType()) { 3106 Size = 0; 3107 Align = 0; 3108 } else { 3109 // Size and align of the whole array, not the element type. 3110 Size = CGM.getContext().getTypeSize(Ty); 3111 Align = getTypeAlignIfRequired(Ty, CGM.getContext()); 3112 } 3113 3114 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 3115 // interior arrays, do we care? Why aren't nested arrays represented the 3116 // obvious/recursive way? 3117 SmallVector<llvm::Metadata *, 8> Subscripts; 3118 QualType EltTy(Ty, 0); 3119 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 3120 // If the number of elements is known, then count is that number. Otherwise, 3121 // it's -1. This allows us to represent a subrange with an array of 0 3122 // elements, like this: 3123 // 3124 // struct foo { 3125 // int x[0]; 3126 // }; 3127 int64_t Count = -1; // Count == -1 is an unbounded array. 3128 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty)) 3129 Count = CAT->getSize().getZExtValue(); 3130 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) { 3131 if (Expr *Size = VAT->getSizeExpr()) { 3132 Expr::EvalResult Result; 3133 if (Size->EvaluateAsInt(Result, CGM.getContext())) 3134 Count = Result.Val.getInt().getExtValue(); 3135 } 3136 } 3137 3138 auto SizeNode = SizeExprCache.find(EltTy); 3139 if (SizeNode != SizeExprCache.end()) 3140 Subscripts.push_back(DBuilder.getOrCreateSubrange( 3141 SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/, 3142 nullptr /*upperBound*/, nullptr /*stride*/)); 3143 else { 3144 auto *CountNode = 3145 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned( 3146 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count)); 3147 Subscripts.push_back(DBuilder.getOrCreateSubrange( 3148 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/, 3149 nullptr /*stride*/)); 3150 } 3151 EltTy = Ty->getElementType(); 3152 } 3153 3154 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 3155 3156 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit), 3157 SubscriptArray); 3158 } 3159 3160 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty, 3161 llvm::DIFile *Unit) { 3162 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty, 3163 Ty->getPointeeType(), Unit); 3164 } 3165 3166 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty, 3167 llvm::DIFile *Unit) { 3168 llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type; 3169 // DW_TAG_rvalue_reference_type was introduced in DWARF 4. 3170 if (CGM.getCodeGenOpts().DebugStrictDwarf && 3171 CGM.getCodeGenOpts().DwarfVersion < 4) 3172 Tag = llvm::dwarf::DW_TAG_reference_type; 3173 3174 return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit); 3175 } 3176 3177 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty, 3178 llvm::DIFile *U) { 3179 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3180 uint64_t Size = 0; 3181 3182 if (!Ty->isIncompleteType()) { 3183 Size = CGM.getContext().getTypeSize(Ty); 3184 3185 // Set the MS inheritance model. There is no flag for the unspecified model. 3186 if (CGM.getTarget().getCXXABI().isMicrosoft()) { 3187 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) { 3188 case MSInheritanceModel::Single: 3189 Flags |= llvm::DINode::FlagSingleInheritance; 3190 break; 3191 case MSInheritanceModel::Multiple: 3192 Flags |= llvm::DINode::FlagMultipleInheritance; 3193 break; 3194 case MSInheritanceModel::Virtual: 3195 Flags |= llvm::DINode::FlagVirtualInheritance; 3196 break; 3197 case MSInheritanceModel::Unspecified: 3198 break; 3199 } 3200 } 3201 } 3202 3203 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U); 3204 if (Ty->isMemberDataPointerType()) 3205 return DBuilder.createMemberPointerType( 3206 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0, 3207 Flags); 3208 3209 const FunctionProtoType *FPT = 3210 Ty->getPointeeType()->getAs<FunctionProtoType>(); 3211 return DBuilder.createMemberPointerType( 3212 getOrCreateInstanceMethodType( 3213 CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()), 3214 FPT, U, false), 3215 ClassType, Size, /*Align=*/0, Flags); 3216 } 3217 3218 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) { 3219 auto *FromTy = getOrCreateType(Ty->getValueType(), U); 3220 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy); 3221 } 3222 3223 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) { 3224 return getOrCreateType(Ty->getElementType(), U); 3225 } 3226 3227 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) { 3228 const EnumDecl *ED = Ty->getDecl(); 3229 3230 uint64_t Size = 0; 3231 uint32_t Align = 0; 3232 if (!ED->getTypeForDecl()->isIncompleteType()) { 3233 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 3234 Align = getDeclAlignIfRequired(ED, CGM.getContext()); 3235 } 3236 3237 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); 3238 3239 bool isImportedFromModule = 3240 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition(); 3241 3242 // If this is just a forward declaration, construct an appropriately 3243 // marked node and just return it. 3244 if (isImportedFromModule || !ED->getDefinition()) { 3245 // Note that it is possible for enums to be created as part of 3246 // their own declcontext. In this case a FwdDecl will be created 3247 // twice. This doesn't cause a problem because both FwdDecls are 3248 // entered into the ReplaceMap: finalize() will replace the first 3249 // FwdDecl with the second and then replace the second with 3250 // complete type. 3251 llvm::DIScope *EDContext = getDeclContextDescriptor(ED); 3252 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); 3253 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType( 3254 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0)); 3255 3256 unsigned Line = getLineNumber(ED->getLocation()); 3257 StringRef EDName = ED->getName(); 3258 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType( 3259 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line, 3260 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier); 3261 3262 ReplaceMap.emplace_back( 3263 std::piecewise_construct, std::make_tuple(Ty), 3264 std::make_tuple(static_cast<llvm::Metadata *>(RetTy))); 3265 return RetTy; 3266 } 3267 3268 return CreateTypeDefinition(Ty); 3269 } 3270 3271 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { 3272 const EnumDecl *ED = Ty->getDecl(); 3273 uint64_t Size = 0; 3274 uint32_t Align = 0; 3275 if (!ED->getTypeForDecl()->isIncompleteType()) { 3276 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 3277 Align = getDeclAlignIfRequired(ED, CGM.getContext()); 3278 } 3279 3280 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); 3281 3282 SmallVector<llvm::Metadata *, 16> Enumerators; 3283 ED = ED->getDefinition(); 3284 for (const auto *Enum : ED->enumerators()) { 3285 Enumerators.push_back( 3286 DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal())); 3287 } 3288 3289 // Return a CompositeType for the enum itself. 3290 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators); 3291 3292 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); 3293 unsigned Line = getLineNumber(ED->getLocation()); 3294 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED); 3295 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit); 3296 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, 3297 Line, Size, Align, EltArray, ClassTy, 3298 Identifier, ED->isScoped()); 3299 } 3300 3301 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent, 3302 unsigned MType, SourceLocation LineLoc, 3303 StringRef Name, StringRef Value) { 3304 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc); 3305 return DBuilder.createMacro(Parent, Line, MType, Name, Value); 3306 } 3307 3308 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent, 3309 SourceLocation LineLoc, 3310 SourceLocation FileLoc) { 3311 llvm::DIFile *FName = getOrCreateFile(FileLoc); 3312 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc); 3313 return DBuilder.createTempMacroFile(Parent, Line, FName); 3314 } 3315 3316 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { 3317 Qualifiers Quals; 3318 do { 3319 Qualifiers InnerQuals = T.getLocalQualifiers(); 3320 // Qualifiers::operator+() doesn't like it if you add a Qualifier 3321 // that is already there. 3322 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals); 3323 Quals += InnerQuals; 3324 QualType LastT = T; 3325 switch (T->getTypeClass()) { 3326 default: 3327 return C.getQualifiedType(T.getTypePtr(), Quals); 3328 case Type::TemplateSpecialization: { 3329 const auto *Spec = cast<TemplateSpecializationType>(T); 3330 if (Spec->isTypeAlias()) 3331 return C.getQualifiedType(T.getTypePtr(), Quals); 3332 T = Spec->desugar(); 3333 break; 3334 } 3335 case Type::TypeOfExpr: 3336 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 3337 break; 3338 case Type::TypeOf: 3339 T = cast<TypeOfType>(T)->getUnderlyingType(); 3340 break; 3341 case Type::Decltype: 3342 T = cast<DecltypeType>(T)->getUnderlyingType(); 3343 break; 3344 case Type::UnaryTransform: 3345 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 3346 break; 3347 case Type::Attributed: 3348 T = cast<AttributedType>(T)->getEquivalentType(); 3349 break; 3350 case Type::Elaborated: 3351 T = cast<ElaboratedType>(T)->getNamedType(); 3352 break; 3353 case Type::Paren: 3354 T = cast<ParenType>(T)->getInnerType(); 3355 break; 3356 case Type::MacroQualified: 3357 T = cast<MacroQualifiedType>(T)->getUnderlyingType(); 3358 break; 3359 case Type::SubstTemplateTypeParm: 3360 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 3361 break; 3362 case Type::Auto: 3363 case Type::DeducedTemplateSpecialization: { 3364 QualType DT = cast<DeducedType>(T)->getDeducedType(); 3365 assert(!DT.isNull() && "Undeduced types shouldn't reach here."); 3366 T = DT; 3367 break; 3368 } 3369 case Type::Adjusted: 3370 case Type::Decayed: 3371 // Decayed and adjusted types use the adjusted type in LLVM and DWARF. 3372 T = cast<AdjustedType>(T)->getAdjustedType(); 3373 break; 3374 } 3375 3376 assert(T != LastT && "Type unwrapping failed to unwrap!"); 3377 (void)LastT; 3378 } while (true); 3379 } 3380 3381 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) { 3382 assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext())); 3383 auto It = TypeCache.find(Ty.getAsOpaquePtr()); 3384 if (It != TypeCache.end()) { 3385 // Verify that the debug info still exists. 3386 if (llvm::Metadata *V = It->second) 3387 return cast<llvm::DIType>(V); 3388 } 3389 3390 return nullptr; 3391 } 3392 3393 void CGDebugInfo::completeTemplateDefinition( 3394 const ClassTemplateSpecializationDecl &SD) { 3395 completeUnusedClass(SD); 3396 } 3397 3398 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) { 3399 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 3400 return; 3401 3402 completeClassData(&D); 3403 // In case this type has no member function definitions being emitted, ensure 3404 // it is retained 3405 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr()); 3406 } 3407 3408 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit, 3409 TypeLoc TL) { 3410 if (Ty.isNull()) 3411 return nullptr; 3412 3413 llvm::TimeTraceScope TimeScope("DebugType", [&]() { 3414 std::string Name; 3415 llvm::raw_string_ostream OS(Name); 3416 Ty.print(OS, getPrintingPolicy()); 3417 return Name; 3418 }); 3419 3420 // Unwrap the type as needed for debug information. 3421 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 3422 3423 if (auto *T = getTypeOrNull(Ty)) 3424 return T; 3425 3426 llvm::DIType *Res = CreateTypeNode(Ty, Unit, TL); 3427 void *TyPtr = Ty.getAsOpaquePtr(); 3428 3429 // And update the type cache. 3430 TypeCache[TyPtr].reset(Res); 3431 3432 return Res; 3433 } 3434 3435 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) { 3436 // A forward declaration inside a module header does not belong to the module. 3437 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition()) 3438 return nullptr; 3439 if (DebugTypeExtRefs && D->isFromASTFile()) { 3440 // Record a reference to an imported clang module or precompiled header. 3441 auto *Reader = CGM.getContext().getExternalSource(); 3442 auto Idx = D->getOwningModuleID(); 3443 auto Info = Reader->getSourceDescriptor(Idx); 3444 if (Info) 3445 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true); 3446 } else if (ClangModuleMap) { 3447 // We are building a clang module or a precompiled header. 3448 // 3449 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies 3450 // and it wouldn't be necessary to specify the parent scope 3451 // because the type is already unique by definition (it would look 3452 // like the output of -fno-standalone-debug). On the other hand, 3453 // the parent scope helps a consumer to quickly locate the object 3454 // file where the type's definition is located, so it might be 3455 // best to make this behavior a command line or debugger tuning 3456 // option. 3457 if (Module *M = D->getOwningModule()) { 3458 // This is a (sub-)module. 3459 auto Info = ASTSourceDescriptor(*M); 3460 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false); 3461 } else { 3462 // This the precompiled header being built. 3463 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false); 3464 } 3465 } 3466 3467 return nullptr; 3468 } 3469 3470 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit, 3471 TypeLoc TL) { 3472 // Handle qualifiers, which recursively handles what they refer to. 3473 if (Ty.hasLocalQualifiers()) 3474 return CreateQualifiedType(Ty, Unit, TL); 3475 3476 // Work out details of type. 3477 switch (Ty->getTypeClass()) { 3478 #define TYPE(Class, Base) 3479 #define ABSTRACT_TYPE(Class, Base) 3480 #define NON_CANONICAL_TYPE(Class, Base) 3481 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3482 #include "clang/AST/TypeNodes.inc" 3483 llvm_unreachable("Dependent types cannot show up in debug information"); 3484 3485 case Type::ExtVector: 3486 case Type::Vector: 3487 return CreateType(cast<VectorType>(Ty), Unit); 3488 case Type::ConstantMatrix: 3489 return CreateType(cast<ConstantMatrixType>(Ty), Unit); 3490 case Type::ObjCObjectPointer: 3491 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 3492 case Type::ObjCObject: 3493 return CreateType(cast<ObjCObjectType>(Ty), Unit); 3494 case Type::ObjCTypeParam: 3495 return CreateType(cast<ObjCTypeParamType>(Ty), Unit); 3496 case Type::ObjCInterface: 3497 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 3498 case Type::Builtin: 3499 return CreateType(cast<BuiltinType>(Ty)); 3500 case Type::Complex: 3501 return CreateType(cast<ComplexType>(Ty)); 3502 case Type::Pointer: 3503 return CreateType(cast<PointerType>(Ty), Unit, TL); 3504 case Type::BlockPointer: 3505 return CreateType(cast<BlockPointerType>(Ty), Unit); 3506 case Type::Typedef: 3507 return CreateType(cast<TypedefType>(Ty), Unit); 3508 case Type::Record: 3509 return CreateType(cast<RecordType>(Ty)); 3510 case Type::Enum: 3511 return CreateEnumType(cast<EnumType>(Ty)); 3512 case Type::FunctionProto: 3513 case Type::FunctionNoProto: 3514 return CreateType(cast<FunctionType>(Ty), Unit, TL); 3515 case Type::ConstantArray: 3516 case Type::VariableArray: 3517 case Type::IncompleteArray: 3518 return CreateType(cast<ArrayType>(Ty), Unit); 3519 3520 case Type::LValueReference: 3521 return CreateType(cast<LValueReferenceType>(Ty), Unit); 3522 case Type::RValueReference: 3523 return CreateType(cast<RValueReferenceType>(Ty), Unit); 3524 3525 case Type::MemberPointer: 3526 return CreateType(cast<MemberPointerType>(Ty), Unit); 3527 3528 case Type::Atomic: 3529 return CreateType(cast<AtomicType>(Ty), Unit); 3530 3531 case Type::ExtInt: 3532 return CreateType(cast<ExtIntType>(Ty)); 3533 case Type::Pipe: 3534 return CreateType(cast<PipeType>(Ty), Unit); 3535 3536 case Type::TemplateSpecialization: 3537 return CreateType(cast<TemplateSpecializationType>(Ty), Unit); 3538 3539 case Type::Auto: 3540 case Type::Attributed: 3541 case Type::Adjusted: 3542 case Type::Decayed: 3543 case Type::DeducedTemplateSpecialization: 3544 case Type::Elaborated: 3545 case Type::Paren: 3546 case Type::MacroQualified: 3547 case Type::SubstTemplateTypeParm: 3548 case Type::TypeOfExpr: 3549 case Type::TypeOf: 3550 case Type::Decltype: 3551 case Type::UnaryTransform: 3552 break; 3553 } 3554 3555 llvm_unreachable("type should have been unwrapped!"); 3556 } 3557 3558 llvm::DICompositeType * 3559 CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) { 3560 QualType QTy(Ty, 0); 3561 3562 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy)); 3563 3564 // We may have cached a forward decl when we could have created 3565 // a non-forward decl. Go ahead and create a non-forward decl 3566 // now. 3567 if (T && !T->isForwardDecl()) 3568 return T; 3569 3570 // Otherwise create the type. 3571 llvm::DICompositeType *Res = CreateLimitedType(Ty); 3572 3573 // Propagate members from the declaration to the definition 3574 // CreateType(const RecordType*) will overwrite this with the members in the 3575 // correct order if the full type is needed. 3576 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray()); 3577 3578 // And update the type cache. 3579 TypeCache[QTy.getAsOpaquePtr()].reset(Res); 3580 return Res; 3581 } 3582 3583 // TODO: Currently used for context chains when limiting debug info. 3584 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 3585 RecordDecl *RD = Ty->getDecl(); 3586 3587 // Get overall information about the record type for the debug info. 3588 StringRef RDName = getClassName(RD); 3589 const SourceLocation Loc = RD->getLocation(); 3590 llvm::DIFile *DefUnit = nullptr; 3591 unsigned Line = 0; 3592 if (Loc.isValid()) { 3593 DefUnit = getOrCreateFile(Loc); 3594 Line = getLineNumber(Loc); 3595 } 3596 3597 llvm::DIScope *RDContext = getDeclContextDescriptor(RD); 3598 3599 // If we ended up creating the type during the context chain construction, 3600 // just return that. 3601 auto *T = cast_or_null<llvm::DICompositeType>( 3602 getTypeOrNull(CGM.getContext().getRecordType(RD))); 3603 if (T && (!T->isForwardDecl() || !RD->getDefinition())) 3604 return T; 3605 3606 // If this is just a forward or incomplete declaration, construct an 3607 // appropriately marked node and just return it. 3608 const RecordDecl *D = RD->getDefinition(); 3609 if (!D || !D->isCompleteDefinition()) 3610 return getOrCreateRecordFwdDecl(Ty, RDContext); 3611 3612 uint64_t Size = CGM.getContext().getTypeSize(Ty); 3613 auto Align = getDeclAlignIfRequired(D, CGM.getContext()); 3614 3615 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); 3616 3617 // Explicitly record the calling convention and export symbols for C++ 3618 // records. 3619 auto Flags = llvm::DINode::FlagZero; 3620 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3621 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect) 3622 Flags |= llvm::DINode::FlagTypePassByReference; 3623 else 3624 Flags |= llvm::DINode::FlagTypePassByValue; 3625 3626 // Record if a C++ record is non-trivial type. 3627 if (!CXXRD->isTrivial()) 3628 Flags |= llvm::DINode::FlagNonTrivial; 3629 3630 // Record exports it symbols to the containing structure. 3631 if (CXXRD->isAnonymousStructOrUnion()) 3632 Flags |= llvm::DINode::FlagExportSymbols; 3633 } 3634 3635 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D); 3636 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType( 3637 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 3638 Flags, Identifier, Annotations); 3639 3640 // Elements of composite types usually have back to the type, creating 3641 // uniquing cycles. Distinct nodes are more efficient. 3642 switch (RealDecl->getTag()) { 3643 default: 3644 llvm_unreachable("invalid composite type tag"); 3645 3646 case llvm::dwarf::DW_TAG_array_type: 3647 case llvm::dwarf::DW_TAG_enumeration_type: 3648 // Array elements and most enumeration elements don't have back references, 3649 // so they don't tend to be involved in uniquing cycles and there is some 3650 // chance of merging them when linking together two modules. Only make 3651 // them distinct if they are ODR-uniqued. 3652 if (Identifier.empty()) 3653 break; 3654 LLVM_FALLTHROUGH; 3655 3656 case llvm::dwarf::DW_TAG_structure_type: 3657 case llvm::dwarf::DW_TAG_union_type: 3658 case llvm::dwarf::DW_TAG_class_type: 3659 // Immediately resolve to a distinct node. 3660 RealDecl = 3661 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl)); 3662 break; 3663 } 3664 3665 RegionMap[Ty->getDecl()].reset(RealDecl); 3666 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl); 3667 3668 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 3669 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(), 3670 CollectCXXTemplateParams(TSpecial, DefUnit)); 3671 return RealDecl; 3672 } 3673 3674 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD, 3675 llvm::DICompositeType *RealDecl) { 3676 // A class's primary base or the class itself contains the vtable. 3677 llvm::DICompositeType *ContainingType = nullptr; 3678 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 3679 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 3680 // Seek non-virtual primary base root. 3681 while (1) { 3682 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 3683 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 3684 if (PBT && !BRL.isPrimaryBaseVirtual()) 3685 PBase = PBT; 3686 else 3687 break; 3688 } 3689 ContainingType = cast<llvm::DICompositeType>( 3690 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), 3691 getOrCreateFile(RD->getLocation()))); 3692 } else if (RD->isDynamicClass()) 3693 ContainingType = RealDecl; 3694 3695 DBuilder.replaceVTableHolder(RealDecl, ContainingType); 3696 } 3697 3698 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType, 3699 StringRef Name, uint64_t *Offset) { 3700 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 3701 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 3702 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext()); 3703 llvm::DIType *Ty = 3704 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign, 3705 *Offset, llvm::DINode::FlagZero, FieldTy); 3706 *Offset += FieldSize; 3707 return Ty; 3708 } 3709 3710 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit, 3711 StringRef &Name, 3712 StringRef &LinkageName, 3713 llvm::DIScope *&FDContext, 3714 llvm::DINodeArray &TParamsArray, 3715 llvm::DINode::DIFlags &Flags) { 3716 const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl()); 3717 Name = getFunctionName(FD); 3718 // Use mangled name as linkage name for C/C++ functions. 3719 if (FD->getType()->getAs<FunctionProtoType>()) 3720 LinkageName = CGM.getMangledName(GD); 3721 if (FD->hasPrototype()) 3722 Flags |= llvm::DINode::FlagPrototyped; 3723 // No need to replicate the linkage name if it isn't different from the 3724 // subprogram name, no need to have it at all unless coverage is enabled or 3725 // debug is set to more than just line tables or extra debug info is needed. 3726 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs && 3727 !CGM.getCodeGenOpts().EmitGcovNotes && 3728 !CGM.getCodeGenOpts().DebugInfoForProfiling && 3729 !CGM.getCodeGenOpts().PseudoProbeForProfiling && 3730 DebugKind <= codegenoptions::DebugLineTablesOnly)) 3731 LinkageName = StringRef(); 3732 3733 // Emit the function scope in line tables only mode (if CodeView) to 3734 // differentiate between function names. 3735 if (CGM.getCodeGenOpts().hasReducedDebugInfo() || 3736 (DebugKind == codegenoptions::DebugLineTablesOnly && 3737 CGM.getCodeGenOpts().EmitCodeView)) { 3738 if (const NamespaceDecl *NSDecl = 3739 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 3740 FDContext = getOrCreateNamespace(NSDecl); 3741 else if (const RecordDecl *RDecl = 3742 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) { 3743 llvm::DIScope *Mod = getParentModuleOrNull(RDecl); 3744 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU); 3745 } 3746 } 3747 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) { 3748 // Check if it is a noreturn-marked function 3749 if (FD->isNoReturn()) 3750 Flags |= llvm::DINode::FlagNoReturn; 3751 // Collect template parameters. 3752 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 3753 } 3754 } 3755 3756 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit, 3757 unsigned &LineNo, QualType &T, 3758 StringRef &Name, StringRef &LinkageName, 3759 llvm::MDTuple *&TemplateParameters, 3760 llvm::DIScope *&VDContext) { 3761 Unit = getOrCreateFile(VD->getLocation()); 3762 LineNo = getLineNumber(VD->getLocation()); 3763 3764 setLocation(VD->getLocation()); 3765 3766 T = VD->getType(); 3767 if (T->isIncompleteArrayType()) { 3768 // CodeGen turns int[] into int[1] so we'll do the same here. 3769 llvm::APInt ConstVal(32, 1); 3770 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 3771 3772 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr, 3773 ArrayType::Normal, 0); 3774 } 3775 3776 Name = VD->getName(); 3777 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) && 3778 !isa<ObjCMethodDecl>(VD->getDeclContext())) 3779 LinkageName = CGM.getMangledName(VD); 3780 if (LinkageName == Name) 3781 LinkageName = StringRef(); 3782 3783 if (isa<VarTemplateSpecializationDecl>(VD)) { 3784 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit); 3785 TemplateParameters = parameterNodes.get(); 3786 } else { 3787 TemplateParameters = nullptr; 3788 } 3789 3790 // Since we emit declarations (DW_AT_members) for static members, place the 3791 // definition of those static members in the namespace they were declared in 3792 // in the source code (the lexical decl context). 3793 // FIXME: Generalize this for even non-member global variables where the 3794 // declaration and definition may have different lexical decl contexts, once 3795 // we have support for emitting declarations of (non-member) global variables. 3796 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext() 3797 : VD->getDeclContext(); 3798 // When a record type contains an in-line initialization of a static data 3799 // member, and the record type is marked as __declspec(dllexport), an implicit 3800 // definition of the member will be created in the record context. DWARF 3801 // doesn't seem to have a nice way to describe this in a form that consumers 3802 // are likely to understand, so fake the "normal" situation of a definition 3803 // outside the class by putting it in the global scope. 3804 if (DC->isRecord()) 3805 DC = CGM.getContext().getTranslationUnitDecl(); 3806 3807 llvm::DIScope *Mod = getParentModuleOrNull(VD); 3808 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU); 3809 } 3810 3811 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD, 3812 bool Stub) { 3813 llvm::DINodeArray TParamsArray; 3814 StringRef Name, LinkageName; 3815 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3816 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 3817 SourceLocation Loc = GD.getDecl()->getLocation(); 3818 llvm::DIFile *Unit = getOrCreateFile(Loc); 3819 llvm::DIScope *DContext = Unit; 3820 unsigned Line = getLineNumber(Loc); 3821 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray, 3822 Flags); 3823 auto *FD = cast<FunctionDecl>(GD.getDecl()); 3824 3825 // Build function type. 3826 SmallVector<QualType, 16> ArgTypes; 3827 for (const ParmVarDecl *Parm : FD->parameters()) 3828 ArgTypes.push_back(Parm->getType()); 3829 3830 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 3831 QualType FnType = CGM.getContext().getFunctionType( 3832 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC)); 3833 if (!FD->isExternallyVisible()) 3834 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; 3835 if (CGM.getLangOpts().Optimize) 3836 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 3837 3838 if (Stub) { 3839 Flags |= getCallSiteRelatedAttrs(); 3840 SPFlags |= llvm::DISubprogram::SPFlagDefinition; 3841 return DBuilder.createFunction( 3842 DContext, Name, LinkageName, Unit, Line, 3843 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags, 3844 TParamsArray.get(), getFunctionDeclaration(FD)); 3845 } 3846 3847 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl( 3848 DContext, Name, LinkageName, Unit, Line, 3849 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags, 3850 TParamsArray.get(), getFunctionDeclaration(FD)); 3851 const FunctionDecl *CanonDecl = FD->getCanonicalDecl(); 3852 FwdDeclReplaceMap.emplace_back(std::piecewise_construct, 3853 std::make_tuple(CanonDecl), 3854 std::make_tuple(SP)); 3855 return SP; 3856 } 3857 3858 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) { 3859 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false); 3860 } 3861 3862 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) { 3863 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true); 3864 } 3865 3866 llvm::DIGlobalVariable * 3867 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) { 3868 QualType T; 3869 StringRef Name, LinkageName; 3870 SourceLocation Loc = VD->getLocation(); 3871 llvm::DIFile *Unit = getOrCreateFile(Loc); 3872 llvm::DIScope *DContext = Unit; 3873 unsigned Line = getLineNumber(Loc); 3874 llvm::MDTuple *TemplateParameters = nullptr; 3875 3876 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters, 3877 DContext); 3878 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 3879 auto *GV = DBuilder.createTempGlobalVariableFwdDecl( 3880 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit), 3881 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align); 3882 FwdDeclReplaceMap.emplace_back( 3883 std::piecewise_construct, 3884 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())), 3885 std::make_tuple(static_cast<llvm::Metadata *>(GV))); 3886 return GV; 3887 } 3888 3889 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { 3890 // We only need a declaration (not a definition) of the type - so use whatever 3891 // we would otherwise do to get a type for a pointee. (forward declarations in 3892 // limited debug info, full definitions (if the type definition is available) 3893 // in unlimited debug info) 3894 if (const auto *TD = dyn_cast<TypeDecl>(D)) 3895 return getOrCreateType(CGM.getContext().getTypeDeclType(TD), 3896 getOrCreateFile(TD->getLocation())); 3897 auto I = DeclCache.find(D->getCanonicalDecl()); 3898 3899 if (I != DeclCache.end()) { 3900 auto N = I->second; 3901 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N)) 3902 return GVE->getVariable(); 3903 return dyn_cast_or_null<llvm::DINode>(N); 3904 } 3905 3906 // No definition for now. Emit a forward definition that might be 3907 // merged with a potential upcoming definition. 3908 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 3909 return getFunctionForwardDeclaration(FD); 3910 else if (const auto *VD = dyn_cast<VarDecl>(D)) 3911 return getGlobalVariableForwardDeclaration(VD); 3912 3913 return nullptr; 3914 } 3915 3916 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) { 3917 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly) 3918 return nullptr; 3919 3920 const auto *FD = dyn_cast<FunctionDecl>(D); 3921 if (!FD) 3922 return nullptr; 3923 3924 // Setup context. 3925 auto *S = getDeclContextDescriptor(D); 3926 3927 auto MI = SPCache.find(FD->getCanonicalDecl()); 3928 if (MI == SPCache.end()) { 3929 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) { 3930 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), 3931 cast<llvm::DICompositeType>(S)); 3932 } 3933 } 3934 if (MI != SPCache.end()) { 3935 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 3936 if (SP && !SP->isDefinition()) 3937 return SP; 3938 } 3939 3940 for (auto NextFD : FD->redecls()) { 3941 auto MI = SPCache.find(NextFD->getCanonicalDecl()); 3942 if (MI != SPCache.end()) { 3943 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 3944 if (SP && !SP->isDefinition()) 3945 return SP; 3946 } 3947 } 3948 return nullptr; 3949 } 3950 3951 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration( 3952 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo, 3953 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) { 3954 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly) 3955 return nullptr; 3956 3957 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 3958 if (!OMD) 3959 return nullptr; 3960 3961 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod()) 3962 return nullptr; 3963 3964 if (OMD->isDirectMethod()) 3965 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect; 3966 3967 // Starting with DWARF V5 method declarations are emitted as children of 3968 // the interface type. 3969 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext()); 3970 if (!ID) 3971 ID = OMD->getClassInterface(); 3972 if (!ID) 3973 return nullptr; 3974 QualType QTy(ID->getTypeForDecl(), 0); 3975 auto It = TypeCache.find(QTy.getAsOpaquePtr()); 3976 if (It == TypeCache.end()) 3977 return nullptr; 3978 auto *InterfaceType = cast<llvm::DICompositeType>(It->second); 3979 llvm::DISubprogram *FD = DBuilder.createFunction( 3980 InterfaceType, getObjCMethodName(OMD), StringRef(), 3981 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags); 3982 DBuilder.finalizeSubprogram(FD); 3983 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()}); 3984 return FD; 3985 } 3986 3987 // getOrCreateFunctionType - Construct type. If it is a c++ method, include 3988 // implicit parameter "this". 3989 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D, 3990 QualType FnType, 3991 llvm::DIFile *F) { 3992 // In CodeView, we emit the function types in line tables only because the 3993 // only way to distinguish between functions is by display name and type. 3994 if (!D || (DebugKind <= codegenoptions::DebugLineTablesOnly && 3995 !CGM.getCodeGenOpts().EmitCodeView)) 3996 // Create fake but valid subroutine type. Otherwise -verify would fail, and 3997 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields. 3998 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None)); 3999 4000 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) 4001 return getOrCreateMethodType(Method, F, false); 4002 4003 const auto *FTy = FnType->getAs<FunctionType>(); 4004 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C; 4005 4006 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 4007 // Add "self" and "_cmd" 4008 SmallVector<llvm::Metadata *, 16> Elts; 4009 4010 // First element is always return type. For 'void' functions it is NULL. 4011 QualType ResultTy = OMethod->getReturnType(); 4012 4013 // Replace the instancetype keyword with the actual type. 4014 if (ResultTy == CGM.getContext().getObjCInstanceType()) 4015 ResultTy = CGM.getContext().getPointerType( 4016 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); 4017 4018 Elts.push_back(getOrCreateType(ResultTy, F)); 4019 // "self" pointer is always first argument. 4020 QualType SelfDeclTy; 4021 if (auto *SelfDecl = OMethod->getSelfDecl()) 4022 SelfDeclTy = SelfDecl->getType(); 4023 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType)) 4024 if (FPT->getNumParams() > 1) 4025 SelfDeclTy = FPT->getParamType(0); 4026 if (!SelfDeclTy.isNull()) 4027 Elts.push_back( 4028 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F))); 4029 // "_cmd" pointer is always second argument. 4030 Elts.push_back(DBuilder.createArtificialType( 4031 getOrCreateType(CGM.getContext().getObjCSelType(), F))); 4032 // Get rest of the arguments. 4033 for (const auto *PI : OMethod->parameters()) 4034 Elts.push_back(getOrCreateType(PI->getType(), F)); 4035 // Variadic methods need a special marker at the end of the type list. 4036 if (OMethod->isVariadic()) 4037 Elts.push_back(DBuilder.createUnspecifiedParameter()); 4038 4039 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 4040 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero, 4041 getDwarfCC(CC)); 4042 } 4043 4044 // Handle variadic function types; they need an additional 4045 // unspecified parameter. 4046 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 4047 if (FD->isVariadic()) { 4048 SmallVector<llvm::Metadata *, 16> EltTys; 4049 EltTys.push_back(getOrCreateType(FD->getReturnType(), F)); 4050 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType)) 4051 for (QualType ParamType : FPT->param_types()) 4052 EltTys.push_back(getOrCreateType(ParamType, F)); 4053 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 4054 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 4055 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero, 4056 getDwarfCC(CC)); 4057 } 4058 4059 TypeLoc TL; 4060 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 4061 if (const TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4062 TL = TSI->getTypeLoc(); 4063 } 4064 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F, TL)); 4065 } 4066 4067 QualType 4068 CGDebugInfo::getFunctionType(const FunctionDecl *FD, QualType RetTy, 4069 const SmallVectorImpl<const VarDecl *> &Args) { 4070 CallingConv CC = CallingConv::CC_C; 4071 if (FD) 4072 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>()) 4073 CC = SrcFnTy->getCallConv(); 4074 SmallVector<QualType, 16> ArgTypes; 4075 for (const VarDecl *VD : Args) 4076 ArgTypes.push_back(VD->getType()); 4077 return CGM.getContext().getFunctionType(RetTy, ArgTypes, 4078 FunctionProtoType::ExtProtoInfo(CC)); 4079 } 4080 4081 void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc, 4082 SourceLocation ScopeLoc, QualType FnType, 4083 llvm::Function *Fn, bool CurFuncIsThunk) { 4084 StringRef Name; 4085 StringRef LinkageName; 4086 4087 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 4088 4089 const Decl *D = GD.getDecl(); 4090 bool HasDecl = (D != nullptr); 4091 4092 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 4093 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 4094 llvm::DIFile *Unit = getOrCreateFile(Loc); 4095 llvm::DIScope *FDContext = Unit; 4096 llvm::DINodeArray TParamsArray; 4097 if (!HasDecl) { 4098 // Use llvm function name. 4099 LinkageName = Fn->getName(); 4100 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 4101 // If there is a subprogram for this function available then use it. 4102 auto FI = SPCache.find(FD->getCanonicalDecl()); 4103 if (FI != SPCache.end()) { 4104 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second); 4105 if (SP && SP->isDefinition()) { 4106 LexicalBlockStack.emplace_back(SP); 4107 RegionMap[D].reset(SP); 4108 return; 4109 } 4110 } 4111 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 4112 TParamsArray, Flags); 4113 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) { 4114 Name = getObjCMethodName(OMD); 4115 Flags |= llvm::DINode::FlagPrototyped; 4116 } else if (isa<VarDecl>(D) && 4117 GD.getDynamicInitKind() != DynamicInitKind::NoStub) { 4118 // This is a global initializer or atexit destructor for a global variable. 4119 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(), 4120 Fn); 4121 } else { 4122 Name = Fn->getName(); 4123 4124 if (isa<BlockDecl>(D)) 4125 LinkageName = Name; 4126 4127 Flags |= llvm::DINode::FlagPrototyped; 4128 } 4129 if (Name.startswith("\01")) 4130 Name = Name.substr(1); 4131 4132 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() || 4133 (isa<VarDecl>(D) && GD.getDynamicInitKind() != DynamicInitKind::NoStub)) { 4134 Flags |= llvm::DINode::FlagArtificial; 4135 // Artificial functions should not silently reuse CurLoc. 4136 CurLoc = SourceLocation(); 4137 } 4138 4139 if (CurFuncIsThunk) 4140 Flags |= llvm::DINode::FlagThunk; 4141 4142 if (Fn->hasLocalLinkage()) 4143 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; 4144 if (CGM.getLangOpts().Optimize) 4145 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 4146 4147 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs(); 4148 llvm::DISubprogram::DISPFlags SPFlagsForDef = 4149 SPFlags | llvm::DISubprogram::SPFlagDefinition; 4150 4151 const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc); 4152 unsigned ScopeLine = getLineNumber(ScopeLoc); 4153 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit); 4154 llvm::DISubprogram *Decl = nullptr; 4155 llvm::DINodeArray Annotations = nullptr; 4156 if (D) { 4157 Decl = isa<ObjCMethodDecl>(D) 4158 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags) 4159 : getFunctionDeclaration(D); 4160 Annotations = CollectBTFDeclTagAnnotations(D); 4161 } 4162 4163 // FIXME: The function declaration we're constructing here is mostly reusing 4164 // declarations from CXXMethodDecl and not constructing new ones for arbitrary 4165 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for 4166 // all subprograms instead of the actual context since subprogram definitions 4167 // are emitted as CU level entities by the backend. 4168 llvm::DISubprogram *SP = DBuilder.createFunction( 4169 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine, 4170 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr, 4171 Annotations); 4172 Fn->setSubprogram(SP); 4173 // We might get here with a VarDecl in the case we're generating 4174 // code for the initialization of globals. Do not record these decls 4175 // as they will overwrite the actual VarDecl Decl in the cache. 4176 if (HasDecl && isa<FunctionDecl>(D)) 4177 DeclCache[D->getCanonicalDecl()].reset(SP); 4178 4179 // Push the function onto the lexical block stack. 4180 LexicalBlockStack.emplace_back(SP); 4181 4182 if (HasDecl) 4183 RegionMap[D].reset(SP); 4184 } 4185 4186 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, 4187 QualType FnType, llvm::Function *Fn) { 4188 StringRef Name; 4189 StringRef LinkageName; 4190 4191 const Decl *D = GD.getDecl(); 4192 if (!D) 4193 return; 4194 4195 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() { 4196 return GetName(D, true); 4197 }); 4198 4199 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 4200 llvm::DIFile *Unit = getOrCreateFile(Loc); 4201 bool IsDeclForCallSite = Fn ? true : false; 4202 llvm::DIScope *FDContext = 4203 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D); 4204 llvm::DINodeArray TParamsArray; 4205 if (isa<FunctionDecl>(D)) { 4206 // If there is a DISubprogram for this function available then use it. 4207 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 4208 TParamsArray, Flags); 4209 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) { 4210 Name = getObjCMethodName(OMD); 4211 Flags |= llvm::DINode::FlagPrototyped; 4212 } else { 4213 llvm_unreachable("not a function or ObjC method"); 4214 } 4215 if (!Name.empty() && Name[0] == '\01') 4216 Name = Name.substr(1); 4217 4218 if (D->isImplicit()) { 4219 Flags |= llvm::DINode::FlagArtificial; 4220 // Artificial functions without a location should not silently reuse CurLoc. 4221 if (Loc.isInvalid()) 4222 CurLoc = SourceLocation(); 4223 } 4224 unsigned LineNo = getLineNumber(Loc); 4225 unsigned ScopeLine = 0; 4226 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; 4227 if (CGM.getLangOpts().Optimize) 4228 SPFlags |= llvm::DISubprogram::SPFlagOptimized; 4229 4230 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D); 4231 llvm::DISubprogram *SP = DBuilder.createFunction( 4232 FDContext, Name, LinkageName, Unit, LineNo, 4233 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags, 4234 TParamsArray.get(), getFunctionDeclaration(D), nullptr, Annotations); 4235 4236 if (IsDeclForCallSite) 4237 Fn->setSubprogram(SP); 4238 4239 DBuilder.finalizeSubprogram(SP); 4240 } 4241 4242 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke, 4243 QualType CalleeType, 4244 const FunctionDecl *CalleeDecl) { 4245 if (!CallOrInvoke) 4246 return; 4247 auto *Func = CallOrInvoke->getCalledFunction(); 4248 if (!Func) 4249 return; 4250 if (Func->getSubprogram()) 4251 return; 4252 4253 // Do not emit a declaration subprogram for a builtin, a function with nodebug 4254 // attribute, or if call site info isn't required. Also, elide declarations 4255 // for functions with reserved names, as call site-related features aren't 4256 // interesting in this case (& also, the compiler may emit calls to these 4257 // functions without debug locations, which makes the verifier complain). 4258 if (CalleeDecl->getBuiltinID() != 0 || CalleeDecl->hasAttr<NoDebugAttr>() || 4259 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero) 4260 return; 4261 if (CalleeDecl->isReserved(CGM.getLangOpts()) != 4262 ReservedIdentifierStatus::NotReserved) 4263 return; 4264 4265 // If there is no DISubprogram attached to the function being called, 4266 // create the one describing the function in order to have complete 4267 // call site debug info. 4268 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined()) 4269 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func); 4270 } 4271 4272 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) { 4273 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4274 // If there is a subprogram for this function available then use it. 4275 auto FI = SPCache.find(FD->getCanonicalDecl()); 4276 llvm::DISubprogram *SP = nullptr; 4277 if (FI != SPCache.end()) 4278 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second); 4279 if (!SP || !SP->isDefinition()) 4280 SP = getFunctionStub(GD); 4281 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 4282 LexicalBlockStack.emplace_back(SP); 4283 setInlinedAt(Builder.getCurrentDebugLocation()); 4284 EmitLocation(Builder, FD->getLocation()); 4285 } 4286 4287 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) { 4288 assert(CurInlinedAt && "unbalanced inline scope stack"); 4289 EmitFunctionEnd(Builder, nullptr); 4290 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt()); 4291 } 4292 4293 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) { 4294 // Update our current location 4295 setLocation(Loc); 4296 4297 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty()) 4298 return; 4299 4300 llvm::MDNode *Scope = LexicalBlockStack.back(); 4301 Builder.SetCurrentDebugLocation( 4302 llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc), 4303 getColumnNumber(CurLoc), Scope, CurInlinedAt)); 4304 } 4305 4306 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 4307 llvm::MDNode *Back = nullptr; 4308 if (!LexicalBlockStack.empty()) 4309 Back = LexicalBlockStack.back().get(); 4310 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock( 4311 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc), 4312 getColumnNumber(CurLoc))); 4313 } 4314 4315 void CGDebugInfo::AppendAddressSpaceXDeref( 4316 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const { 4317 Optional<unsigned> DWARFAddressSpace = 4318 CGM.getTarget().getDWARFAddressSpace(AddressSpace); 4319 if (!DWARFAddressSpace) 4320 return; 4321 4322 Expr.push_back(llvm::dwarf::DW_OP_constu); 4323 Expr.push_back(DWARFAddressSpace.getValue()); 4324 Expr.push_back(llvm::dwarf::DW_OP_swap); 4325 Expr.push_back(llvm::dwarf::DW_OP_xderef); 4326 } 4327 4328 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, 4329 SourceLocation Loc) { 4330 // Set our current location. 4331 setLocation(Loc); 4332 4333 // Emit a line table change for the current location inside the new scope. 4334 Builder.SetCurrentDebugLocation(llvm::DILocation::get( 4335 CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc), 4336 LexicalBlockStack.back(), CurInlinedAt)); 4337 4338 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 4339 return; 4340 4341 // Create a new lexical block and push it on the stack. 4342 CreateLexicalBlock(Loc); 4343 } 4344 4345 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, 4346 SourceLocation Loc) { 4347 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 4348 4349 // Provide an entry in the line table for the end of the block. 4350 EmitLocation(Builder, Loc); 4351 4352 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 4353 return; 4354 4355 LexicalBlockStack.pop_back(); 4356 } 4357 4358 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) { 4359 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 4360 unsigned RCount = FnBeginRegionCount.back(); 4361 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 4362 4363 // Pop all regions for this function. 4364 while (LexicalBlockStack.size() != RCount) { 4365 // Provide an entry in the line table for the end of the block. 4366 EmitLocation(Builder, CurLoc); 4367 LexicalBlockStack.pop_back(); 4368 } 4369 FnBeginRegionCount.pop_back(); 4370 4371 if (Fn && Fn->getSubprogram()) 4372 DBuilder.finalizeSubprogram(Fn->getSubprogram()); 4373 } 4374 4375 CGDebugInfo::BlockByRefType 4376 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 4377 uint64_t *XOffset) { 4378 SmallVector<llvm::Metadata *, 5> EltTys; 4379 QualType FType; 4380 uint64_t FieldSize, FieldOffset; 4381 uint32_t FieldAlign; 4382 4383 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 4384 QualType Type = VD->getType(); 4385 4386 FieldOffset = 0; 4387 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 4388 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 4389 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 4390 FType = CGM.getContext().IntTy; 4391 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 4392 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 4393 4394 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 4395 if (HasCopyAndDispose) { 4396 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 4397 EltTys.push_back( 4398 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset)); 4399 EltTys.push_back( 4400 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset)); 4401 } 4402 bool HasByrefExtendedLayout; 4403 Qualifiers::ObjCLifetime Lifetime; 4404 if (CGM.getContext().getByrefLifetime(Type, Lifetime, 4405 HasByrefExtendedLayout) && 4406 HasByrefExtendedLayout) { 4407 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 4408 EltTys.push_back( 4409 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset)); 4410 } 4411 4412 CharUnits Align = CGM.getContext().getDeclAlign(VD); 4413 if (Align > CGM.getContext().toCharUnitsFromBits( 4414 CGM.getTarget().getPointerAlign(0))) { 4415 CharUnits FieldOffsetInBytes = 4416 CGM.getContext().toCharUnitsFromBits(FieldOffset); 4417 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align); 4418 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes; 4419 4420 if (NumPaddingBytes.isPositive()) { 4421 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 4422 FType = CGM.getContext().getConstantArrayType( 4423 CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0); 4424 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 4425 } 4426 } 4427 4428 FType = Type; 4429 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit); 4430 FieldSize = CGM.getContext().getTypeSize(FType); 4431 FieldAlign = CGM.getContext().toBits(Align); 4432 4433 *XOffset = FieldOffset; 4434 llvm::DIType *FieldTy = DBuilder.createMemberType( 4435 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset, 4436 llvm::DINode::FlagZero, WrappedTy); 4437 EltTys.push_back(FieldTy); 4438 FieldOffset += FieldSize; 4439 4440 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 4441 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, 4442 llvm::DINode::FlagZero, nullptr, Elements), 4443 WrappedTy}; 4444 } 4445 4446 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD, 4447 llvm::Value *Storage, 4448 llvm::Optional<unsigned> ArgNo, 4449 CGBuilderTy &Builder, 4450 const bool UsePointerValue) { 4451 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 4452 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 4453 if (VD->hasAttr<NoDebugAttr>()) 4454 return nullptr; 4455 4456 bool Unwritten = 4457 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) && 4458 cast<Decl>(VD->getDeclContext())->isImplicit()); 4459 llvm::DIFile *Unit = nullptr; 4460 if (!Unwritten) 4461 Unit = getOrCreateFile(VD->getLocation()); 4462 llvm::DIType *Ty; 4463 uint64_t XOffset = 0; 4464 if (VD->hasAttr<BlocksAttr>()) 4465 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType; 4466 else { 4467 TypeLoc TL; 4468 if (const TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4469 TL = TSI->getTypeLoc(); 4470 Ty = getOrCreateType(VD->getType(), Unit, TL); 4471 } 4472 4473 // If there is no debug info for this type then do not emit debug info 4474 // for this variable. 4475 if (!Ty) 4476 return nullptr; 4477 4478 // Get location information. 4479 unsigned Line = 0; 4480 unsigned Column = 0; 4481 if (!Unwritten) { 4482 Line = getLineNumber(VD->getLocation()); 4483 Column = getColumnNumber(VD->getLocation()); 4484 } 4485 SmallVector<int64_t, 13> Expr; 4486 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 4487 if (VD->isImplicit()) 4488 Flags |= llvm::DINode::FlagArtificial; 4489 4490 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 4491 4492 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType()); 4493 AppendAddressSpaceXDeref(AddressSpace, Expr); 4494 4495 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an 4496 // object pointer flag. 4497 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) { 4498 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis || 4499 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf) 4500 Flags |= llvm::DINode::FlagObjectPointer; 4501 } 4502 4503 // Note: Older versions of clang used to emit byval references with an extra 4504 // DW_OP_deref, because they referenced the IR arg directly instead of 4505 // referencing an alloca. Newer versions of LLVM don't treat allocas 4506 // differently from other function arguments when used in a dbg.declare. 4507 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back()); 4508 StringRef Name = VD->getName(); 4509 if (!Name.empty()) { 4510 // __block vars are stored on the heap if they are captured by a block that 4511 // can escape the local scope. 4512 if (VD->isEscapingByref()) { 4513 // Here, we need an offset *into* the alloca. 4514 CharUnits offset = CharUnits::fromQuantity(32); 4515 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst); 4516 // offset of __forwarding field 4517 offset = CGM.getContext().toCharUnitsFromBits( 4518 CGM.getTarget().getPointerWidth(0)); 4519 Expr.push_back(offset.getQuantity()); 4520 Expr.push_back(llvm::dwarf::DW_OP_deref); 4521 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst); 4522 // offset of x field 4523 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 4524 Expr.push_back(offset.getQuantity()); 4525 } 4526 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) { 4527 // If VD is an anonymous union then Storage represents value for 4528 // all union fields. 4529 const RecordDecl *RD = RT->getDecl(); 4530 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 4531 // GDB has trouble finding local variables in anonymous unions, so we emit 4532 // artificial local variables for each of the members. 4533 // 4534 // FIXME: Remove this code as soon as GDB supports this. 4535 // The debug info verifier in LLVM operates based on the assumption that a 4536 // variable has the same size as its storage and we had to disable the 4537 // check for artificial variables. 4538 for (const auto *Field : RD->fields()) { 4539 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 4540 StringRef FieldName = Field->getName(); 4541 4542 // Ignore unnamed fields. Do not ignore unnamed records. 4543 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 4544 continue; 4545 4546 // Use VarDecl's Tag, Scope and Line number. 4547 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext()); 4548 auto *D = DBuilder.createAutoVariable( 4549 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize, 4550 Flags | llvm::DINode::FlagArtificial, FieldAlign); 4551 4552 // Insert an llvm.dbg.declare into the current block. 4553 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 4554 llvm::DILocation::get(CGM.getLLVMContext(), Line, 4555 Column, Scope, 4556 CurInlinedAt), 4557 Builder.GetInsertBlock()); 4558 } 4559 } 4560 } 4561 4562 // Clang stores the sret pointer provided by the caller in a static alloca. 4563 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as 4564 // the address of the variable. 4565 if (UsePointerValue) { 4566 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) && 4567 "Debug info already contains DW_OP_deref."); 4568 Expr.push_back(llvm::dwarf::DW_OP_deref); 4569 } 4570 4571 // Create the descriptor for the variable. 4572 llvm::DILocalVariable *D = nullptr; 4573 if (ArgNo) { 4574 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD); 4575 D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty, 4576 CGM.getLangOpts().Optimize, Flags, 4577 Annotations); 4578 } else { 4579 // For normal local variable, we will try to find out whether 'VD' is the 4580 // copy parameter of coroutine. 4581 // If yes, we are going to use DIVariable of the origin parameter instead 4582 // of creating the new one. 4583 // If no, it might be a normal alloc, we just create a new one for it. 4584 4585 // Check whether the VD is move parameters. 4586 auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * { 4587 // The scope of parameter and move-parameter should be distinct 4588 // DISubprogram. 4589 if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct()) 4590 return nullptr; 4591 4592 auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) { 4593 Stmt *StmtPtr = const_cast<Stmt *>(Pair.second); 4594 if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) { 4595 DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup(); 4596 Decl *Decl = DeclGroup.getSingleDecl(); 4597 if (VD == dyn_cast_or_null<VarDecl>(Decl)) 4598 return true; 4599 } 4600 return false; 4601 }); 4602 4603 if (Iter != CoroutineParameterMappings.end()) { 4604 ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first); 4605 auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) { 4606 return DbgPair.first == PD && DbgPair.second->getScope() == Scope; 4607 }); 4608 if (Iter2 != ParamDbgMappings.end()) 4609 return const_cast<llvm::DILocalVariable *>(Iter2->second); 4610 } 4611 return nullptr; 4612 }; 4613 4614 // If we couldn't find a move param DIVariable, create a new one. 4615 D = RemapCoroArgToLocalVar(); 4616 // Or we will create a new DIVariable for this Decl if D dose not exists. 4617 if (!D) 4618 D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty, 4619 CGM.getLangOpts().Optimize, Flags, Align); 4620 } 4621 // Insert an llvm.dbg.declare into the current block. 4622 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 4623 llvm::DILocation::get(CGM.getLLVMContext(), Line, 4624 Column, Scope, CurInlinedAt), 4625 Builder.GetInsertBlock()); 4626 4627 return D; 4628 } 4629 4630 llvm::DILocalVariable * 4631 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage, 4632 CGBuilderTy &Builder, 4633 const bool UsePointerValue) { 4634 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 4635 return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue); 4636 } 4637 4638 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) { 4639 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 4640 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 4641 4642 if (D->hasAttr<NoDebugAttr>()) 4643 return; 4644 4645 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back()); 4646 llvm::DIFile *Unit = getOrCreateFile(D->getLocation()); 4647 4648 // Get location information. 4649 unsigned Line = getLineNumber(D->getLocation()); 4650 unsigned Column = getColumnNumber(D->getLocation()); 4651 4652 StringRef Name = D->getName(); 4653 4654 // Create the descriptor for the label. 4655 auto *L = 4656 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize); 4657 4658 // Insert an llvm.dbg.label into the current block. 4659 DBuilder.insertLabel(L, 4660 llvm::DILocation::get(CGM.getLLVMContext(), Line, Column, 4661 Scope, CurInlinedAt), 4662 Builder.GetInsertBlock()); 4663 } 4664 4665 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy, 4666 llvm::DIType *Ty) { 4667 llvm::DIType *CachedTy = getTypeOrNull(QualTy); 4668 if (CachedTy) 4669 Ty = CachedTy; 4670 return DBuilder.createObjectPointerType(Ty); 4671 } 4672 4673 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 4674 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder, 4675 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) { 4676 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 4677 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 4678 4679 if (Builder.GetInsertBlock() == nullptr) 4680 return; 4681 if (VD->hasAttr<NoDebugAttr>()) 4682 return; 4683 4684 bool isByRef = VD->hasAttr<BlocksAttr>(); 4685 4686 uint64_t XOffset = 0; 4687 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 4688 llvm::DIType *Ty; 4689 if (isByRef) 4690 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType; 4691 else 4692 Ty = getOrCreateType(VD->getType(), Unit); 4693 4694 // Self is passed along as an implicit non-arg variable in a 4695 // block. Mark it as the object pointer. 4696 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) 4697 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf) 4698 Ty = CreateSelfType(VD->getType(), Ty); 4699 4700 // Get location information. 4701 const unsigned Line = 4702 getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc); 4703 unsigned Column = getColumnNumber(VD->getLocation()); 4704 4705 const llvm::DataLayout &target = CGM.getDataLayout(); 4706 4707 CharUnits offset = CharUnits::fromQuantity( 4708 target.getStructLayout(blockInfo.StructureType) 4709 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 4710 4711 SmallVector<int64_t, 9> addr; 4712 addr.push_back(llvm::dwarf::DW_OP_deref); 4713 addr.push_back(llvm::dwarf::DW_OP_plus_uconst); 4714 addr.push_back(offset.getQuantity()); 4715 if (isByRef) { 4716 addr.push_back(llvm::dwarf::DW_OP_deref); 4717 addr.push_back(llvm::dwarf::DW_OP_plus_uconst); 4718 // offset of __forwarding field 4719 offset = 4720 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0)); 4721 addr.push_back(offset.getQuantity()); 4722 addr.push_back(llvm::dwarf::DW_OP_deref); 4723 addr.push_back(llvm::dwarf::DW_OP_plus_uconst); 4724 // offset of x field 4725 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 4726 addr.push_back(offset.getQuantity()); 4727 } 4728 4729 // Create the descriptor for the variable. 4730 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 4731 auto *D = DBuilder.createAutoVariable( 4732 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit, 4733 Line, Ty, false, llvm::DINode::FlagZero, Align); 4734 4735 // Insert an llvm.dbg.declare into the current block. 4736 auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column, 4737 LexicalBlockStack.back(), CurInlinedAt); 4738 auto *Expr = DBuilder.createExpression(addr); 4739 if (InsertPoint) 4740 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint); 4741 else 4742 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock()); 4743 } 4744 4745 llvm::DILocalVariable * 4746 CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 4747 unsigned ArgNo, CGBuilderTy &Builder) { 4748 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 4749 return EmitDeclare(VD, AI, ArgNo, Builder); 4750 } 4751 4752 namespace { 4753 struct BlockLayoutChunk { 4754 uint64_t OffsetInBits; 4755 const BlockDecl::Capture *Capture; 4756 }; 4757 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 4758 return l.OffsetInBits < r.OffsetInBits; 4759 } 4760 } // namespace 4761 4762 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare( 4763 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc, 4764 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit, 4765 SmallVectorImpl<llvm::Metadata *> &Fields) { 4766 // Blocks in OpenCL have unique constraints which make the standard fields 4767 // redundant while requiring size and align fields for enqueue_kernel. See 4768 // initializeForBlockHeader in CGBlocks.cpp 4769 if (CGM.getLangOpts().OpenCL) { 4770 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public, 4771 BlockLayout.getElementOffsetInBits(0), 4772 Unit, Unit)); 4773 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public, 4774 BlockLayout.getElementOffsetInBits(1), 4775 Unit, Unit)); 4776 } else { 4777 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public, 4778 BlockLayout.getElementOffsetInBits(0), 4779 Unit, Unit)); 4780 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public, 4781 BlockLayout.getElementOffsetInBits(1), 4782 Unit, Unit)); 4783 Fields.push_back( 4784 createFieldType("__reserved", Context.IntTy, Loc, AS_public, 4785 BlockLayout.getElementOffsetInBits(2), Unit, Unit)); 4786 auto *FnTy = Block.getBlockExpr()->getFunctionType(); 4787 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); 4788 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public, 4789 BlockLayout.getElementOffsetInBits(3), 4790 Unit, Unit)); 4791 Fields.push_back(createFieldType( 4792 "__descriptor", 4793 Context.getPointerType(Block.NeedsCopyDispose 4794 ? Context.getBlockDescriptorExtendedType() 4795 : Context.getBlockDescriptorType()), 4796 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit)); 4797 } 4798 } 4799 4800 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 4801 StringRef Name, 4802 unsigned ArgNo, 4803 llvm::AllocaInst *Alloca, 4804 CGBuilderTy &Builder) { 4805 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 4806 ASTContext &C = CGM.getContext(); 4807 const BlockDecl *blockDecl = block.getBlockDecl(); 4808 4809 // Collect some general information about the block's location. 4810 SourceLocation loc = blockDecl->getCaretLocation(); 4811 llvm::DIFile *tunit = getOrCreateFile(loc); 4812 unsigned line = getLineNumber(loc); 4813 unsigned column = getColumnNumber(loc); 4814 4815 // Build the debug-info type for the block literal. 4816 getDeclContextDescriptor(blockDecl); 4817 4818 const llvm::StructLayout *blockLayout = 4819 CGM.getDataLayout().getStructLayout(block.StructureType); 4820 4821 SmallVector<llvm::Metadata *, 16> fields; 4822 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit, 4823 fields); 4824 4825 // We want to sort the captures by offset, not because DWARF 4826 // requires this, but because we're paranoid about debuggers. 4827 SmallVector<BlockLayoutChunk, 8> chunks; 4828 4829 // 'this' capture. 4830 if (blockDecl->capturesCXXThis()) { 4831 BlockLayoutChunk chunk; 4832 chunk.OffsetInBits = 4833 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 4834 chunk.Capture = nullptr; 4835 chunks.push_back(chunk); 4836 } 4837 4838 // Variable captures. 4839 for (const auto &capture : blockDecl->captures()) { 4840 const VarDecl *variable = capture.getVariable(); 4841 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 4842 4843 // Ignore constant captures. 4844 if (captureInfo.isConstant()) 4845 continue; 4846 4847 BlockLayoutChunk chunk; 4848 chunk.OffsetInBits = 4849 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 4850 chunk.Capture = &capture; 4851 chunks.push_back(chunk); 4852 } 4853 4854 // Sort by offset. 4855 llvm::array_pod_sort(chunks.begin(), chunks.end()); 4856 4857 for (const BlockLayoutChunk &Chunk : chunks) { 4858 uint64_t offsetInBits = Chunk.OffsetInBits; 4859 const BlockDecl::Capture *capture = Chunk.Capture; 4860 4861 // If we have a null capture, this must be the C++ 'this' capture. 4862 if (!capture) { 4863 QualType type; 4864 if (auto *Method = 4865 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext())) 4866 type = Method->getThisType(); 4867 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent())) 4868 type = QualType(RDecl->getTypeForDecl(), 0); 4869 else 4870 llvm_unreachable("unexpected block declcontext"); 4871 4872 fields.push_back(createFieldType("this", type, loc, AS_public, 4873 offsetInBits, tunit, tunit)); 4874 continue; 4875 } 4876 4877 const VarDecl *variable = capture->getVariable(); 4878 StringRef name = variable->getName(); 4879 4880 llvm::DIType *fieldType; 4881 if (capture->isByRef()) { 4882 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy); 4883 auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0; 4884 // FIXME: This recomputes the layout of the BlockByRefWrapper. 4885 uint64_t xoffset; 4886 fieldType = 4887 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper; 4888 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width); 4889 fieldType = DBuilder.createMemberType(tunit, name, tunit, line, 4890 PtrInfo.Width, Align, offsetInBits, 4891 llvm::DINode::FlagZero, fieldType); 4892 } else { 4893 auto Align = getDeclAlignIfRequired(variable, CGM.getContext()); 4894 fieldType = createFieldType(name, variable->getType(), loc, AS_public, 4895 offsetInBits, Align, tunit, tunit); 4896 } 4897 fields.push_back(fieldType); 4898 } 4899 4900 SmallString<36> typeName; 4901 llvm::raw_svector_ostream(typeName) 4902 << "__block_literal_" << CGM.getUniqueBlockCount(); 4903 4904 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields); 4905 4906 llvm::DIType *type = 4907 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 4908 CGM.getContext().toBits(block.BlockSize), 0, 4909 llvm::DINode::FlagZero, nullptr, fieldsArray); 4910 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 4911 4912 // Get overall information about the block. 4913 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial; 4914 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back()); 4915 4916 // Create the descriptor for the parameter. 4917 auto *debugVar = DBuilder.createParameterVariable( 4918 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags); 4919 4920 // Insert an llvm.dbg.declare into the current block. 4921 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(), 4922 llvm::DILocation::get(CGM.getLLVMContext(), line, 4923 column, scope, CurInlinedAt), 4924 Builder.GetInsertBlock()); 4925 } 4926 4927 llvm::DIDerivedType * 4928 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) { 4929 if (!D || !D->isStaticDataMember()) 4930 return nullptr; 4931 4932 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl()); 4933 if (MI != StaticDataMemberCache.end()) { 4934 assert(MI->second && "Static data member declaration should still exist"); 4935 return MI->second; 4936 } 4937 4938 // If the member wasn't found in the cache, lazily construct and add it to the 4939 // type (used when a limited form of the type is emitted). 4940 auto DC = D->getDeclContext(); 4941 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D)); 4942 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC)); 4943 } 4944 4945 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls( 4946 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo, 4947 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) { 4948 llvm::DIGlobalVariableExpression *GVE = nullptr; 4949 4950 for (const auto *Field : RD->fields()) { 4951 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 4952 StringRef FieldName = Field->getName(); 4953 4954 // Ignore unnamed fields, but recurse into anonymous records. 4955 if (FieldName.empty()) { 4956 if (const auto *RT = dyn_cast<RecordType>(Field->getType())) 4957 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName, 4958 Var, DContext); 4959 continue; 4960 } 4961 // Use VarDecl's Tag, Scope and Line number. 4962 GVE = DBuilder.createGlobalVariableExpression( 4963 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy, 4964 Var->hasLocalLinkage()); 4965 Var->addDebugInfo(GVE); 4966 } 4967 return GVE; 4968 } 4969 4970 namespace { 4971 struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> { 4972 bool Reconstitutable = true; 4973 bool VisitVectorType(VectorType *FT) { 4974 Reconstitutable = false; 4975 return false; 4976 } 4977 bool VisitAtomicType(AtomicType *FT) { 4978 Reconstitutable = false; 4979 return false; 4980 } 4981 bool TraverseEnumType(EnumType *ET) { 4982 // Unnamed enums can't be reconstituted due to a lack of column info we 4983 // produce in the DWARF, so we can't get Clang's full name back. 4984 if (const auto *ED = dyn_cast<EnumDecl>(ET->getDecl())) { 4985 if (!ED->getIdentifier()) { 4986 Reconstitutable = false; 4987 return false; 4988 } 4989 } 4990 return true; 4991 } 4992 bool VisitFunctionProtoType(FunctionProtoType *FT) { 4993 // noexcept is not encoded in DWARF, so the reversi 4994 Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType()); 4995 return Reconstitutable; 4996 } 4997 bool TraverseRecordType(RecordType *RT) { 4998 // Unnamed classes/lambdas can't be reconstituted due to a lack of column 4999 // info we produce in the DWARF, so we can't get Clang's full name back. 5000 // But so long as it's not one of those, it doesn't matter if some sub-type 5001 // of the record (a template parameter) can't be reconstituted - because the 5002 // un-reconstitutable type itself will carry its own name. 5003 const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 5004 if (!RD) 5005 return true; 5006 if (RD->isLambda() || !RD->getIdentifier()) { 5007 Reconstitutable = false; 5008 return false; 5009 } 5010 return true; 5011 } 5012 }; 5013 } // anonymous namespace 5014 5015 // Test whether a type name could be rebuilt from emitted debug info. 5016 static bool IsReconstitutableType(QualType QT) { 5017 ReconstitutableType T; 5018 T.TraverseType(QT); 5019 return T.Reconstitutable; 5020 } 5021 5022 std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const { 5023 std::string Name; 5024 llvm::raw_string_ostream OS(Name); 5025 const NamedDecl *ND = dyn_cast<NamedDecl>(D); 5026 if (!ND) 5027 return Name; 5028 codegenoptions::DebugTemplateNamesKind TemplateNamesKind = 5029 CGM.getCodeGenOpts().getDebugSimpleTemplateNames(); 5030 Optional<TemplateArgs> Args; 5031 5032 bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND); 5033 if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) { 5034 Args = GetTemplateArgs(RD); 5035 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) { 5036 Args = GetTemplateArgs(FD); 5037 auto NameKind = ND->getDeclName().getNameKind(); 5038 IsOperatorOverload |= 5039 NameKind == DeclarationName::CXXOperatorName || 5040 NameKind == DeclarationName::CXXConversionFunctionName; 5041 } else if (auto *VD = dyn_cast<VarDecl>(ND)) { 5042 Args = GetTemplateArgs(VD); 5043 } 5044 std::function<bool(ArrayRef<TemplateArgument>)> HasReconstitutableArgs = 5045 [&](ArrayRef<TemplateArgument> Args) { 5046 return llvm::all_of(Args, [&](const TemplateArgument &TA) { 5047 switch (TA.getKind()) { 5048 case TemplateArgument::Template: 5049 // Easy to reconstitute - the value of the parameter in the debug 5050 // info is the string name of the template. (so the template name 5051 // itself won't benefit from any name rebuilding, but that's a 5052 // representational limitation - maybe DWARF could be 5053 // changed/improved to use some more structural representation) 5054 return true; 5055 case TemplateArgument::Declaration: 5056 // Reference and pointer non-type template parameters point to 5057 // variables, functions, etc and their value is, at best (for 5058 // variables) represented as an address - not a reference to the 5059 // DWARF describing the variable/function/etc. This makes it hard, 5060 // possibly impossible to rebuild the original name - looking up the 5061 // address in the executable file's symbol table would be needed. 5062 return false; 5063 case TemplateArgument::NullPtr: 5064 // These could be rebuilt, but figured they're close enough to the 5065 // declaration case, and not worth rebuilding. 5066 return false; 5067 case TemplateArgument::Pack: 5068 // A pack is invalid if any of the elements of the pack are invalid. 5069 return HasReconstitutableArgs(TA.getPackAsArray()); 5070 case TemplateArgument::Integral: 5071 // Larger integers get encoded as DWARF blocks which are a bit 5072 // harder to parse back into a large integer, etc - so punting on 5073 // this for now. Re-parsing the integers back into APInt is probably 5074 // feasible some day. 5075 return TA.getAsIntegral().getBitWidth() <= 64; 5076 case TemplateArgument::Type: 5077 return IsReconstitutableType(TA.getAsType()); 5078 default: 5079 llvm_unreachable("Other, unresolved, template arguments should " 5080 "not be seen here"); 5081 } 5082 }); 5083 }; 5084 // A conversion operator presents complications/ambiguity if there's a 5085 // conversion to class template that is itself a template, eg: 5086 // template<typename T> 5087 // operator ns::t1<T, int>(); 5088 // This should be named, eg: "operator ns::t1<float, int><float>" 5089 // (ignoring clang bug that means this is currently "operator t1<float>") 5090 // but if the arguments were stripped, the consumer couldn't differentiate 5091 // whether the template argument list for the conversion type was the 5092 // function's argument list (& no reconstitution was needed) or not. 5093 // This could be handled if reconstitutable names had a separate attribute 5094 // annotating them as such - this would remove the ambiguity. 5095 // 5096 // Alternatively the template argument list could be parsed enough to check 5097 // whether there's one list or two, then compare that with the DWARF 5098 // description of the return type and the template argument lists to determine 5099 // how many lists there should be and if one is missing it could be assumed(?) 5100 // to be the function's template argument list & then be rebuilt. 5101 // 5102 // Other operator overloads that aren't conversion operators could be 5103 // reconstituted but would require a bit more nuance about detecting the 5104 // difference between these different operators during that rebuilding. 5105 bool Reconstitutable = 5106 Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload; 5107 5108 PrintingPolicy PP = getPrintingPolicy(); 5109 5110 if (TemplateNamesKind == codegenoptions::DebugTemplateNamesKind::Full || 5111 !Reconstitutable) { 5112 ND->getNameForDiagnostic(OS, PP, Qualified); 5113 } else { 5114 bool Mangled = 5115 TemplateNamesKind == codegenoptions::DebugTemplateNamesKind::Mangled; 5116 // check if it's a template 5117 if (Mangled) 5118 OS << "_STN"; 5119 5120 OS << ND->getDeclName(); 5121 std::string EncodedOriginalName; 5122 llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName); 5123 EncodedOriginalNameOS << ND->getDeclName(); 5124 5125 if (Mangled) { 5126 OS << "|"; 5127 printTemplateArgumentList(OS, Args->Args, PP); 5128 printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP); 5129 #ifndef NDEBUG 5130 std::string CanonicalOriginalName; 5131 llvm::raw_string_ostream OriginalOS(CanonicalOriginalName); 5132 ND->getNameForDiagnostic(OriginalOS, PP, Qualified); 5133 assert(EncodedOriginalNameOS.str() == OriginalOS.str()); 5134 #endif 5135 } 5136 } 5137 return Name; 5138 } 5139 5140 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 5141 const VarDecl *D) { 5142 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 5143 if (D->hasAttr<NoDebugAttr>()) 5144 return; 5145 5146 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() { 5147 return GetName(D, true); 5148 }); 5149 5150 // If we already created a DIGlobalVariable for this declaration, just attach 5151 // it to the llvm::GlobalVariable. 5152 auto Cached = DeclCache.find(D->getCanonicalDecl()); 5153 if (Cached != DeclCache.end()) 5154 return Var->addDebugInfo( 5155 cast<llvm::DIGlobalVariableExpression>(Cached->second)); 5156 5157 // Create global variable debug descriptor. 5158 llvm::DIFile *Unit = nullptr; 5159 llvm::DIScope *DContext = nullptr; 5160 unsigned LineNo; 5161 StringRef DeclName, LinkageName; 5162 QualType T; 5163 llvm::MDTuple *TemplateParameters = nullptr; 5164 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, 5165 TemplateParameters, DContext); 5166 5167 // Attempt to store one global variable for the declaration - even if we 5168 // emit a lot of fields. 5169 llvm::DIGlobalVariableExpression *GVE = nullptr; 5170 5171 // If this is an anonymous union then we'll want to emit a global 5172 // variable for each member of the anonymous union so that it's possible 5173 // to find the name of any field in the union. 5174 if (T->isUnionType() && DeclName.empty()) { 5175 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 5176 assert(RD->isAnonymousStructOrUnion() && 5177 "unnamed non-anonymous struct or union?"); 5178 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext); 5179 } else { 5180 auto Align = getDeclAlignIfRequired(D, CGM.getContext()); 5181 5182 SmallVector<int64_t, 4> Expr; 5183 unsigned AddressSpace = 5184 CGM.getContext().getTargetAddressSpace(D->getType()); 5185 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) { 5186 if (D->hasAttr<CUDASharedAttr>()) 5187 AddressSpace = 5188 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared); 5189 else if (D->hasAttr<CUDAConstantAttr>()) 5190 AddressSpace = 5191 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant); 5192 } 5193 AppendAddressSpaceXDeref(AddressSpace, Expr); 5194 5195 TypeLoc TL; 5196 if (const TypeSourceInfo *TSI = D->getTypeSourceInfo()) 5197 TL = TSI->getTypeLoc(); 5198 5199 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D); 5200 GVE = DBuilder.createGlobalVariableExpression( 5201 DContext, DeclName, LinkageName, Unit, LineNo, 5202 getOrCreateType(T, Unit, TL), Var->hasLocalLinkage(), true, 5203 Expr.empty() ? nullptr : DBuilder.createExpression(Expr), 5204 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters, 5205 Align, Annotations); 5206 Var->addDebugInfo(GVE); 5207 } 5208 DeclCache[D->getCanonicalDecl()].reset(GVE); 5209 } 5210 5211 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) { 5212 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 5213 if (VD->hasAttr<NoDebugAttr>()) 5214 return; 5215 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() { 5216 return GetName(VD, true); 5217 }); 5218 5219 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 5220 // Create the descriptor for the variable. 5221 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 5222 StringRef Name = VD->getName(); 5223 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit); 5224 5225 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) { 5226 const auto *ED = cast<EnumDecl>(ECD->getDeclContext()); 5227 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 5228 5229 if (CGM.getCodeGenOpts().EmitCodeView) { 5230 // If CodeView, emit enums as global variables, unless they are defined 5231 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for 5232 // enums in classes, and because it is difficult to attach this scope 5233 // information to the global variable. 5234 if (isa<RecordDecl>(ED->getDeclContext())) 5235 return; 5236 } else { 5237 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For 5238 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the 5239 // first time `ZERO` is referenced in a function. 5240 llvm::DIType *EDTy = 5241 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 5242 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type); 5243 (void)EDTy; 5244 return; 5245 } 5246 } 5247 5248 // Do not emit separate definitions for function local consts. 5249 if (isa<FunctionDecl>(VD->getDeclContext())) 5250 return; 5251 5252 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 5253 auto *VarD = dyn_cast<VarDecl>(VD); 5254 if (VarD && VarD->isStaticDataMember()) { 5255 auto *RD = cast<RecordDecl>(VarD->getDeclContext()); 5256 getDeclContextDescriptor(VarD); 5257 // Ensure that the type is retained even though it's otherwise unreferenced. 5258 // 5259 // FIXME: This is probably unnecessary, since Ty should reference RD 5260 // through its scope. 5261 RetainedTypes.push_back( 5262 CGM.getContext().getRecordType(RD).getAsOpaquePtr()); 5263 5264 return; 5265 } 5266 llvm::DIScope *DContext = getDeclContextDescriptor(VD); 5267 5268 auto &GV = DeclCache[VD]; 5269 if (GV) 5270 return; 5271 llvm::DIExpression *InitExpr = nullptr; 5272 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) { 5273 // FIXME: Add a representation for integer constants wider than 64 bits. 5274 if (Init.isInt()) 5275 InitExpr = 5276 DBuilder.createConstantValueExpression(Init.getInt().getExtValue()); 5277 else if (Init.isFloat()) 5278 InitExpr = DBuilder.createConstantValueExpression( 5279 Init.getFloat().bitcastToAPInt().getZExtValue()); 5280 } 5281 5282 llvm::MDTuple *TemplateParameters = nullptr; 5283 5284 if (isa<VarTemplateSpecializationDecl>(VD)) 5285 if (VarD) { 5286 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit); 5287 TemplateParameters = parameterNodes.get(); 5288 } 5289 5290 GV.reset(DBuilder.createGlobalVariableExpression( 5291 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty, 5292 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD), 5293 TemplateParameters, Align)); 5294 } 5295 5296 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var, 5297 const VarDecl *D) { 5298 assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); 5299 if (D->hasAttr<NoDebugAttr>()) 5300 return; 5301 5302 auto Align = getDeclAlignIfRequired(D, CGM.getContext()); 5303 llvm::DIFile *Unit = getOrCreateFile(D->getLocation()); 5304 StringRef Name = D->getName(); 5305 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit); 5306 5307 llvm::DIScope *DContext = getDeclContextDescriptor(D); 5308 llvm::DIGlobalVariableExpression *GVE = 5309 DBuilder.createGlobalVariableExpression( 5310 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()), 5311 Ty, false, false, nullptr, nullptr, nullptr, Align); 5312 Var->addDebugInfo(GVE); 5313 } 5314 5315 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { 5316 if (!LexicalBlockStack.empty()) 5317 return LexicalBlockStack.back(); 5318 llvm::DIScope *Mod = getParentModuleOrNull(D); 5319 return getContextDescriptor(D, Mod ? Mod : TheCU); 5320 } 5321 5322 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { 5323 if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) 5324 return; 5325 const NamespaceDecl *NSDecl = UD.getNominatedNamespace(); 5326 if (!NSDecl->isAnonymousNamespace() || 5327 CGM.getCodeGenOpts().DebugExplicitImport) { 5328 auto Loc = UD.getLocation(); 5329 if (!Loc.isValid()) 5330 Loc = CurLoc; 5331 DBuilder.createImportedModule( 5332 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())), 5333 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc)); 5334 } 5335 } 5336 5337 void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl &USD) { 5338 if (llvm::DINode *Target = 5339 getDeclarationOrDefinition(USD.getUnderlyingDecl())) { 5340 auto Loc = USD.getLocation(); 5341 DBuilder.createImportedDeclaration( 5342 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target, 5343 getOrCreateFile(Loc), getLineNumber(Loc)); 5344 } 5345 } 5346 5347 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { 5348 if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) 5349 return; 5350 assert(UD.shadow_size() && 5351 "We shouldn't be codegening an invalid UsingDecl containing no decls"); 5352 5353 for (const auto *USD : UD.shadows()) { 5354 // FIXME: Skip functions with undeduced auto return type for now since we 5355 // don't currently have the plumbing for separate declarations & definitions 5356 // of free functions and mismatched types (auto in the declaration, concrete 5357 // return type in the definition) 5358 if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl())) 5359 if (const auto *AT = FD->getType() 5360 ->castAs<FunctionProtoType>() 5361 ->getContainedAutoType()) 5362 if (AT->getDeducedType().isNull()) 5363 continue; 5364 5365 EmitUsingShadowDecl(*USD); 5366 // Emitting one decl is sufficient - debuggers can detect that this is an 5367 // overloaded name & provide lookup for all the overloads. 5368 break; 5369 } 5370 } 5371 5372 void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) { 5373 if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) 5374 return; 5375 assert(UD.shadow_size() && 5376 "We shouldn't be codegening an invalid UsingEnumDecl" 5377 " containing no decls"); 5378 5379 for (const auto *USD : UD.shadows()) 5380 EmitUsingShadowDecl(*USD); 5381 } 5382 5383 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) { 5384 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB) 5385 return; 5386 if (Module *M = ID.getImportedModule()) { 5387 auto Info = ASTSourceDescriptor(*M); 5388 auto Loc = ID.getLocation(); 5389 DBuilder.createImportedDeclaration( 5390 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())), 5391 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc), 5392 getLineNumber(Loc)); 5393 } 5394 } 5395 5396 llvm::DIImportedEntity * 5397 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { 5398 if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) 5399 return nullptr; 5400 auto &VH = NamespaceAliasCache[&NA]; 5401 if (VH) 5402 return cast<llvm::DIImportedEntity>(VH); 5403 llvm::DIImportedEntity *R; 5404 auto Loc = NA.getLocation(); 5405 if (const auto *Underlying = 5406 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace())) 5407 // This could cache & dedup here rather than relying on metadata deduping. 5408 R = DBuilder.createImportedDeclaration( 5409 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 5410 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc), 5411 getLineNumber(Loc), NA.getName()); 5412 else 5413 R = DBuilder.createImportedDeclaration( 5414 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 5415 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())), 5416 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName()); 5417 VH.reset(R); 5418 return R; 5419 } 5420 5421 llvm::DINamespace * 5422 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) { 5423 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued 5424 // if necessary, and this way multiple declarations of the same namespace in 5425 // different parent modules stay distinct. 5426 auto I = NamespaceCache.find(NSDecl); 5427 if (I != NamespaceCache.end()) 5428 return cast<llvm::DINamespace>(I->second); 5429 5430 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl); 5431 // Don't trust the context if it is a DIModule (see comment above). 5432 llvm::DINamespace *NS = 5433 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline()); 5434 NamespaceCache[NSDecl].reset(NS); 5435 return NS; 5436 } 5437 5438 void CGDebugInfo::setDwoId(uint64_t Signature) { 5439 assert(TheCU && "no main compile unit"); 5440 TheCU->setDWOId(Signature); 5441 } 5442 5443 void CGDebugInfo::finalize() { 5444 // Creating types might create further types - invalidating the current 5445 // element and the size(), so don't cache/reference them. 5446 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) { 5447 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i]; 5448 llvm::DIType *Ty = E.Type->getDecl()->getDefinition() 5449 ? CreateTypeDefinition(E.Type, E.Unit) 5450 : E.Decl; 5451 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty); 5452 } 5453 5454 // Add methods to interface. 5455 for (const auto &P : ObjCMethodCache) { 5456 if (P.second.empty()) 5457 continue; 5458 5459 QualType QTy(P.first->getTypeForDecl(), 0); 5460 auto It = TypeCache.find(QTy.getAsOpaquePtr()); 5461 assert(It != TypeCache.end()); 5462 5463 llvm::DICompositeType *InterfaceDecl = 5464 cast<llvm::DICompositeType>(It->second); 5465 5466 auto CurElts = InterfaceDecl->getElements(); 5467 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end()); 5468 5469 // For DWARF v4 or earlier, only add objc_direct methods. 5470 for (auto &SubprogramDirect : P.second) 5471 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt()) 5472 EltTys.push_back(SubprogramDirect.getPointer()); 5473 5474 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 5475 DBuilder.replaceArrays(InterfaceDecl, Elements); 5476 } 5477 5478 for (const auto &P : ReplaceMap) { 5479 assert(P.second); 5480 auto *Ty = cast<llvm::DIType>(P.second); 5481 assert(Ty->isForwardDecl()); 5482 5483 auto It = TypeCache.find(P.first); 5484 assert(It != TypeCache.end()); 5485 assert(It->second); 5486 5487 DBuilder.replaceTemporary(llvm::TempDIType(Ty), 5488 cast<llvm::DIType>(It->second)); 5489 } 5490 5491 for (const auto &P : FwdDeclReplaceMap) { 5492 assert(P.second); 5493 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second)); 5494 llvm::Metadata *Repl; 5495 5496 auto It = DeclCache.find(P.first); 5497 // If there has been no definition for the declaration, call RAUW 5498 // with ourselves, that will destroy the temporary MDNode and 5499 // replace it with a standard one, avoiding leaking memory. 5500 if (It == DeclCache.end()) 5501 Repl = P.second; 5502 else 5503 Repl = It->second; 5504 5505 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl)) 5506 Repl = GVE->getVariable(); 5507 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl)); 5508 } 5509 5510 // We keep our own list of retained types, because we need to look 5511 // up the final type in the type cache. 5512 for (auto &RT : RetainedTypes) 5513 if (auto MD = TypeCache[RT]) 5514 DBuilder.retainType(cast<llvm::DIType>(MD)); 5515 5516 DBuilder.finalize(); 5517 } 5518 5519 // Don't ignore in case of explicit cast where it is referenced indirectly. 5520 void CGDebugInfo::EmitExplicitCastType(QualType Ty) { 5521 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) 5522 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile())) 5523 DBuilder.retainType(DieTy); 5524 } 5525 5526 void CGDebugInfo::EmitAndRetainType(QualType Ty) { 5527 if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo()) 5528 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile())) 5529 DBuilder.retainType(DieTy); 5530 } 5531 5532 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) { 5533 if (LexicalBlockStack.empty()) 5534 return llvm::DebugLoc(); 5535 5536 llvm::MDNode *Scope = LexicalBlockStack.back(); 5537 return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc), 5538 getColumnNumber(Loc), Scope); 5539 } 5540 5541 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const { 5542 // Call site-related attributes are only useful in optimized programs, and 5543 // when there's a possibility of debugging backtraces. 5544 if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo || 5545 DebugKind == codegenoptions::LocTrackingOnly) 5546 return llvm::DINode::FlagZero; 5547 5548 // Call site-related attributes are available in DWARF v5. Some debuggers, 5549 // while not fully DWARF v5-compliant, may accept these attributes as if they 5550 // were part of DWARF v4. 5551 bool SupportsDWARFv4Ext = 5552 CGM.getCodeGenOpts().DwarfVersion == 4 && 5553 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB || 5554 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB); 5555 5556 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5) 5557 return llvm::DINode::FlagZero; 5558 5559 return llvm::DINode::FlagAllCallsDescribed; 5560 } 5561