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