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