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