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