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