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