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