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