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