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