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