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