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