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