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