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