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