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