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