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