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