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