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