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