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