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