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