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