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