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