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 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent, 2423 unsigned MType, SourceLocation LineLoc, 2424 StringRef Name, StringRef Value) { 2425 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc); 2426 return DBuilder.createMacro(Parent, Line, MType, Name, Value); 2427 } 2428 2429 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent, 2430 SourceLocation LineLoc, 2431 SourceLocation FileLoc) { 2432 llvm::DIFile *FName = getOrCreateFile(FileLoc); 2433 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc); 2434 return DBuilder.createTempMacroFile(Parent, Line, FName); 2435 } 2436 2437 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { 2438 Qualifiers Quals; 2439 do { 2440 Qualifiers InnerQuals = T.getLocalQualifiers(); 2441 // Qualifiers::operator+() doesn't like it if you add a Qualifier 2442 // that is already there. 2443 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals); 2444 Quals += InnerQuals; 2445 QualType LastT = T; 2446 switch (T->getTypeClass()) { 2447 default: 2448 return C.getQualifiedType(T.getTypePtr(), Quals); 2449 case Type::TemplateSpecialization: { 2450 const auto *Spec = cast<TemplateSpecializationType>(T); 2451 if (Spec->isTypeAlias()) 2452 return C.getQualifiedType(T.getTypePtr(), Quals); 2453 T = Spec->desugar(); 2454 break; 2455 } 2456 case Type::TypeOfExpr: 2457 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 2458 break; 2459 case Type::TypeOf: 2460 T = cast<TypeOfType>(T)->getUnderlyingType(); 2461 break; 2462 case Type::Decltype: 2463 T = cast<DecltypeType>(T)->getUnderlyingType(); 2464 break; 2465 case Type::UnaryTransform: 2466 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 2467 break; 2468 case Type::Attributed: 2469 T = cast<AttributedType>(T)->getEquivalentType(); 2470 break; 2471 case Type::Elaborated: 2472 T = cast<ElaboratedType>(T)->getNamedType(); 2473 break; 2474 case Type::Paren: 2475 T = cast<ParenType>(T)->getInnerType(); 2476 break; 2477 case Type::SubstTemplateTypeParm: 2478 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 2479 break; 2480 case Type::Auto: { 2481 QualType DT = cast<AutoType>(T)->getDeducedType(); 2482 assert(!DT.isNull() && "Undeduced types shouldn't reach here."); 2483 T = DT; 2484 break; 2485 } 2486 case Type::Adjusted: 2487 case Type::Decayed: 2488 // Decayed and adjusted types use the adjusted type in LLVM and DWARF. 2489 T = cast<AdjustedType>(T)->getAdjustedType(); 2490 break; 2491 } 2492 2493 assert(T != LastT && "Type unwrapping failed to unwrap!"); 2494 (void)LastT; 2495 } while (true); 2496 } 2497 2498 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) { 2499 2500 // Unwrap the type as needed for debug information. 2501 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2502 2503 auto it = TypeCache.find(Ty.getAsOpaquePtr()); 2504 if (it != TypeCache.end()) { 2505 // Verify that the debug info still exists. 2506 if (llvm::Metadata *V = it->second) 2507 return cast<llvm::DIType>(V); 2508 } 2509 2510 return nullptr; 2511 } 2512 2513 void CGDebugInfo::completeTemplateDefinition( 2514 const ClassTemplateSpecializationDecl &SD) { 2515 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 2516 return; 2517 2518 completeClassData(&SD); 2519 // In case this type has no member function definitions being emitted, ensure 2520 // it is retained 2521 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr()); 2522 } 2523 2524 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) { 2525 if (Ty.isNull()) 2526 return nullptr; 2527 2528 // Unwrap the type as needed for debug information. 2529 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2530 2531 if (auto *T = getTypeOrNull(Ty)) 2532 return T; 2533 2534 llvm::DIType *Res = CreateTypeNode(Ty, Unit); 2535 void* TyPtr = Ty.getAsOpaquePtr(); 2536 2537 // And update the type cache. 2538 TypeCache[TyPtr].reset(Res); 2539 2540 return Res; 2541 } 2542 2543 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) { 2544 // A forward declaration inside a module header does not belong to the module. 2545 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition()) 2546 return nullptr; 2547 if (DebugTypeExtRefs && D->isFromASTFile()) { 2548 // Record a reference to an imported clang module or precompiled header. 2549 auto *Reader = CGM.getContext().getExternalSource(); 2550 auto Idx = D->getOwningModuleID(); 2551 auto Info = Reader->getSourceDescriptor(Idx); 2552 if (Info) 2553 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true); 2554 } else if (ClangModuleMap) { 2555 // We are building a clang module or a precompiled header. 2556 // 2557 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies 2558 // and it wouldn't be necessary to specify the parent scope 2559 // because the type is already unique by definition (it would look 2560 // like the output of -fno-standalone-debug). On the other hand, 2561 // the parent scope helps a consumer to quickly locate the object 2562 // file where the type's definition is located, so it might be 2563 // best to make this behavior a command line or debugger tuning 2564 // option. 2565 FullSourceLoc Loc(D->getLocation(), CGM.getContext().getSourceManager()); 2566 if (Module *M = ClangModuleMap->inferModuleFromLocation(Loc)) { 2567 // This is a (sub-)module. 2568 auto Info = ExternalASTSource::ASTSourceDescriptor(*M); 2569 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false); 2570 } else { 2571 // This the precompiled header being built. 2572 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false); 2573 } 2574 } 2575 2576 return nullptr; 2577 } 2578 2579 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) { 2580 // Handle qualifiers, which recursively handles what they refer to. 2581 if (Ty.hasLocalQualifiers()) 2582 return CreateQualifiedType(Ty, Unit); 2583 2584 // Work out details of type. 2585 switch (Ty->getTypeClass()) { 2586 #define TYPE(Class, Base) 2587 #define ABSTRACT_TYPE(Class, Base) 2588 #define NON_CANONICAL_TYPE(Class, Base) 2589 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2590 #include "clang/AST/TypeNodes.def" 2591 llvm_unreachable("Dependent types cannot show up in debug information"); 2592 2593 case Type::ExtVector: 2594 case Type::Vector: 2595 return CreateType(cast<VectorType>(Ty), Unit); 2596 case Type::ObjCObjectPointer: 2597 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 2598 case Type::ObjCObject: 2599 return CreateType(cast<ObjCObjectType>(Ty), Unit); 2600 case Type::ObjCTypeParam: 2601 return CreateType(cast<ObjCTypeParamType>(Ty), Unit); 2602 case Type::ObjCInterface: 2603 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 2604 case Type::Builtin: 2605 return CreateType(cast<BuiltinType>(Ty)); 2606 case Type::Complex: 2607 return CreateType(cast<ComplexType>(Ty)); 2608 case Type::Pointer: 2609 return CreateType(cast<PointerType>(Ty), Unit); 2610 case Type::BlockPointer: 2611 return CreateType(cast<BlockPointerType>(Ty), Unit); 2612 case Type::Typedef: 2613 return CreateType(cast<TypedefType>(Ty), Unit); 2614 case Type::Record: 2615 return CreateType(cast<RecordType>(Ty)); 2616 case Type::Enum: 2617 return CreateEnumType(cast<EnumType>(Ty)); 2618 case Type::FunctionProto: 2619 case Type::FunctionNoProto: 2620 return CreateType(cast<FunctionType>(Ty), Unit); 2621 case Type::ConstantArray: 2622 case Type::VariableArray: 2623 case Type::IncompleteArray: 2624 return CreateType(cast<ArrayType>(Ty), Unit); 2625 2626 case Type::LValueReference: 2627 return CreateType(cast<LValueReferenceType>(Ty), Unit); 2628 case Type::RValueReference: 2629 return CreateType(cast<RValueReferenceType>(Ty), Unit); 2630 2631 case Type::MemberPointer: 2632 return CreateType(cast<MemberPointerType>(Ty), Unit); 2633 2634 case Type::Atomic: 2635 return CreateType(cast<AtomicType>(Ty), Unit); 2636 2637 case Type::Pipe: 2638 return CreateType(cast<PipeType>(Ty), Unit); 2639 2640 case Type::TemplateSpecialization: 2641 return CreateType(cast<TemplateSpecializationType>(Ty), Unit); 2642 2643 case Type::Auto: 2644 case Type::Attributed: 2645 case Type::Adjusted: 2646 case Type::Decayed: 2647 case Type::DeducedTemplateSpecialization: 2648 case Type::Elaborated: 2649 case Type::Paren: 2650 case Type::SubstTemplateTypeParm: 2651 case Type::TypeOfExpr: 2652 case Type::TypeOf: 2653 case Type::Decltype: 2654 case Type::UnaryTransform: 2655 case Type::PackExpansion: 2656 break; 2657 } 2658 2659 llvm_unreachable("type should have been unwrapped!"); 2660 } 2661 2662 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty, 2663 llvm::DIFile *Unit) { 2664 QualType QTy(Ty, 0); 2665 2666 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy)); 2667 2668 // We may have cached a forward decl when we could have created 2669 // a non-forward decl. Go ahead and create a non-forward decl 2670 // now. 2671 if (T && !T->isForwardDecl()) 2672 return T; 2673 2674 // Otherwise create the type. 2675 llvm::DICompositeType *Res = CreateLimitedType(Ty); 2676 2677 // Propagate members from the declaration to the definition 2678 // CreateType(const RecordType*) will overwrite this with the members in the 2679 // correct order if the full type is needed. 2680 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray()); 2681 2682 // And update the type cache. 2683 TypeCache[QTy.getAsOpaquePtr()].reset(Res); 2684 return Res; 2685 } 2686 2687 // TODO: Currently used for context chains when limiting debug info. 2688 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 2689 RecordDecl *RD = Ty->getDecl(); 2690 2691 // Get overall information about the record type for the debug info. 2692 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 2693 unsigned Line = getLineNumber(RD->getLocation()); 2694 StringRef RDName = getClassName(RD); 2695 2696 llvm::DIScope *RDContext = getDeclContextDescriptor(RD); 2697 2698 // If we ended up creating the type during the context chain construction, 2699 // just return that. 2700 auto *T = cast_or_null<llvm::DICompositeType>( 2701 getTypeOrNull(CGM.getContext().getRecordType(RD))); 2702 if (T && (!T->isForwardDecl() || !RD->getDefinition())) 2703 return T; 2704 2705 // If this is just a forward or incomplete declaration, construct an 2706 // appropriately marked node and just return it. 2707 const RecordDecl *D = RD->getDefinition(); 2708 if (!D || !D->isCompleteDefinition()) 2709 return getOrCreateRecordFwdDecl(Ty, RDContext); 2710 2711 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2712 auto Align = getDeclAlignIfRequired(D, CGM.getContext()); 2713 2714 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 2715 2716 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType( 2717 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 2718 llvm::DINode::FlagZero, FullName); 2719 2720 // Elements of composite types usually have back to the type, creating 2721 // uniquing cycles. Distinct nodes are more efficient. 2722 switch (RealDecl->getTag()) { 2723 default: 2724 llvm_unreachable("invalid composite type tag"); 2725 2726 case llvm::dwarf::DW_TAG_array_type: 2727 case llvm::dwarf::DW_TAG_enumeration_type: 2728 // Array elements and most enumeration elements don't have back references, 2729 // so they don't tend to be involved in uniquing cycles and there is some 2730 // chance of merging them when linking together two modules. Only make 2731 // them distinct if they are ODR-uniqued. 2732 if (FullName.empty()) 2733 break; 2734 2735 case llvm::dwarf::DW_TAG_structure_type: 2736 case llvm::dwarf::DW_TAG_union_type: 2737 case llvm::dwarf::DW_TAG_class_type: 2738 // Immediatley resolve to a distinct node. 2739 RealDecl = 2740 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl)); 2741 break; 2742 } 2743 2744 RegionMap[Ty->getDecl()].reset(RealDecl); 2745 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl); 2746 2747 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 2748 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(), 2749 CollectCXXTemplateParams(TSpecial, DefUnit)); 2750 return RealDecl; 2751 } 2752 2753 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD, 2754 llvm::DICompositeType *RealDecl) { 2755 // A class's primary base or the class itself contains the vtable. 2756 llvm::DICompositeType *ContainingType = nullptr; 2757 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 2758 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 2759 // Seek non-virtual primary base root. 2760 while (1) { 2761 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 2762 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 2763 if (PBT && !BRL.isPrimaryBaseVirtual()) 2764 PBase = PBT; 2765 else 2766 break; 2767 } 2768 ContainingType = cast<llvm::DICompositeType>( 2769 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), 2770 getOrCreateFile(RD->getLocation()))); 2771 } else if (RD->isDynamicClass()) 2772 ContainingType = RealDecl; 2773 2774 DBuilder.replaceVTableHolder(RealDecl, ContainingType); 2775 } 2776 2777 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType, 2778 StringRef Name, uint64_t *Offset) { 2779 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2780 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 2781 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext()); 2782 llvm::DIType *Ty = 2783 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign, 2784 *Offset, llvm::DINode::FlagZero, FieldTy); 2785 *Offset += FieldSize; 2786 return Ty; 2787 } 2788 2789 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit, 2790 StringRef &Name, 2791 StringRef &LinkageName, 2792 llvm::DIScope *&FDContext, 2793 llvm::DINodeArray &TParamsArray, 2794 llvm::DINode::DIFlags &Flags) { 2795 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2796 Name = getFunctionName(FD); 2797 // Use mangled name as linkage name for C/C++ functions. 2798 if (FD->hasPrototype()) { 2799 LinkageName = CGM.getMangledName(GD); 2800 Flags |= llvm::DINode::FlagPrototyped; 2801 } 2802 // No need to replicate the linkage name if it isn't different from the 2803 // subprogram name, no need to have it at all unless coverage is enabled or 2804 // debug is set to more than just line tables or extra debug info is needed. 2805 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs && 2806 !CGM.getCodeGenOpts().EmitGcovNotes && 2807 !CGM.getCodeGenOpts().DebugInfoForProfiling && 2808 DebugKind <= codegenoptions::DebugLineTablesOnly)) 2809 LinkageName = StringRef(); 2810 2811 if (DebugKind >= codegenoptions::LimitedDebugInfo) { 2812 if (const NamespaceDecl *NSDecl = 2813 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 2814 FDContext = getOrCreateNameSpace(NSDecl); 2815 else if (const RecordDecl *RDecl = 2816 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) { 2817 llvm::DIScope *Mod = getParentModuleOrNull(RDecl); 2818 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU); 2819 } 2820 // Check if it is a noreturn-marked function 2821 if (FD->isNoReturn()) 2822 Flags |= llvm::DINode::FlagNoReturn; 2823 // Collect template parameters. 2824 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 2825 } 2826 } 2827 2828 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit, 2829 unsigned &LineNo, QualType &T, 2830 StringRef &Name, StringRef &LinkageName, 2831 llvm::DIScope *&VDContext) { 2832 Unit = getOrCreateFile(VD->getLocation()); 2833 LineNo = getLineNumber(VD->getLocation()); 2834 2835 setLocation(VD->getLocation()); 2836 2837 T = VD->getType(); 2838 if (T->isIncompleteArrayType()) { 2839 // CodeGen turns int[] into int[1] so we'll do the same here. 2840 llvm::APInt ConstVal(32, 1); 2841 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2842 2843 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2844 ArrayType::Normal, 0); 2845 } 2846 2847 Name = VD->getName(); 2848 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) && 2849 !isa<ObjCMethodDecl>(VD->getDeclContext())) 2850 LinkageName = CGM.getMangledName(VD); 2851 if (LinkageName == Name) 2852 LinkageName = StringRef(); 2853 2854 // Since we emit declarations (DW_AT_members) for static members, place the 2855 // definition of those static members in the namespace they were declared in 2856 // in the source code (the lexical decl context). 2857 // FIXME: Generalize this for even non-member global variables where the 2858 // declaration and definition may have different lexical decl contexts, once 2859 // we have support for emitting declarations of (non-member) global variables. 2860 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext() 2861 : VD->getDeclContext(); 2862 // When a record type contains an in-line initialization of a static data 2863 // member, and the record type is marked as __declspec(dllexport), an implicit 2864 // definition of the member will be created in the record context. DWARF 2865 // doesn't seem to have a nice way to describe this in a form that consumers 2866 // are likely to understand, so fake the "normal" situation of a definition 2867 // outside the class by putting it in the global scope. 2868 if (DC->isRecord()) 2869 DC = CGM.getContext().getTranslationUnitDecl(); 2870 2871 llvm::DIScope *Mod = getParentModuleOrNull(VD); 2872 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU); 2873 } 2874 2875 llvm::DISubprogram * 2876 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) { 2877 llvm::DINodeArray TParamsArray; 2878 StringRef Name, LinkageName; 2879 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 2880 SourceLocation Loc = FD->getLocation(); 2881 llvm::DIFile *Unit = getOrCreateFile(Loc); 2882 llvm::DIScope *DContext = Unit; 2883 unsigned Line = getLineNumber(Loc); 2884 2885 collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext, 2886 TParamsArray, Flags); 2887 // Build function type. 2888 SmallVector<QualType, 16> ArgTypes; 2889 for (const ParmVarDecl *Parm: FD->parameters()) 2890 ArgTypes.push_back(Parm->getType()); 2891 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 2892 QualType FnType = CGM.getContext().getFunctionType( 2893 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC)); 2894 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl( 2895 DContext, Name, LinkageName, Unit, Line, 2896 getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(), 2897 /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize, 2898 TParamsArray.get(), getFunctionDeclaration(FD)); 2899 const auto *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl()); 2900 FwdDeclReplaceMap.emplace_back(std::piecewise_construct, 2901 std::make_tuple(CanonDecl), 2902 std::make_tuple(SP)); 2903 return SP; 2904 } 2905 2906 llvm::DIGlobalVariable * 2907 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) { 2908 QualType T; 2909 StringRef Name, LinkageName; 2910 SourceLocation Loc = VD->getLocation(); 2911 llvm::DIFile *Unit = getOrCreateFile(Loc); 2912 llvm::DIScope *DContext = Unit; 2913 unsigned Line = getLineNumber(Loc); 2914 2915 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext); 2916 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 2917 auto *GV = DBuilder.createTempGlobalVariableFwdDecl( 2918 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit), 2919 !VD->isExternallyVisible(), nullptr, Align); 2920 FwdDeclReplaceMap.emplace_back( 2921 std::piecewise_construct, 2922 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())), 2923 std::make_tuple(static_cast<llvm::Metadata *>(GV))); 2924 return GV; 2925 } 2926 2927 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { 2928 // We only need a declaration (not a definition) of the type - so use whatever 2929 // we would otherwise do to get a type for a pointee. (forward declarations in 2930 // limited debug info, full definitions (if the type definition is available) 2931 // in unlimited debug info) 2932 if (const auto *TD = dyn_cast<TypeDecl>(D)) 2933 return getOrCreateType(CGM.getContext().getTypeDeclType(TD), 2934 getOrCreateFile(TD->getLocation())); 2935 auto I = DeclCache.find(D->getCanonicalDecl()); 2936 2937 if (I != DeclCache.end()) { 2938 auto N = I->second; 2939 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N)) 2940 return GVE->getVariable(); 2941 return dyn_cast_or_null<llvm::DINode>(N); 2942 } 2943 2944 // No definition for now. Emit a forward definition that might be 2945 // merged with a potential upcoming definition. 2946 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 2947 return getFunctionForwardDeclaration(FD); 2948 else if (const auto *VD = dyn_cast<VarDecl>(D)) 2949 return getGlobalVariableForwardDeclaration(VD); 2950 2951 return nullptr; 2952 } 2953 2954 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) { 2955 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly) 2956 return nullptr; 2957 2958 const auto *FD = dyn_cast<FunctionDecl>(D); 2959 if (!FD) 2960 return nullptr; 2961 2962 // Setup context. 2963 auto *S = getDeclContextDescriptor(D); 2964 2965 auto MI = SPCache.find(FD->getCanonicalDecl()); 2966 if (MI == SPCache.end()) { 2967 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) { 2968 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), 2969 cast<llvm::DICompositeType>(S)); 2970 } 2971 } 2972 if (MI != SPCache.end()) { 2973 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 2974 if (SP && !SP->isDefinition()) 2975 return SP; 2976 } 2977 2978 for (auto NextFD : FD->redecls()) { 2979 auto MI = SPCache.find(NextFD->getCanonicalDecl()); 2980 if (MI != SPCache.end()) { 2981 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 2982 if (SP && !SP->isDefinition()) 2983 return SP; 2984 } 2985 } 2986 return nullptr; 2987 } 2988 2989 // getOrCreateFunctionType - Construct type. If it is a c++ method, include 2990 // implicit parameter "this". 2991 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D, 2992 QualType FnType, 2993 llvm::DIFile *F) { 2994 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly) 2995 // Create fake but valid subroutine type. Otherwise -verify would fail, and 2996 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields. 2997 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None)); 2998 2999 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) 3000 return getOrCreateMethodType(Method, F); 3001 3002 const auto *FTy = FnType->getAs<FunctionType>(); 3003 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C; 3004 3005 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 3006 // Add "self" and "_cmd" 3007 SmallVector<llvm::Metadata *, 16> Elts; 3008 3009 // First element is always return type. For 'void' functions it is NULL. 3010 QualType ResultTy = OMethod->getReturnType(); 3011 3012 // Replace the instancetype keyword with the actual type. 3013 if (ResultTy == CGM.getContext().getObjCInstanceType()) 3014 ResultTy = CGM.getContext().getPointerType( 3015 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); 3016 3017 Elts.push_back(getOrCreateType(ResultTy, F)); 3018 // "self" pointer is always first argument. 3019 QualType SelfDeclTy; 3020 if (auto *SelfDecl = OMethod->getSelfDecl()) 3021 SelfDeclTy = SelfDecl->getType(); 3022 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType)) 3023 if (FPT->getNumParams() > 1) 3024 SelfDeclTy = FPT->getParamType(0); 3025 if (!SelfDeclTy.isNull()) 3026 Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F))); 3027 // "_cmd" pointer is always second argument. 3028 Elts.push_back(DBuilder.createArtificialType( 3029 getOrCreateType(CGM.getContext().getObjCSelType(), F))); 3030 // Get rest of the arguments. 3031 for (const auto *PI : OMethod->parameters()) 3032 Elts.push_back(getOrCreateType(PI->getType(), F)); 3033 // Variadic methods need a special marker at the end of the type list. 3034 if (OMethod->isVariadic()) 3035 Elts.push_back(DBuilder.createUnspecifiedParameter()); 3036 3037 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 3038 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero, 3039 getDwarfCC(CC)); 3040 } 3041 3042 // Handle variadic function types; they need an additional 3043 // unspecified parameter. 3044 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 3045 if (FD->isVariadic()) { 3046 SmallVector<llvm::Metadata *, 16> EltTys; 3047 EltTys.push_back(getOrCreateType(FD->getReturnType(), F)); 3048 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType)) 3049 for (QualType ParamType : FPT->param_types()) 3050 EltTys.push_back(getOrCreateType(ParamType, F)); 3051 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 3052 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 3053 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero, 3054 getDwarfCC(CC)); 3055 } 3056 3057 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F)); 3058 } 3059 3060 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc, 3061 SourceLocation ScopeLoc, QualType FnType, 3062 llvm::Function *Fn, CGBuilderTy &Builder) { 3063 3064 StringRef Name; 3065 StringRef LinkageName; 3066 3067 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 3068 3069 const Decl *D = GD.getDecl(); 3070 bool HasDecl = (D != nullptr); 3071 3072 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3073 llvm::DIFile *Unit = getOrCreateFile(Loc); 3074 llvm::DIScope *FDContext = Unit; 3075 llvm::DINodeArray TParamsArray; 3076 if (!HasDecl) { 3077 // Use llvm function name. 3078 LinkageName = Fn->getName(); 3079 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3080 // If there is a subprogram for this function available then use it. 3081 auto FI = SPCache.find(FD->getCanonicalDecl()); 3082 if (FI != SPCache.end()) { 3083 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second); 3084 if (SP && SP->isDefinition()) { 3085 LexicalBlockStack.emplace_back(SP); 3086 RegionMap[D].reset(SP); 3087 return; 3088 } 3089 } 3090 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 3091 TParamsArray, Flags); 3092 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) { 3093 Name = getObjCMethodName(OMD); 3094 Flags |= llvm::DINode::FlagPrototyped; 3095 } else { 3096 // Use llvm function name. 3097 Name = Fn->getName(); 3098 Flags |= llvm::DINode::FlagPrototyped; 3099 } 3100 if (Name.startswith("\01")) 3101 Name = Name.substr(1); 3102 3103 if (!HasDecl || D->isImplicit()) { 3104 Flags |= llvm::DINode::FlagArtificial; 3105 // Artificial functions should not silently reuse CurLoc. 3106 CurLoc = SourceLocation(); 3107 } 3108 unsigned LineNo = getLineNumber(Loc); 3109 unsigned ScopeLine = getLineNumber(ScopeLoc); 3110 3111 // FIXME: The function declaration we're constructing here is mostly reusing 3112 // declarations from CXXMethodDecl and not constructing new ones for arbitrary 3113 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for 3114 // all subprograms instead of the actual context since subprogram definitions 3115 // are emitted as CU level entities by the backend. 3116 llvm::DISubprogram *SP = DBuilder.createFunction( 3117 FDContext, Name, LinkageName, Unit, LineNo, 3118 getOrCreateFunctionType(D, FnType, Unit), Fn->hasLocalLinkage(), 3119 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize, 3120 TParamsArray.get(), getFunctionDeclaration(D)); 3121 Fn->setSubprogram(SP); 3122 // We might get here with a VarDecl in the case we're generating 3123 // code for the initialization of globals. Do not record these decls 3124 // as they will overwrite the actual VarDecl Decl in the cache. 3125 if (HasDecl && isa<FunctionDecl>(D)) 3126 DeclCache[D->getCanonicalDecl()].reset(SP); 3127 3128 // Push the function onto the lexical block stack. 3129 LexicalBlockStack.emplace_back(SP); 3130 3131 if (HasDecl) 3132 RegionMap[D].reset(SP); 3133 } 3134 3135 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, 3136 QualType FnType) { 3137 StringRef Name; 3138 StringRef LinkageName; 3139 3140 const Decl *D = GD.getDecl(); 3141 if (!D) 3142 return; 3143 3144 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3145 llvm::DIFile *Unit = getOrCreateFile(Loc); 3146 llvm::DIScope *FDContext = getDeclContextDescriptor(D); 3147 llvm::DINodeArray TParamsArray; 3148 if (isa<FunctionDecl>(D)) { 3149 // If there is a DISubprogram for this function available then use it. 3150 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 3151 TParamsArray, Flags); 3152 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) { 3153 Name = getObjCMethodName(OMD); 3154 Flags |= llvm::DINode::FlagPrototyped; 3155 } else { 3156 llvm_unreachable("not a function or ObjC method"); 3157 } 3158 if (!Name.empty() && Name[0] == '\01') 3159 Name = Name.substr(1); 3160 3161 if (D->isImplicit()) { 3162 Flags |= llvm::DINode::FlagArtificial; 3163 // Artificial functions without a location should not silently reuse CurLoc. 3164 if (Loc.isInvalid()) 3165 CurLoc = SourceLocation(); 3166 } 3167 unsigned LineNo = getLineNumber(Loc); 3168 unsigned ScopeLine = 0; 3169 3170 DBuilder.retainType(DBuilder.createFunction( 3171 FDContext, Name, LinkageName, Unit, LineNo, 3172 getOrCreateFunctionType(D, FnType, Unit), false /*internalLinkage*/, 3173 false /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize, 3174 TParamsArray.get(), getFunctionDeclaration(D))); 3175 } 3176 3177 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) { 3178 // Update our current location 3179 setLocation(Loc); 3180 3181 if (CurLoc.isInvalid() || CurLoc.isMacroID()) 3182 return; 3183 3184 llvm::MDNode *Scope = LexicalBlockStack.back(); 3185 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 3186 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope)); 3187 } 3188 3189 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 3190 llvm::MDNode *Back = nullptr; 3191 if (!LexicalBlockStack.empty()) 3192 Back = LexicalBlockStack.back().get(); 3193 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock( 3194 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc), 3195 getColumnNumber(CurLoc))); 3196 } 3197 3198 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, 3199 SourceLocation Loc) { 3200 // Set our current location. 3201 setLocation(Loc); 3202 3203 // Emit a line table change for the current location inside the new scope. 3204 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 3205 getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back())); 3206 3207 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 3208 return; 3209 3210 // Create a new lexical block and push it on the stack. 3211 CreateLexicalBlock(Loc); 3212 } 3213 3214 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, 3215 SourceLocation Loc) { 3216 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3217 3218 // Provide an entry in the line table for the end of the block. 3219 EmitLocation(Builder, Loc); 3220 3221 if (DebugKind <= codegenoptions::DebugLineTablesOnly) 3222 return; 3223 3224 LexicalBlockStack.pop_back(); 3225 } 3226 3227 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 3228 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3229 unsigned RCount = FnBeginRegionCount.back(); 3230 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 3231 3232 // Pop all regions for this function. 3233 while (LexicalBlockStack.size() != RCount) { 3234 // Provide an entry in the line table for the end of the block. 3235 EmitLocation(Builder, CurLoc); 3236 LexicalBlockStack.pop_back(); 3237 } 3238 FnBeginRegionCount.pop_back(); 3239 } 3240 3241 llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 3242 uint64_t *XOffset) { 3243 3244 SmallVector<llvm::Metadata *, 5> EltTys; 3245 QualType FType; 3246 uint64_t FieldSize, FieldOffset; 3247 uint32_t FieldAlign; 3248 3249 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 3250 QualType Type = VD->getType(); 3251 3252 FieldOffset = 0; 3253 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 3254 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 3255 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 3256 FType = CGM.getContext().IntTy; 3257 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 3258 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 3259 3260 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 3261 if (HasCopyAndDispose) { 3262 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 3263 EltTys.push_back( 3264 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset)); 3265 EltTys.push_back( 3266 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset)); 3267 } 3268 bool HasByrefExtendedLayout; 3269 Qualifiers::ObjCLifetime Lifetime; 3270 if (CGM.getContext().getByrefLifetime(Type, Lifetime, 3271 HasByrefExtendedLayout) && 3272 HasByrefExtendedLayout) { 3273 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 3274 EltTys.push_back( 3275 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset)); 3276 } 3277 3278 CharUnits Align = CGM.getContext().getDeclAlign(VD); 3279 if (Align > CGM.getContext().toCharUnitsFromBits( 3280 CGM.getTarget().getPointerAlign(0))) { 3281 CharUnits FieldOffsetInBytes = 3282 CGM.getContext().toCharUnitsFromBits(FieldOffset); 3283 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align); 3284 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes; 3285 3286 if (NumPaddingBytes.isPositive()) { 3287 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 3288 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 3289 pad, ArrayType::Normal, 0); 3290 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 3291 } 3292 } 3293 3294 FType = Type; 3295 llvm::DIType *FieldTy = getOrCreateType(FType, Unit); 3296 FieldSize = CGM.getContext().getTypeSize(FType); 3297 FieldAlign = CGM.getContext().toBits(Align); 3298 3299 *XOffset = FieldOffset; 3300 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize, 3301 FieldAlign, FieldOffset, 3302 llvm::DINode::FlagZero, FieldTy); 3303 EltTys.push_back(FieldTy); 3304 FieldOffset += FieldSize; 3305 3306 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 3307 3308 llvm::DINode::DIFlags Flags = llvm::DINode::FlagBlockByrefStruct; 3309 3310 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags, 3311 nullptr, Elements); 3312 } 3313 3314 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage, 3315 llvm::Optional<unsigned> ArgNo, 3316 CGBuilderTy &Builder) { 3317 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3318 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3319 if (VD->hasAttr<NoDebugAttr>()) 3320 return; 3321 3322 bool Unwritten = 3323 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) && 3324 cast<Decl>(VD->getDeclContext())->isImplicit()); 3325 llvm::DIFile *Unit = nullptr; 3326 if (!Unwritten) 3327 Unit = getOrCreateFile(VD->getLocation()); 3328 llvm::DIType *Ty; 3329 uint64_t XOffset = 0; 3330 if (VD->hasAttr<BlocksAttr>()) 3331 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 3332 else 3333 Ty = getOrCreateType(VD->getType(), Unit); 3334 3335 // If there is no debug info for this type then do not emit debug info 3336 // for this variable. 3337 if (!Ty) 3338 return; 3339 3340 // Get location information. 3341 unsigned Line = 0; 3342 unsigned Column = 0; 3343 if (!Unwritten) { 3344 Line = getLineNumber(VD->getLocation()); 3345 Column = getColumnNumber(VD->getLocation()); 3346 } 3347 SmallVector<int64_t, 9> Expr; 3348 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; 3349 if (VD->isImplicit()) 3350 Flags |= llvm::DINode::FlagArtificial; 3351 3352 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 3353 3354 // If this is the first argument and it is implicit then 3355 // give it an object pointer flag. 3356 // FIXME: There has to be a better way to do this, but for static 3357 // functions there won't be an implicit param at arg1 and 3358 // otherwise it is 'self' or 'this'. 3359 if (isa<ImplicitParamDecl>(VD) && ArgNo && *ArgNo == 1) 3360 Flags |= llvm::DINode::FlagObjectPointer; 3361 if (auto *Arg = dyn_cast<llvm::Argument>(Storage)) 3362 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() && 3363 !VD->getType()->isPointerType()) 3364 Expr.push_back(llvm::dwarf::DW_OP_deref); 3365 3366 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back()); 3367 3368 StringRef Name = VD->getName(); 3369 if (!Name.empty()) { 3370 if (VD->hasAttr<BlocksAttr>()) { 3371 CharUnits offset = CharUnits::fromQuantity(32); 3372 Expr.push_back(llvm::dwarf::DW_OP_plus); 3373 // offset of __forwarding field 3374 offset = CGM.getContext().toCharUnitsFromBits( 3375 CGM.getTarget().getPointerWidth(0)); 3376 Expr.push_back(offset.getQuantity()); 3377 Expr.push_back(llvm::dwarf::DW_OP_deref); 3378 Expr.push_back(llvm::dwarf::DW_OP_plus); 3379 // offset of x field 3380 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 3381 Expr.push_back(offset.getQuantity()); 3382 3383 // Create the descriptor for the variable. 3384 auto *D = ArgNo 3385 ? DBuilder.createParameterVariable(Scope, VD->getName(), 3386 *ArgNo, Unit, Line, Ty) 3387 : DBuilder.createAutoVariable(Scope, VD->getName(), Unit, 3388 Line, Ty, Align); 3389 3390 // Insert an llvm.dbg.declare into the current block. 3391 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 3392 llvm::DebugLoc::get(Line, Column, Scope), 3393 Builder.GetInsertBlock()); 3394 return; 3395 } else if (isa<VariableArrayType>(VD->getType())) 3396 Expr.push_back(llvm::dwarf::DW_OP_deref); 3397 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) { 3398 // If VD is an anonymous union then Storage represents value for 3399 // all union fields. 3400 const auto *RD = cast<RecordDecl>(RT->getDecl()); 3401 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 3402 // GDB has trouble finding local variables in anonymous unions, so we emit 3403 // artifical local variables for each of the members. 3404 // 3405 // FIXME: Remove this code as soon as GDB supports this. 3406 // The debug info verifier in LLVM operates based on the assumption that a 3407 // variable has the same size as its storage and we had to disable the check 3408 // for artificial variables. 3409 for (const auto *Field : RD->fields()) { 3410 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 3411 StringRef FieldName = Field->getName(); 3412 3413 // Ignore unnamed fields. Do not ignore unnamed records. 3414 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 3415 continue; 3416 3417 // Use VarDecl's Tag, Scope and Line number. 3418 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext()); 3419 auto *D = DBuilder.createAutoVariable( 3420 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize, 3421 Flags | llvm::DINode::FlagArtificial, FieldAlign); 3422 3423 // Insert an llvm.dbg.declare into the current block. 3424 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 3425 llvm::DebugLoc::get(Line, Column, Scope), 3426 Builder.GetInsertBlock()); 3427 } 3428 } 3429 } 3430 3431 // Create the descriptor for the variable. 3432 auto *D = ArgNo 3433 ? DBuilder.createParameterVariable( 3434 Scope, Name, *ArgNo, Unit, Line, Ty, 3435 CGM.getLangOpts().Optimize, Flags) 3436 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty, 3437 CGM.getLangOpts().Optimize, Flags, 3438 Align); 3439 3440 // Insert an llvm.dbg.declare into the current block. 3441 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 3442 llvm::DebugLoc::get(Line, Column, Scope), 3443 Builder.GetInsertBlock()); 3444 } 3445 3446 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 3447 llvm::Value *Storage, 3448 CGBuilderTy &Builder) { 3449 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3450 EmitDeclare(VD, Storage, llvm::None, Builder); 3451 } 3452 3453 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy, 3454 llvm::DIType *Ty) { 3455 llvm::DIType *CachedTy = getTypeOrNull(QualTy); 3456 if (CachedTy) 3457 Ty = CachedTy; 3458 return DBuilder.createObjectPointerType(Ty); 3459 } 3460 3461 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 3462 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder, 3463 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) { 3464 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3465 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 3466 3467 if (Builder.GetInsertBlock() == nullptr) 3468 return; 3469 if (VD->hasAttr<NoDebugAttr>()) 3470 return; 3471 3472 bool isByRef = VD->hasAttr<BlocksAttr>(); 3473 3474 uint64_t XOffset = 0; 3475 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 3476 llvm::DIType *Ty; 3477 if (isByRef) 3478 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 3479 else 3480 Ty = getOrCreateType(VD->getType(), Unit); 3481 3482 // Self is passed along as an implicit non-arg variable in a 3483 // block. Mark it as the object pointer. 3484 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self") 3485 Ty = CreateSelfType(VD->getType(), Ty); 3486 3487 // Get location information. 3488 unsigned Line = getLineNumber(VD->getLocation()); 3489 unsigned Column = getColumnNumber(VD->getLocation()); 3490 3491 const llvm::DataLayout &target = CGM.getDataLayout(); 3492 3493 CharUnits offset = CharUnits::fromQuantity( 3494 target.getStructLayout(blockInfo.StructureType) 3495 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 3496 3497 SmallVector<int64_t, 9> addr; 3498 if (isa<llvm::AllocaInst>(Storage)) 3499 addr.push_back(llvm::dwarf::DW_OP_deref); 3500 addr.push_back(llvm::dwarf::DW_OP_plus); 3501 addr.push_back(offset.getQuantity()); 3502 if (isByRef) { 3503 addr.push_back(llvm::dwarf::DW_OP_deref); 3504 addr.push_back(llvm::dwarf::DW_OP_plus); 3505 // offset of __forwarding field 3506 offset = 3507 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0)); 3508 addr.push_back(offset.getQuantity()); 3509 addr.push_back(llvm::dwarf::DW_OP_deref); 3510 addr.push_back(llvm::dwarf::DW_OP_plus); 3511 // offset of x field 3512 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 3513 addr.push_back(offset.getQuantity()); 3514 } 3515 3516 // Create the descriptor for the variable. 3517 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 3518 auto *D = DBuilder.createAutoVariable( 3519 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit, 3520 Line, Ty, false, llvm::DINode::FlagZero, Align); 3521 3522 // Insert an llvm.dbg.declare into the current block. 3523 auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back()); 3524 if (InsertPoint) 3525 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL, 3526 InsertPoint); 3527 else 3528 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL, 3529 Builder.GetInsertBlock()); 3530 } 3531 3532 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 3533 unsigned ArgNo, 3534 CGBuilderTy &Builder) { 3535 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3536 EmitDeclare(VD, AI, ArgNo, Builder); 3537 } 3538 3539 namespace { 3540 struct BlockLayoutChunk { 3541 uint64_t OffsetInBits; 3542 const BlockDecl::Capture *Capture; 3543 }; 3544 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 3545 return l.OffsetInBits < r.OffsetInBits; 3546 } 3547 } 3548 3549 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 3550 llvm::Value *Arg, 3551 unsigned ArgNo, 3552 llvm::Value *LocalAddr, 3553 CGBuilderTy &Builder) { 3554 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3555 ASTContext &C = CGM.getContext(); 3556 const BlockDecl *blockDecl = block.getBlockDecl(); 3557 3558 // Collect some general information about the block's location. 3559 SourceLocation loc = blockDecl->getCaretLocation(); 3560 llvm::DIFile *tunit = getOrCreateFile(loc); 3561 unsigned line = getLineNumber(loc); 3562 unsigned column = getColumnNumber(loc); 3563 3564 // Build the debug-info type for the block literal. 3565 getDeclContextDescriptor(blockDecl); 3566 3567 const llvm::StructLayout *blockLayout = 3568 CGM.getDataLayout().getStructLayout(block.StructureType); 3569 3570 SmallVector<llvm::Metadata *, 16> fields; 3571 fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public, 3572 blockLayout->getElementOffsetInBits(0), 3573 tunit, tunit)); 3574 fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public, 3575 blockLayout->getElementOffsetInBits(1), 3576 tunit, tunit)); 3577 fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public, 3578 blockLayout->getElementOffsetInBits(2), 3579 tunit, tunit)); 3580 auto *FnTy = block.getBlockExpr()->getFunctionType(); 3581 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); 3582 fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public, 3583 blockLayout->getElementOffsetInBits(3), 3584 tunit, tunit)); 3585 fields.push_back(createFieldType( 3586 "__descriptor", C.getPointerType(block.NeedsCopyDispose 3587 ? C.getBlockDescriptorExtendedType() 3588 : C.getBlockDescriptorType()), 3589 loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit)); 3590 3591 // We want to sort the captures by offset, not because DWARF 3592 // requires this, but because we're paranoid about debuggers. 3593 SmallVector<BlockLayoutChunk, 8> chunks; 3594 3595 // 'this' capture. 3596 if (blockDecl->capturesCXXThis()) { 3597 BlockLayoutChunk chunk; 3598 chunk.OffsetInBits = 3599 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 3600 chunk.Capture = nullptr; 3601 chunks.push_back(chunk); 3602 } 3603 3604 // Variable captures. 3605 for (const auto &capture : blockDecl->captures()) { 3606 const VarDecl *variable = capture.getVariable(); 3607 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 3608 3609 // Ignore constant captures. 3610 if (captureInfo.isConstant()) 3611 continue; 3612 3613 BlockLayoutChunk chunk; 3614 chunk.OffsetInBits = 3615 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 3616 chunk.Capture = &capture; 3617 chunks.push_back(chunk); 3618 } 3619 3620 // Sort by offset. 3621 llvm::array_pod_sort(chunks.begin(), chunks.end()); 3622 3623 for (const BlockLayoutChunk &Chunk : chunks) { 3624 uint64_t offsetInBits = Chunk.OffsetInBits; 3625 const BlockDecl::Capture *capture = Chunk.Capture; 3626 3627 // If we have a null capture, this must be the C++ 'this' capture. 3628 if (!capture) { 3629 QualType type; 3630 if (auto *Method = 3631 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext())) 3632 type = Method->getThisType(C); 3633 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent())) 3634 type = QualType(RDecl->getTypeForDecl(), 0); 3635 else 3636 llvm_unreachable("unexpected block declcontext"); 3637 3638 fields.push_back(createFieldType("this", type, loc, AS_public, 3639 offsetInBits, tunit, tunit)); 3640 continue; 3641 } 3642 3643 const VarDecl *variable = capture->getVariable(); 3644 StringRef name = variable->getName(); 3645 3646 llvm::DIType *fieldType; 3647 if (capture->isByRef()) { 3648 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy); 3649 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0; 3650 3651 // FIXME: this creates a second copy of this type! 3652 uint64_t xoffset; 3653 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset); 3654 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width); 3655 fieldType = DBuilder.createMemberType(tunit, name, tunit, line, 3656 PtrInfo.Width, Align, offsetInBits, 3657 llvm::DINode::FlagZero, fieldType); 3658 } else { 3659 auto Align = getDeclAlignIfRequired(variable, CGM.getContext()); 3660 fieldType = createFieldType(name, variable->getType(), loc, AS_public, 3661 offsetInBits, Align, tunit, tunit); 3662 } 3663 fields.push_back(fieldType); 3664 } 3665 3666 SmallString<36> typeName; 3667 llvm::raw_svector_ostream(typeName) << "__block_literal_" 3668 << CGM.getUniqueBlockCount(); 3669 3670 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields); 3671 3672 llvm::DIType *type = 3673 DBuilder.createStructType(tunit, typeName.str(), tunit, line, 3674 CGM.getContext().toBits(block.BlockSize), 0, 3675 llvm::DINode::FlagZero, nullptr, fieldsArray); 3676 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 3677 3678 // Get overall information about the block. 3679 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial; 3680 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back()); 3681 3682 // Create the descriptor for the parameter. 3683 auto *debugVar = DBuilder.createParameterVariable( 3684 scope, Arg->getName(), ArgNo, tunit, line, type, 3685 CGM.getLangOpts().Optimize, flags); 3686 3687 if (LocalAddr) { 3688 // Insert an llvm.dbg.value into the current block. 3689 DBuilder.insertDbgValueIntrinsic( 3690 LocalAddr, 0, debugVar, DBuilder.createExpression(), 3691 llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock()); 3692 } 3693 3694 // Insert an llvm.dbg.declare into the current block. 3695 DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(), 3696 llvm::DebugLoc::get(line, column, scope), 3697 Builder.GetInsertBlock()); 3698 } 3699 3700 llvm::DIDerivedType * 3701 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) { 3702 if (!D->isStaticDataMember()) 3703 return nullptr; 3704 3705 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl()); 3706 if (MI != StaticDataMemberCache.end()) { 3707 assert(MI->second && "Static data member declaration should still exist"); 3708 return MI->second; 3709 } 3710 3711 // If the member wasn't found in the cache, lazily construct and add it to the 3712 // type (used when a limited form of the type is emitted). 3713 auto DC = D->getDeclContext(); 3714 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D)); 3715 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC)); 3716 } 3717 3718 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls( 3719 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo, 3720 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) { 3721 llvm::DIGlobalVariableExpression *GVE = nullptr; 3722 3723 for (const auto *Field : RD->fields()) { 3724 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 3725 StringRef FieldName = Field->getName(); 3726 3727 // Ignore unnamed fields, but recurse into anonymous records. 3728 if (FieldName.empty()) { 3729 if (const auto *RT = dyn_cast<RecordType>(Field->getType())) 3730 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName, 3731 Var, DContext); 3732 continue; 3733 } 3734 // Use VarDecl's Tag, Scope and Line number. 3735 GVE = DBuilder.createGlobalVariableExpression( 3736 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy, 3737 Var->hasLocalLinkage()); 3738 Var->addDebugInfo(GVE); 3739 } 3740 return GVE; 3741 } 3742 3743 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 3744 const VarDecl *D) { 3745 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3746 if (D->hasAttr<NoDebugAttr>()) 3747 return; 3748 3749 // If we already created a DIGlobalVariable for this declaration, just attach 3750 // it to the llvm::GlobalVariable. 3751 auto Cached = DeclCache.find(D->getCanonicalDecl()); 3752 if (Cached != DeclCache.end()) 3753 return Var->addDebugInfo( 3754 cast<llvm::DIGlobalVariableExpression>(Cached->second)); 3755 3756 // Create global variable debug descriptor. 3757 llvm::DIFile *Unit = nullptr; 3758 llvm::DIScope *DContext = nullptr; 3759 unsigned LineNo; 3760 StringRef DeclName, LinkageName; 3761 QualType T; 3762 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext); 3763 3764 // Attempt to store one global variable for the declaration - even if we 3765 // emit a lot of fields. 3766 llvm::DIGlobalVariableExpression *GVE = nullptr; 3767 3768 // If this is an anonymous union then we'll want to emit a global 3769 // variable for each member of the anonymous union so that it's possible 3770 // to find the name of any field in the union. 3771 if (T->isUnionType() && DeclName.empty()) { 3772 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 3773 assert(RD->isAnonymousStructOrUnion() && 3774 "unnamed non-anonymous struct or union?"); 3775 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext); 3776 } else { 3777 auto Align = getDeclAlignIfRequired(D, CGM.getContext()); 3778 GVE = DBuilder.createGlobalVariableExpression( 3779 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit), 3780 Var->hasLocalLinkage(), /*Expr=*/nullptr, 3781 getOrCreateStaticDataMemberDeclarationOrNull(D), Align); 3782 Var->addDebugInfo(GVE); 3783 } 3784 DeclCache[D->getCanonicalDecl()].reset(GVE); 3785 } 3786 3787 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) { 3788 assert(DebugKind >= codegenoptions::LimitedDebugInfo); 3789 if (VD->hasAttr<NoDebugAttr>()) 3790 return; 3791 auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); 3792 // Create the descriptor for the variable. 3793 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 3794 StringRef Name = VD->getName(); 3795 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit); 3796 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) { 3797 const auto *ED = cast<EnumDecl>(ECD->getDeclContext()); 3798 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 3799 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 3800 } 3801 // Do not use global variables for enums. 3802 // 3803 // FIXME: why not? 3804 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type) 3805 return; 3806 // Do not emit separate definitions for function local const/statics. 3807 if (isa<FunctionDecl>(VD->getDeclContext())) 3808 return; 3809 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 3810 auto *VarD = cast<VarDecl>(VD); 3811 if (VarD->isStaticDataMember()) { 3812 auto *RD = cast<RecordDecl>(VarD->getDeclContext()); 3813 getDeclContextDescriptor(VarD); 3814 // Ensure that the type is retained even though it's otherwise unreferenced. 3815 // 3816 // FIXME: This is probably unnecessary, since Ty should reference RD 3817 // through its scope. 3818 RetainedTypes.push_back( 3819 CGM.getContext().getRecordType(RD).getAsOpaquePtr()); 3820 return; 3821 } 3822 3823 llvm::DIScope *DContext = getDeclContextDescriptor(VD); 3824 3825 auto &GV = DeclCache[VD]; 3826 if (GV) 3827 return; 3828 llvm::DIExpression *InitExpr = nullptr; 3829 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) { 3830 // FIXME: Add a representation for integer constants wider than 64 bits. 3831 if (Init.isInt()) 3832 InitExpr = 3833 DBuilder.createConstantValueExpression(Init.getInt().getExtValue()); 3834 else if (Init.isFloat()) 3835 InitExpr = DBuilder.createConstantValueExpression( 3836 Init.getFloat().bitcastToAPInt().getZExtValue()); 3837 } 3838 GV.reset(DBuilder.createGlobalVariableExpression( 3839 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty, 3840 true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD), 3841 Align)); 3842 } 3843 3844 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { 3845 if (!LexicalBlockStack.empty()) 3846 return LexicalBlockStack.back(); 3847 llvm::DIScope *Mod = getParentModuleOrNull(D); 3848 return getContextDescriptor(D, Mod ? Mod : TheCU); 3849 } 3850 3851 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { 3852 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 3853 return; 3854 const NamespaceDecl *NSDecl = UD.getNominatedNamespace(); 3855 if (!NSDecl->isAnonymousNamespace() || 3856 CGM.getCodeGenOpts().DebugExplicitImport) { 3857 DBuilder.createImportedModule( 3858 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())), 3859 getOrCreateNameSpace(NSDecl), 3860 getLineNumber(UD.getLocation())); 3861 } 3862 } 3863 3864 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { 3865 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 3866 return; 3867 assert(UD.shadow_size() && 3868 "We shouldn't be codegening an invalid UsingDecl containing no decls"); 3869 // Emitting one decl is sufficient - debuggers can detect that this is an 3870 // overloaded name & provide lookup for all the overloads. 3871 const UsingShadowDecl &USD = **UD.shadow_begin(); 3872 3873 // FIXME: Skip functions with undeduced auto return type for now since we 3874 // don't currently have the plumbing for separate declarations & definitions 3875 // of free functions and mismatched types (auto in the declaration, concrete 3876 // return type in the definition) 3877 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl())) 3878 if (const auto *AT = 3879 FD->getType()->getAs<FunctionProtoType>()->getContainedAutoType()) 3880 if (AT->getDeducedType().isNull()) 3881 return; 3882 if (llvm::DINode *Target = 3883 getDeclarationOrDefinition(USD.getUnderlyingDecl())) 3884 DBuilder.createImportedDeclaration( 3885 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target, 3886 getLineNumber(USD.getLocation())); 3887 } 3888 3889 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) { 3890 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB) 3891 return; 3892 if (Module *M = ID.getImportedModule()) { 3893 auto Info = ExternalASTSource::ASTSourceDescriptor(*M); 3894 DBuilder.createImportedDeclaration( 3895 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())), 3896 getOrCreateModuleRef(Info, DebugTypeExtRefs), 3897 getLineNumber(ID.getLocation())); 3898 } 3899 } 3900 3901 llvm::DIImportedEntity * 3902 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { 3903 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 3904 return nullptr; 3905 auto &VH = NamespaceAliasCache[&NA]; 3906 if (VH) 3907 return cast<llvm::DIImportedEntity>(VH); 3908 llvm::DIImportedEntity *R; 3909 if (const auto *Underlying = 3910 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace())) 3911 // This could cache & dedup here rather than relying on metadata deduping. 3912 R = DBuilder.createImportedDeclaration( 3913 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 3914 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()), 3915 NA.getName()); 3916 else 3917 R = DBuilder.createImportedDeclaration( 3918 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 3919 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())), 3920 getLineNumber(NA.getLocation()), NA.getName()); 3921 VH.reset(R); 3922 return R; 3923 } 3924 3925 llvm::DINamespace * 3926 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { 3927 NSDecl = NSDecl->getCanonicalDecl(); 3928 auto I = NameSpaceCache.find(NSDecl); 3929 if (I != NameSpaceCache.end()) 3930 return cast<llvm::DINamespace>(I->second); 3931 3932 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 3933 llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation()); 3934 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl); 3935 llvm::DINamespace *NS = DBuilder.createNameSpace( 3936 Context, NSDecl->getName(), FileD, LineNo, NSDecl->isInline()); 3937 NameSpaceCache[NSDecl].reset(NS); 3938 return NS; 3939 } 3940 3941 void CGDebugInfo::setDwoId(uint64_t Signature) { 3942 assert(TheCU && "no main compile unit"); 3943 TheCU->setDWOId(Signature); 3944 } 3945 3946 3947 void CGDebugInfo::finalize() { 3948 // Creating types might create further types - invalidating the current 3949 // element and the size(), so don't cache/reference them. 3950 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) { 3951 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i]; 3952 llvm::DIType *Ty = E.Type->getDecl()->getDefinition() 3953 ? CreateTypeDefinition(E.Type, E.Unit) 3954 : E.Decl; 3955 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty); 3956 } 3957 3958 for (auto p : ReplaceMap) { 3959 assert(p.second); 3960 auto *Ty = cast<llvm::DIType>(p.second); 3961 assert(Ty->isForwardDecl()); 3962 3963 auto it = TypeCache.find(p.first); 3964 assert(it != TypeCache.end()); 3965 assert(it->second); 3966 3967 DBuilder.replaceTemporary(llvm::TempDIType(Ty), 3968 cast<llvm::DIType>(it->second)); 3969 } 3970 3971 for (const auto &p : FwdDeclReplaceMap) { 3972 assert(p.second); 3973 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second)); 3974 llvm::Metadata *Repl; 3975 3976 auto it = DeclCache.find(p.first); 3977 // If there has been no definition for the declaration, call RAUW 3978 // with ourselves, that will destroy the temporary MDNode and 3979 // replace it with a standard one, avoiding leaking memory. 3980 if (it == DeclCache.end()) 3981 Repl = p.second; 3982 else 3983 Repl = it->second; 3984 3985 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl)) 3986 Repl = GVE->getVariable(); 3987 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl)); 3988 } 3989 3990 // We keep our own list of retained types, because we need to look 3991 // up the final type in the type cache. 3992 for (auto &RT : RetainedTypes) 3993 if (auto MD = TypeCache[RT]) 3994 DBuilder.retainType(cast<llvm::DIType>(MD)); 3995 3996 DBuilder.finalize(); 3997 } 3998 3999 void CGDebugInfo::EmitExplicitCastType(QualType Ty) { 4000 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo) 4001 return; 4002 4003 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile())) 4004 // Don't ignore in case of explicit cast where it is referenced indirectly. 4005 DBuilder.retainType(DieTy); 4006 } 4007 4008 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) { 4009 if (LexicalBlockStack.empty()) 4010 return llvm::DebugLoc(); 4011 4012 llvm::MDNode *Scope = LexicalBlockStack.back(); 4013 return llvm::DebugLoc::get( 4014 getLineNumber(Loc), getColumnNumber(Loc), Scope); 4015 } 4016