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