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