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::DIScope>(LexicalBlockStack.back()); 124 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc); 125 126 if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename()) 127 return; 128 129 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) { 130 LexicalBlockStack.pop_back(); 131 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile( 132 LBF->getScope(), getOrCreateFile(CurLoc))); 133 } else if (isa<llvm::DILexicalBlock>(Scope) || 134 isa<llvm::DISubprogram>(Scope)) { 135 LexicalBlockStack.pop_back(); 136 LexicalBlockStack.emplace_back( 137 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc))); 138 } 139 } 140 141 /// getContextDescriptor - Get context info for the decl. 142 llvm::DIScope *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::DIScope>(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::DIFile *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::DIFile>(V); 266 } 267 268 llvm::DIFile *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::DIFile *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::DIType *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::DINodeArray()); 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::DIType *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::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty, 540 llvm::DIFile *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::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, 574 llvm::DIFile *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::DIType *CGDebugInfo::CreateType(const PointerType *Ty, 587 llvm::DIFile *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::DICompileUnit *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::DICompositeType * 633 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty, 634 llvm::DIScope *Ctx) { 635 const RecordDecl *RD = Ty->getDecl(); 636 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD))) 637 return cast<llvm::DICompositeType>(T); 638 llvm::DIFile *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::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType( 654 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, 655 llvm::DINode::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::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag, 663 const Type *Ty, 664 QualType PointeeTy, 665 llvm::DIFile *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::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name, 682 llvm::DIType *&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::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty, 693 llvm::DIFile *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::DINodeArray 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::DINode::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::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, 751 llvm::DIFile *Unit) { 752 assert(Ty->isTypeAlias()); 753 llvm::DIType *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::DIType *CGDebugInfo::CreateType(const TypedefType *Ty, 774 llvm::DIFile *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::DIType *CGDebugInfo::CreateType(const FunctionType *Ty, 787 llvm::DIFile *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::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 805 return DBuilder.createSubroutineType(Unit, EltTypeArray); 806 } 807 808 /// Convert an AccessSpecifier into the corresponding DINode 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::DINode::FlagPrivate; 824 case clang::AS_protected: 825 return llvm::DINode::FlagProtected; 826 case clang::AS_public: 827 return llvm::DINode::FlagPublic; 828 case clang::AS_none: 829 return 0; 830 } 831 llvm_unreachable("unexpected access enumerator"); 832 } 833 834 llvm::DIType *CGDebugInfo::createFieldType( 835 StringRef name, QualType type, uint64_t sizeInBitsOverride, 836 SourceLocation loc, AccessSpecifier AS, uint64_t offsetInBits, 837 llvm::DIFile *tunit, llvm::DIScope *scope, const RecordDecl *RD) { 838 llvm::DIType *debugType = getOrCreateType(type, tunit); 839 840 // Get the location for the field. 841 llvm::DIFile *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::DIType *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::DIFile *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::DIType *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::DIFile *VUnit = getOrCreateFile(f->getLocation()); 895 QualType type = f->getType(); 896 llvm::DIType *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::DIDerivedType * 907 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *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::DIFile *VUnit = getOrCreateFile(Var->getLocation()); 913 llvm::DIType *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::DIDerivedType *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::DIFile *tunit, 938 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *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::DIType *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::DIFile *tunit, 964 SmallVectorImpl<llvm::Metadata *> &elements, 965 llvm::DICompositeType *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::DIDerivedTypeBase>(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::DISubroutineType * 1004 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, 1005 llvm::DIFile *Unit) { 1006 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>(); 1007 if (Method->isStatic()) 1008 return cast_or_null<llvm::DISubroutineType>( 1009 getOrCreateType(QualType(Func, 0), Unit)); 1010 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()), 1011 Func, Unit); 1012 } 1013 1014 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType( 1015 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) { 1016 // Add "this" pointer. 1017 llvm::DITypeRefArray Args( 1018 cast<llvm::DISubroutineType>(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::DIType *PointeeType = getOrCreateType(PointeeTy, Unit); 1037 llvm::DIType *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::DIType *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::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 1057 1058 unsigned Flags = 0; 1059 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue) 1060 Flags |= llvm::DINode::FlagLValueReference; 1061 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue) 1062 Flags |= llvm::DINode::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::DISubprogram *CGDebugInfo::CreateCXXMemberFunction( 1080 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) { 1081 bool IsCtorOrDtor = 1082 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method); 1083 1084 StringRef MethodName = getFunctionName(Method); 1085 llvm::DISubroutineType *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::DIFile *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::DIType *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::DINode::FlagArtificial; 1126 Flags |= getAccessFlag(Method->getAccess(), Method->getParent()); 1127 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) { 1128 if (CXXC->isExplicit()) 1129 Flags |= llvm::DINode::FlagExplicit; 1130 } else if (const CXXConversionDecl *CXXC = 1131 dyn_cast<CXXConversionDecl>(Method)) { 1132 if (CXXC->isExplicit()) 1133 Flags |= llvm::DINode::FlagExplicit; 1134 } 1135 if (Method->hasPrototype()) 1136 Flags |= llvm::DINode::FlagPrototyped; 1137 if (Method->getRefQualifier() == RQ_LValue) 1138 Flags |= llvm::DINode::FlagLValueReference; 1139 if (Method->getRefQualifier() == RQ_RValue) 1140 Flags |= llvm::DINode::FlagRValueReference; 1141 1142 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit); 1143 llvm::DISubprogram *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::DIFile *Unit, 1159 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *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::DIFile *Unit, 1198 SmallVectorImpl<llvm::Metadata *> &EltTys, 1199 llvm::DIType *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::DINode::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::DIType *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::DINodeArray 1236 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList, 1237 ArrayRef<TemplateArgument> TAList, 1238 llvm::DIFile *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::DIType *TTy = getOrCreateType(TA.getAsType(), Unit); 1248 TemplateParams.push_back( 1249 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy)); 1250 } break; 1251 case TemplateArgument::Integral: { 1252 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit); 1253 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1254 TheCU, Name, TTy, 1255 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()))); 1256 } break; 1257 case TemplateArgument::Declaration: { 1258 const ValueDecl *D = TA.getAsDecl(); 1259 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext()); 1260 llvm::DIType *TTy = getOrCreateType(T, Unit); 1261 llvm::Constant *V = nullptr; 1262 const CXXMethodDecl *MD; 1263 // Variable pointer template parameters have a value that is the address 1264 // of the variable. 1265 if (const auto *VD = dyn_cast<VarDecl>(D)) 1266 V = CGM.GetAddrOfGlobalVar(VD); 1267 // Member function pointers have special support for building them, though 1268 // this is currently unsupported in LLVM CodeGen. 1269 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance()) 1270 V = CGM.getCXXABI().EmitMemberPointer(MD); 1271 else if (const auto *FD = dyn_cast<FunctionDecl>(D)) 1272 V = CGM.GetAddrOfFunction(FD); 1273 // Member data pointers have special handling too to compute the fixed 1274 // offset within the object. 1275 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) { 1276 // These five lines (& possibly the above member function pointer 1277 // handling) might be able to be refactored to use similar code in 1278 // CodeGenModule::getMemberPointerConstant 1279 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D); 1280 CharUnits chars = 1281 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset); 1282 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars); 1283 } 1284 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1285 TheCU, Name, TTy, 1286 cast_or_null<llvm::Constant>(V->stripPointerCasts()))); 1287 } break; 1288 case TemplateArgument::NullPtr: { 1289 QualType T = TA.getNullPtrType(); 1290 llvm::DIType *TTy = getOrCreateType(T, Unit); 1291 llvm::Constant *V = nullptr; 1292 // Special case member data pointer null values since they're actually -1 1293 // instead of zero. 1294 if (const MemberPointerType *MPT = 1295 dyn_cast<MemberPointerType>(T.getTypePtr())) 1296 // But treat member function pointers as simple zero integers because 1297 // it's easier than having a special case in LLVM's CodeGen. If LLVM 1298 // CodeGen grows handling for values of non-null member function 1299 // pointers then perhaps we could remove this special case and rely on 1300 // EmitNullMemberPointer for member function pointers. 1301 if (MPT->isMemberDataPointer()) 1302 V = CGM.getCXXABI().EmitNullMemberPointer(MPT); 1303 if (!V) 1304 V = llvm::ConstantInt::get(CGM.Int8Ty, 0); 1305 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1306 TheCU, Name, TTy, cast<llvm::Constant>(V))); 1307 } break; 1308 case TemplateArgument::Template: 1309 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter( 1310 TheCU, Name, nullptr, 1311 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString())); 1312 break; 1313 case TemplateArgument::Pack: 1314 TemplateParams.push_back(DBuilder.createTemplateParameterPack( 1315 TheCU, Name, nullptr, 1316 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit))); 1317 break; 1318 case TemplateArgument::Expression: { 1319 const Expr *E = TA.getAsExpr(); 1320 QualType T = E->getType(); 1321 if (E->isGLValue()) 1322 T = CGM.getContext().getLValueReferenceType(T); 1323 llvm::Constant *V = CGM.EmitConstantExpr(E, T); 1324 assert(V && "Expression in template argument isn't constant"); 1325 llvm::DIType *TTy = getOrCreateType(T, Unit); 1326 TemplateParams.push_back(DBuilder.createTemplateValueParameter( 1327 TheCU, Name, TTy, cast<llvm::Constant>(V->stripPointerCasts()))); 1328 } break; 1329 // And the following should never occur: 1330 case TemplateArgument::TemplateExpansion: 1331 case TemplateArgument::Null: 1332 llvm_unreachable( 1333 "These argument types shouldn't exist in concrete types"); 1334 } 1335 } 1336 return DBuilder.getOrCreateArray(TemplateParams); 1337 } 1338 1339 /// CollectFunctionTemplateParams - A helper function to collect debug 1340 /// info for function template parameters. 1341 llvm::DINodeArray 1342 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD, 1343 llvm::DIFile *Unit) { 1344 if (FD->getTemplatedKind() == 1345 FunctionDecl::TK_FunctionTemplateSpecialization) { 1346 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo() 1347 ->getTemplate() 1348 ->getTemplateParameters(); 1349 return CollectTemplateParams( 1350 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit); 1351 } 1352 return llvm::DINodeArray(); 1353 } 1354 1355 /// CollectCXXTemplateParams - A helper function to collect debug info for 1356 /// template parameters. 1357 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams( 1358 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) { 1359 // Always get the full list of parameters, not just the ones from 1360 // the specialization. 1361 TemplateParameterList *TPList = 1362 TSpecial->getSpecializedTemplate()->getTemplateParameters(); 1363 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs(); 1364 return CollectTemplateParams(TPList, TAList.asArray(), Unit); 1365 } 1366 1367 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable. 1368 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) { 1369 if (VTablePtrType) 1370 return VTablePtrType; 1371 1372 ASTContext &Context = CGM.getContext(); 1373 1374 /* Function type */ 1375 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit); 1376 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy); 1377 llvm::DIType *SubTy = DBuilder.createSubroutineType(Unit, SElements); 1378 unsigned Size = Context.getTypeSize(Context.VoidPtrTy); 1379 llvm::DIType *vtbl_ptr_type = 1380 DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type"); 1381 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size); 1382 return VTablePtrType; 1383 } 1384 1385 /// getVTableName - Get vtable name for the given Class. 1386 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { 1387 // Copy the gdb compatible name on the side and use its reference. 1388 return internString("_vptr$", RD->getNameAsString()); 1389 } 1390 1391 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate 1392 /// debug info entry in EltTys vector. 1393 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit, 1394 SmallVectorImpl<llvm::Metadata *> &EltTys) { 1395 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 1396 1397 // If there is a primary base then it will hold vtable info. 1398 if (RL.getPrimaryBase()) 1399 return; 1400 1401 // If this class is not dynamic then there is not any vtable info to collect. 1402 if (!RD->isDynamicClass()) 1403 return; 1404 1405 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); 1406 llvm::DIType *VPTR = DBuilder.createMemberType( 1407 Unit, getVTableName(RD), Unit, 0, Size, 0, 0, 1408 llvm::DINode::FlagArtificial, getOrCreateVTablePtrType(Unit)); 1409 EltTys.push_back(VPTR); 1410 } 1411 1412 /// getOrCreateRecordType - Emit record type's standalone debug info. 1413 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy, 1414 SourceLocation Loc) { 1415 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 1416 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc)); 1417 return T; 1418 } 1419 1420 /// getOrCreateInterfaceType - Emit an objective c interface type standalone 1421 /// debug info. 1422 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D, 1423 SourceLocation Loc) { 1424 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 1425 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc)); 1426 RetainedTypes.push_back(D.getAsOpaquePtr()); 1427 return T; 1428 } 1429 1430 void CGDebugInfo::completeType(const EnumDecl *ED) { 1431 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 1432 return; 1433 QualType Ty = CGM.getContext().getEnumType(ED); 1434 void *TyPtr = Ty.getAsOpaquePtr(); 1435 auto I = TypeCache.find(TyPtr); 1436 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl()) 1437 return; 1438 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>()); 1439 assert(!Res->isForwardDecl()); 1440 TypeCache[TyPtr].reset(Res); 1441 } 1442 1443 void CGDebugInfo::completeType(const RecordDecl *RD) { 1444 if (DebugKind > CodeGenOptions::LimitedDebugInfo || 1445 !CGM.getLangOpts().CPlusPlus) 1446 completeRequiredType(RD); 1447 } 1448 1449 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) { 1450 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 1451 return; 1452 1453 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) 1454 if (CXXDecl->isDynamicClass()) 1455 return; 1456 1457 QualType Ty = CGM.getContext().getRecordType(RD); 1458 llvm::DIType *T = getTypeOrNull(Ty); 1459 if (T && T->isForwardDecl()) 1460 completeClassData(RD); 1461 } 1462 1463 void CGDebugInfo::completeClassData(const RecordDecl *RD) { 1464 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 1465 return; 1466 QualType Ty = CGM.getContext().getRecordType(RD); 1467 void *TyPtr = Ty.getAsOpaquePtr(); 1468 auto I = TypeCache.find(TyPtr); 1469 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl()) 1470 return; 1471 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>()); 1472 assert(!Res->isForwardDecl()); 1473 TypeCache[TyPtr].reset(Res); 1474 } 1475 1476 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, 1477 CXXRecordDecl::method_iterator End) { 1478 for (; I != End; ++I) 1479 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction()) 1480 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() && 1481 !I->getMemberSpecializationInfo()->isExplicitSpecialization()) 1482 return true; 1483 return false; 1484 } 1485 1486 static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind, 1487 const RecordDecl *RD, 1488 const LangOptions &LangOpts) { 1489 if (DebugKind > CodeGenOptions::LimitedDebugInfo) 1490 return false; 1491 1492 if (!LangOpts.CPlusPlus) 1493 return false; 1494 1495 if (!RD->isCompleteDefinitionRequired()) 1496 return true; 1497 1498 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1499 1500 if (!CXXDecl) 1501 return false; 1502 1503 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass()) 1504 return true; 1505 1506 TemplateSpecializationKind Spec = TSK_Undeclared; 1507 if (const ClassTemplateSpecializationDecl *SD = 1508 dyn_cast<ClassTemplateSpecializationDecl>(RD)) 1509 Spec = SD->getSpecializationKind(); 1510 1511 if (Spec == TSK_ExplicitInstantiationDeclaration && 1512 hasExplicitMemberDefinition(CXXDecl->method_begin(), 1513 CXXDecl->method_end())) 1514 return true; 1515 1516 return false; 1517 } 1518 1519 /// CreateType - get structure or union type. 1520 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) { 1521 RecordDecl *RD = Ty->getDecl(); 1522 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0))); 1523 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) { 1524 if (!T) 1525 T = getOrCreateRecordFwdDecl( 1526 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext()))); 1527 return T; 1528 } 1529 1530 return CreateTypeDefinition(Ty); 1531 } 1532 1533 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) { 1534 RecordDecl *RD = Ty->getDecl(); 1535 1536 // Get overall information about the record type for the debug info. 1537 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 1538 1539 // Records and classes and unions can all be recursive. To handle them, we 1540 // first generate a debug descriptor for the struct as a forward declaration. 1541 // Then (if it is a definition) we go through and get debug info for all of 1542 // its members. Finally, we create a descriptor for the complete type (which 1543 // may refer to the forward decl if the struct is recursive) and replace all 1544 // uses of the forward declaration with the final definition. 1545 1546 auto *FwdDecl = 1547 cast<llvm::DICompositeType>(getOrCreateLimitedType(Ty, DefUnit)); 1548 1549 const RecordDecl *D = RD->getDefinition(); 1550 if (!D || !D->isCompleteDefinition()) 1551 return FwdDecl; 1552 1553 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) 1554 CollectContainingType(CXXDecl, FwdDecl); 1555 1556 // Push the struct on region stack. 1557 LexicalBlockStack.emplace_back(&*FwdDecl); 1558 RegionMap[Ty->getDecl()].reset(FwdDecl); 1559 1560 // Convert all the elements. 1561 SmallVector<llvm::Metadata *, 16> EltTys; 1562 // what about nested types? 1563 1564 // Note: The split of CXXDecl information here is intentional, the 1565 // gdb tests will depend on a certain ordering at printout. The debug 1566 // information offsets are still correct if we merge them all together 1567 // though. 1568 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD); 1569 if (CXXDecl) { 1570 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl); 1571 CollectVTableInfo(CXXDecl, DefUnit, EltTys); 1572 } 1573 1574 // Collect data fields (including static variables and any initializers). 1575 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl); 1576 if (CXXDecl) 1577 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl); 1578 1579 LexicalBlockStack.pop_back(); 1580 RegionMap.erase(Ty->getDecl()); 1581 1582 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 1583 DBuilder.replaceArrays(FwdDecl, Elements); 1584 1585 if (FwdDecl->isTemporary()) 1586 FwdDecl = 1587 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl)); 1588 1589 RegionMap[Ty->getDecl()].reset(FwdDecl); 1590 return FwdDecl; 1591 } 1592 1593 /// CreateType - get objective-c object type. 1594 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty, 1595 llvm::DIFile *Unit) { 1596 // Ignore protocols. 1597 return getOrCreateType(Ty->getBaseType(), Unit); 1598 } 1599 1600 /// \return true if Getter has the default name for the property PD. 1601 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, 1602 const ObjCMethodDecl *Getter) { 1603 assert(PD); 1604 if (!Getter) 1605 return true; 1606 1607 assert(Getter->getDeclName().isObjCZeroArgSelector()); 1608 return PD->getName() == 1609 Getter->getDeclName().getObjCSelector().getNameForSlot(0); 1610 } 1611 1612 /// \return true if Setter has the default name for the property PD. 1613 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, 1614 const ObjCMethodDecl *Setter) { 1615 assert(PD); 1616 if (!Setter) 1617 return true; 1618 1619 assert(Setter->getDeclName().isObjCOneArgSelector()); 1620 return SelectorTable::constructSetterName(PD->getName()) == 1621 Setter->getDeclName().getObjCSelector().getNameForSlot(0); 1622 } 1623 1624 /// CreateType - get objective-c interface type. 1625 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, 1626 llvm::DIFile *Unit) { 1627 ObjCInterfaceDecl *ID = Ty->getDecl(); 1628 if (!ID) 1629 return nullptr; 1630 1631 // Get overall information about the record type for the debug info. 1632 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation()); 1633 unsigned Line = getLineNumber(ID->getLocation()); 1634 auto RuntimeLang = 1635 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage()); 1636 1637 // If this is just a forward declaration return a special forward-declaration 1638 // debug type since we won't be able to lay out the entire type. 1639 ObjCInterfaceDecl *Def = ID->getDefinition(); 1640 if (!Def || !Def->getImplementation()) { 1641 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType( 1642 llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line, 1643 RuntimeLang); 1644 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit)); 1645 return FwdDecl; 1646 } 1647 1648 return CreateTypeDefinition(Ty, Unit); 1649 } 1650 1651 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty, 1652 llvm::DIFile *Unit) { 1653 ObjCInterfaceDecl *ID = Ty->getDecl(); 1654 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation()); 1655 unsigned Line = getLineNumber(ID->getLocation()); 1656 unsigned RuntimeLang = TheCU->getSourceLanguage(); 1657 1658 // Bit size, align and offset of the type. 1659 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1660 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1661 1662 unsigned Flags = 0; 1663 if (ID->getImplementation()) 1664 Flags |= llvm::DINode::FlagObjcClassComplete; 1665 1666 llvm::DICompositeType *RealDecl = DBuilder.createStructType( 1667 Unit, ID->getName(), DefUnit, Line, Size, Align, Flags, nullptr, 1668 llvm::DINodeArray(), RuntimeLang); 1669 1670 QualType QTy(Ty, 0); 1671 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl); 1672 1673 // Push the struct on region stack. 1674 LexicalBlockStack.emplace_back(RealDecl); 1675 RegionMap[Ty->getDecl()].reset(RealDecl); 1676 1677 // Convert all the elements. 1678 SmallVector<llvm::Metadata *, 16> EltTys; 1679 1680 ObjCInterfaceDecl *SClass = ID->getSuperClass(); 1681 if (SClass) { 1682 llvm::DIType *SClassTy = 1683 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit); 1684 if (!SClassTy) 1685 return nullptr; 1686 1687 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0); 1688 EltTys.push_back(InhTag); 1689 } 1690 1691 // Create entries for all of the properties. 1692 for (const auto *PD : ID->properties()) { 1693 SourceLocation Loc = PD->getLocation(); 1694 llvm::DIFile *PUnit = getOrCreateFile(Loc); 1695 unsigned PLine = getLineNumber(Loc); 1696 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 1697 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 1698 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty( 1699 PD->getName(), PUnit, PLine, 1700 hasDefaultGetterName(PD, Getter) ? "" 1701 : getSelectorName(PD->getGetterName()), 1702 hasDefaultSetterName(PD, Setter) ? "" 1703 : getSelectorName(PD->getSetterName()), 1704 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit)); 1705 EltTys.push_back(PropertyNode); 1706 } 1707 1708 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID); 1709 unsigned FieldNo = 0; 1710 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; 1711 Field = Field->getNextIvar(), ++FieldNo) { 1712 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 1713 if (!FieldTy) 1714 return nullptr; 1715 1716 StringRef FieldName = Field->getName(); 1717 1718 // Ignore unnamed fields. 1719 if (FieldName.empty()) 1720 continue; 1721 1722 // Get the location for the field. 1723 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation()); 1724 unsigned FieldLine = getLineNumber(Field->getLocation()); 1725 QualType FType = Field->getType(); 1726 uint64_t FieldSize = 0; 1727 unsigned FieldAlign = 0; 1728 1729 if (!FType->isIncompleteArrayType()) { 1730 1731 // Bit size, align and offset of the type. 1732 FieldSize = Field->isBitField() 1733 ? Field->getBitWidthValue(CGM.getContext()) 1734 : CGM.getContext().getTypeSize(FType); 1735 FieldAlign = CGM.getContext().getTypeAlign(FType); 1736 } 1737 1738 uint64_t FieldOffset; 1739 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { 1740 // We don't know the runtime offset of an ivar if we're using the 1741 // non-fragile ABI. For bitfields, use the bit offset into the first 1742 // byte of storage of the bitfield. For other fields, use zero. 1743 if (Field->isBitField()) { 1744 FieldOffset = 1745 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field); 1746 FieldOffset %= CGM.getContext().getCharWidth(); 1747 } else { 1748 FieldOffset = 0; 1749 } 1750 } else { 1751 FieldOffset = RL.getFieldOffset(FieldNo); 1752 } 1753 1754 unsigned Flags = 0; 1755 if (Field->getAccessControl() == ObjCIvarDecl::Protected) 1756 Flags = llvm::DINode::FlagProtected; 1757 else if (Field->getAccessControl() == ObjCIvarDecl::Private) 1758 Flags = llvm::DINode::FlagPrivate; 1759 else if (Field->getAccessControl() == ObjCIvarDecl::Public) 1760 Flags = llvm::DINode::FlagPublic; 1761 1762 llvm::MDNode *PropertyNode = nullptr; 1763 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { 1764 if (ObjCPropertyImplDecl *PImpD = 1765 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) { 1766 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { 1767 SourceLocation Loc = PD->getLocation(); 1768 llvm::DIFile *PUnit = getOrCreateFile(Loc); 1769 unsigned PLine = getLineNumber(Loc); 1770 ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); 1771 ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); 1772 PropertyNode = DBuilder.createObjCProperty( 1773 PD->getName(), PUnit, PLine, 1774 hasDefaultGetterName(PD, Getter) ? "" : getSelectorName( 1775 PD->getGetterName()), 1776 hasDefaultSetterName(PD, Setter) ? "" : getSelectorName( 1777 PD->getSetterName()), 1778 PD->getPropertyAttributes(), 1779 getOrCreateType(PD->getType(), PUnit)); 1780 } 1781 } 1782 } 1783 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine, 1784 FieldSize, FieldAlign, FieldOffset, Flags, 1785 FieldTy, PropertyNode); 1786 EltTys.push_back(FieldTy); 1787 } 1788 1789 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 1790 DBuilder.replaceArrays(RealDecl, Elements); 1791 1792 LexicalBlockStack.pop_back(); 1793 return RealDecl; 1794 } 1795 1796 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty, 1797 llvm::DIFile *Unit) { 1798 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit); 1799 int64_t Count = Ty->getNumElements(); 1800 if (Count == 0) 1801 // If number of elements are not known then this is an unbounded array. 1802 // Use Count == -1 to express such arrays. 1803 Count = -1; 1804 1805 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count); 1806 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript); 1807 1808 uint64_t Size = CGM.getContext().getTypeSize(Ty); 1809 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 1810 1811 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray); 1812 } 1813 1814 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) { 1815 uint64_t Size; 1816 uint64_t Align; 1817 1818 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types 1819 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { 1820 Size = 0; 1821 Align = 1822 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT)); 1823 } else if (Ty->isIncompleteArrayType()) { 1824 Size = 0; 1825 if (Ty->getElementType()->isIncompleteType()) 1826 Align = 0; 1827 else 1828 Align = CGM.getContext().getTypeAlign(Ty->getElementType()); 1829 } else if (Ty->isIncompleteType()) { 1830 Size = 0; 1831 Align = 0; 1832 } else { 1833 // Size and align of the whole array, not the element type. 1834 Size = CGM.getContext().getTypeSize(Ty); 1835 Align = CGM.getContext().getTypeAlign(Ty); 1836 } 1837 1838 // Add the dimensions of the array. FIXME: This loses CV qualifiers from 1839 // interior arrays, do we care? Why aren't nested arrays represented the 1840 // obvious/recursive way? 1841 SmallVector<llvm::Metadata *, 8> Subscripts; 1842 QualType EltTy(Ty, 0); 1843 while ((Ty = dyn_cast<ArrayType>(EltTy))) { 1844 // If the number of elements is known, then count is that number. Otherwise, 1845 // it's -1. This allows us to represent a subrange with an array of 0 1846 // elements, like this: 1847 // 1848 // struct foo { 1849 // int x[0]; 1850 // }; 1851 int64_t Count = -1; // Count == -1 is an unbounded array. 1852 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) 1853 Count = CAT->getSize().getZExtValue(); 1854 1855 // FIXME: Verify this is right for VLAs. 1856 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count)); 1857 EltTy = Ty->getElementType(); 1858 } 1859 1860 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts); 1861 1862 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit), 1863 SubscriptArray); 1864 } 1865 1866 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty, 1867 llvm::DIFile *Unit) { 1868 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty, 1869 Ty->getPointeeType(), Unit); 1870 } 1871 1872 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty, 1873 llvm::DIFile *Unit) { 1874 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty, 1875 Ty->getPointeeType(), Unit); 1876 } 1877 1878 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty, 1879 llvm::DIFile *U) { 1880 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U); 1881 if (Ty->isMemberDataPointerType()) 1882 return DBuilder.createMemberPointerType( 1883 getOrCreateType(Ty->getPointeeType(), U), ClassType, 1884 CGM.getContext().getTypeSize(Ty)); 1885 1886 const FunctionProtoType *FPT = 1887 Ty->getPointeeType()->getAs<FunctionProtoType>(); 1888 return DBuilder.createMemberPointerType( 1889 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType( 1890 Ty->getClass(), FPT->getTypeQuals())), 1891 FPT, U), 1892 ClassType, CGM.getContext().getTypeSize(Ty)); 1893 } 1894 1895 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) { 1896 // Ignore the atomic wrapping 1897 // FIXME: What is the correct representation? 1898 return getOrCreateType(Ty->getValueType(), U); 1899 } 1900 1901 /// CreateEnumType - get enumeration type. 1902 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) { 1903 const EnumDecl *ED = Ty->getDecl(); 1904 uint64_t Size = 0; 1905 uint64_t Align = 0; 1906 if (!ED->getTypeForDecl()->isIncompleteType()) { 1907 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1908 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1909 } 1910 1911 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 1912 1913 // If this is just a forward declaration, construct an appropriately 1914 // marked node and just return it. 1915 if (!ED->getDefinition()) { 1916 llvm::DIScope *EDContext = 1917 getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1918 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); 1919 unsigned Line = getLineNumber(ED->getLocation()); 1920 StringRef EDName = ED->getName(); 1921 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType( 1922 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line, 1923 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName); 1924 ReplaceMap.emplace_back( 1925 std::piecewise_construct, std::make_tuple(Ty), 1926 std::make_tuple(static_cast<llvm::Metadata *>(RetTy))); 1927 return RetTy; 1928 } 1929 1930 return CreateTypeDefinition(Ty); 1931 } 1932 1933 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { 1934 const EnumDecl *ED = Ty->getDecl(); 1935 uint64_t Size = 0; 1936 uint64_t Align = 0; 1937 if (!ED->getTypeForDecl()->isIncompleteType()) { 1938 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); 1939 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl()); 1940 } 1941 1942 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 1943 1944 // Create elements for each enumerator. 1945 SmallVector<llvm::Metadata *, 16> Enumerators; 1946 ED = ED->getDefinition(); 1947 for (const auto *Enum : ED->enumerators()) { 1948 Enumerators.push_back(DBuilder.createEnumerator( 1949 Enum->getName(), Enum->getInitVal().getSExtValue())); 1950 } 1951 1952 // Return a CompositeType for the enum itself. 1953 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators); 1954 1955 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); 1956 unsigned Line = getLineNumber(ED->getLocation()); 1957 llvm::DIScope *EnumContext = 1958 getContextDescriptor(cast<Decl>(ED->getDeclContext())); 1959 llvm::DIType *ClassTy = 1960 ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr; 1961 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, 1962 Line, Size, Align, EltArray, ClassTy, 1963 FullName); 1964 } 1965 1966 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { 1967 Qualifiers Quals; 1968 do { 1969 Qualifiers InnerQuals = T.getLocalQualifiers(); 1970 // Qualifiers::operator+() doesn't like it if you add a Qualifier 1971 // that is already there. 1972 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals); 1973 Quals += InnerQuals; 1974 QualType LastT = T; 1975 switch (T->getTypeClass()) { 1976 default: 1977 return C.getQualifiedType(T.getTypePtr(), Quals); 1978 case Type::TemplateSpecialization: { 1979 const auto *Spec = cast<TemplateSpecializationType>(T); 1980 if (Spec->isTypeAlias()) 1981 return C.getQualifiedType(T.getTypePtr(), Quals); 1982 T = Spec->desugar(); 1983 break; 1984 } 1985 case Type::TypeOfExpr: 1986 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 1987 break; 1988 case Type::TypeOf: 1989 T = cast<TypeOfType>(T)->getUnderlyingType(); 1990 break; 1991 case Type::Decltype: 1992 T = cast<DecltypeType>(T)->getUnderlyingType(); 1993 break; 1994 case Type::UnaryTransform: 1995 T = cast<UnaryTransformType>(T)->getUnderlyingType(); 1996 break; 1997 case Type::Attributed: 1998 T = cast<AttributedType>(T)->getEquivalentType(); 1999 break; 2000 case Type::Elaborated: 2001 T = cast<ElaboratedType>(T)->getNamedType(); 2002 break; 2003 case Type::Paren: 2004 T = cast<ParenType>(T)->getInnerType(); 2005 break; 2006 case Type::SubstTemplateTypeParm: 2007 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType(); 2008 break; 2009 case Type::Auto: 2010 QualType DT = cast<AutoType>(T)->getDeducedType(); 2011 assert(!DT.isNull() && "Undeduced types shouldn't reach here."); 2012 T = DT; 2013 break; 2014 } 2015 2016 assert(T != LastT && "Type unwrapping failed to unwrap!"); 2017 (void)LastT; 2018 } while (true); 2019 } 2020 2021 /// getType - Get the type from the cache or return null type if it doesn't 2022 /// exist. 2023 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) { 2024 2025 // Unwrap the type as needed for debug information. 2026 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2027 2028 auto it = TypeCache.find(Ty.getAsOpaquePtr()); 2029 if (it != TypeCache.end()) { 2030 // Verify that the debug info still exists. 2031 if (llvm::Metadata *V = it->second) 2032 return cast<llvm::DIType>(V); 2033 } 2034 2035 return nullptr; 2036 } 2037 2038 void CGDebugInfo::completeTemplateDefinition( 2039 const ClassTemplateSpecializationDecl &SD) { 2040 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2041 return; 2042 2043 completeClassData(&SD); 2044 // In case this type has no member function definitions being emitted, ensure 2045 // it is retained 2046 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr()); 2047 } 2048 2049 /// getOrCreateType - Get the type from the cache or create a new 2050 /// one if necessary. 2051 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) { 2052 if (Ty.isNull()) 2053 return nullptr; 2054 2055 // Unwrap the type as needed for debug information. 2056 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext()); 2057 2058 if (auto *T = getTypeOrNull(Ty)) 2059 return T; 2060 2061 // Otherwise create the type. 2062 llvm::DIType *Res = CreateTypeNode(Ty, Unit); 2063 void *TyPtr = Ty.getAsOpaquePtr(); 2064 2065 // And update the type cache. 2066 TypeCache[TyPtr].reset(Res); 2067 2068 return Res; 2069 } 2070 2071 /// Currently the checksum of an interface includes the number of 2072 /// ivars and property accessors. 2073 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) { 2074 // The assumption is that the number of ivars can only increase 2075 // monotonically, so it is safe to just use their current number as 2076 // a checksum. 2077 unsigned Sum = 0; 2078 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin(); 2079 Ivar != nullptr; Ivar = Ivar->getNextIvar()) 2080 ++Sum; 2081 2082 return Sum; 2083 } 2084 2085 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) { 2086 switch (Ty->getTypeClass()) { 2087 case Type::ObjCObjectPointer: 2088 return getObjCInterfaceDecl( 2089 cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 2090 case Type::ObjCInterface: 2091 return cast<ObjCInterfaceType>(Ty)->getDecl(); 2092 default: 2093 return nullptr; 2094 } 2095 } 2096 2097 /// CreateTypeNode - Create a new debug type node. 2098 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) { 2099 // Handle qualifiers, which recursively handles what they refer to. 2100 if (Ty.hasLocalQualifiers()) 2101 return CreateQualifiedType(Ty, Unit); 2102 2103 // Work out details of type. 2104 switch (Ty->getTypeClass()) { 2105 #define TYPE(Class, Base) 2106 #define ABSTRACT_TYPE(Class, Base) 2107 #define NON_CANONICAL_TYPE(Class, Base) 2108 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2109 #include "clang/AST/TypeNodes.def" 2110 llvm_unreachable("Dependent types cannot show up in debug information"); 2111 2112 case Type::ExtVector: 2113 case Type::Vector: 2114 return CreateType(cast<VectorType>(Ty), Unit); 2115 case Type::ObjCObjectPointer: 2116 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); 2117 case Type::ObjCObject: 2118 return CreateType(cast<ObjCObjectType>(Ty), Unit); 2119 case Type::ObjCInterface: 2120 return CreateType(cast<ObjCInterfaceType>(Ty), Unit); 2121 case Type::Builtin: 2122 return CreateType(cast<BuiltinType>(Ty)); 2123 case Type::Complex: 2124 return CreateType(cast<ComplexType>(Ty)); 2125 case Type::Pointer: 2126 return CreateType(cast<PointerType>(Ty), Unit); 2127 case Type::Adjusted: 2128 case Type::Decayed: 2129 // Decayed and adjusted types use the adjusted type in LLVM and DWARF. 2130 return CreateType( 2131 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit); 2132 case Type::BlockPointer: 2133 return CreateType(cast<BlockPointerType>(Ty), Unit); 2134 case Type::Typedef: 2135 return CreateType(cast<TypedefType>(Ty), Unit); 2136 case Type::Record: 2137 return CreateType(cast<RecordType>(Ty)); 2138 case Type::Enum: 2139 return CreateEnumType(cast<EnumType>(Ty)); 2140 case Type::FunctionProto: 2141 case Type::FunctionNoProto: 2142 return CreateType(cast<FunctionType>(Ty), Unit); 2143 case Type::ConstantArray: 2144 case Type::VariableArray: 2145 case Type::IncompleteArray: 2146 return CreateType(cast<ArrayType>(Ty), Unit); 2147 2148 case Type::LValueReference: 2149 return CreateType(cast<LValueReferenceType>(Ty), Unit); 2150 case Type::RValueReference: 2151 return CreateType(cast<RValueReferenceType>(Ty), Unit); 2152 2153 case Type::MemberPointer: 2154 return CreateType(cast<MemberPointerType>(Ty), Unit); 2155 2156 case Type::Atomic: 2157 return CreateType(cast<AtomicType>(Ty), Unit); 2158 2159 case Type::TemplateSpecialization: 2160 return CreateType(cast<TemplateSpecializationType>(Ty), Unit); 2161 2162 case Type::Auto: 2163 case Type::Attributed: 2164 case Type::Elaborated: 2165 case Type::Paren: 2166 case Type::SubstTemplateTypeParm: 2167 case Type::TypeOfExpr: 2168 case Type::TypeOf: 2169 case Type::Decltype: 2170 case Type::UnaryTransform: 2171 case Type::PackExpansion: 2172 break; 2173 } 2174 2175 llvm_unreachable("type should have been unwrapped!"); 2176 } 2177 2178 /// getOrCreateLimitedType - Get the type from the cache or create a new 2179 /// limited type if necessary. 2180 llvm::DIType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty, 2181 llvm::DIFile *Unit) { 2182 QualType QTy(Ty, 0); 2183 2184 auto *T = cast_or_null<llvm::DICompositeTypeBase>(getTypeOrNull(QTy)); 2185 2186 // We may have cached a forward decl when we could have created 2187 // a non-forward decl. Go ahead and create a non-forward decl 2188 // now. 2189 if (T && !T->isForwardDecl()) 2190 return T; 2191 2192 // Otherwise create the type. 2193 llvm::DICompositeType *Res = CreateLimitedType(Ty); 2194 2195 // Propagate members from the declaration to the definition 2196 // CreateType(const RecordType*) will overwrite this with the members in the 2197 // correct order if the full type is needed. 2198 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray()); 2199 2200 // And update the type cache. 2201 TypeCache[QTy.getAsOpaquePtr()].reset(Res); 2202 return Res; 2203 } 2204 2205 // TODO: Currently used for context chains when limiting debug info. 2206 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) { 2207 RecordDecl *RD = Ty->getDecl(); 2208 2209 // Get overall information about the record type for the debug info. 2210 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation()); 2211 unsigned Line = getLineNumber(RD->getLocation()); 2212 StringRef RDName = getClassName(RD); 2213 2214 llvm::DIScope *RDContext = 2215 getContextDescriptor(cast<Decl>(RD->getDeclContext())); 2216 2217 // If we ended up creating the type during the context chain construction, 2218 // just return that. 2219 auto *T = cast_or_null<llvm::DICompositeType>( 2220 getTypeOrNull(CGM.getContext().getRecordType(RD))); 2221 if (T && (!T->isForwardDecl() || !RD->getDefinition())) 2222 return T; 2223 2224 // If this is just a forward or incomplete declaration, construct an 2225 // appropriately marked node and just return it. 2226 const RecordDecl *D = RD->getDefinition(); 2227 if (!D || !D->isCompleteDefinition()) 2228 return getOrCreateRecordFwdDecl(Ty, RDContext); 2229 2230 uint64_t Size = CGM.getContext().getTypeSize(Ty); 2231 uint64_t Align = CGM.getContext().getTypeAlign(Ty); 2232 2233 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU); 2234 2235 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType( 2236 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0, 2237 FullName); 2238 2239 RegionMap[Ty->getDecl()].reset(RealDecl); 2240 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl); 2241 2242 if (const ClassTemplateSpecializationDecl *TSpecial = 2243 dyn_cast<ClassTemplateSpecializationDecl>(RD)) 2244 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(), 2245 CollectCXXTemplateParams(TSpecial, DefUnit)); 2246 return RealDecl; 2247 } 2248 2249 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD, 2250 llvm::DICompositeType *RealDecl) { 2251 // A class's primary base or the class itself contains the vtable. 2252 llvm::DICompositeType *ContainingType = nullptr; 2253 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); 2254 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { 2255 // Seek non-virtual primary base root. 2256 while (1) { 2257 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); 2258 const CXXRecordDecl *PBT = BRL.getPrimaryBase(); 2259 if (PBT && !BRL.isPrimaryBaseVirtual()) 2260 PBase = PBT; 2261 else 2262 break; 2263 } 2264 ContainingType = cast<llvm::DICompositeType>( 2265 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), 2266 getOrCreateFile(RD->getLocation()))); 2267 } else if (RD->isDynamicClass()) 2268 ContainingType = RealDecl; 2269 2270 DBuilder.replaceVTableHolder(RealDecl, ContainingType); 2271 } 2272 2273 /// CreateMemberType - Create new member and increase Offset by FType's size. 2274 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType, 2275 StringRef Name, uint64_t *Offset) { 2276 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit); 2277 uint64_t FieldSize = CGM.getContext().getTypeSize(FType); 2278 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType); 2279 llvm::DIType *Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, 2280 FieldAlign, *Offset, 0, FieldTy); 2281 *Offset += FieldSize; 2282 return Ty; 2283 } 2284 2285 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit, 2286 StringRef &Name, 2287 StringRef &LinkageName, 2288 llvm::DIScope *&FDContext, 2289 llvm::DINodeArray &TParamsArray, 2290 unsigned &Flags) { 2291 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 2292 Name = getFunctionName(FD); 2293 // Use mangled name as linkage name for C/C++ functions. 2294 if (FD->hasPrototype()) { 2295 LinkageName = CGM.getMangledName(GD); 2296 Flags |= llvm::DINode::FlagPrototyped; 2297 } 2298 // No need to replicate the linkage name if it isn't different from the 2299 // subprogram name, no need to have it at all unless coverage is enabled or 2300 // debug is set to more than just line tables. 2301 if (LinkageName == Name || 2302 (!CGM.getCodeGenOpts().EmitGcovArcs && 2303 !CGM.getCodeGenOpts().EmitGcovNotes && 2304 DebugKind <= CodeGenOptions::DebugLineTablesOnly)) 2305 LinkageName = StringRef(); 2306 2307 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) { 2308 if (const NamespaceDecl *NSDecl = 2309 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) 2310 FDContext = getOrCreateNameSpace(NSDecl); 2311 else if (const RecordDecl *RDecl = 2312 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) 2313 FDContext = getContextDescriptor(cast<Decl>(RDecl)); 2314 // Collect template parameters. 2315 TParamsArray = CollectFunctionTemplateParams(FD, Unit); 2316 } 2317 } 2318 2319 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit, 2320 unsigned &LineNo, QualType &T, 2321 StringRef &Name, StringRef &LinkageName, 2322 llvm::DIScope *&VDContext) { 2323 Unit = getOrCreateFile(VD->getLocation()); 2324 LineNo = getLineNumber(VD->getLocation()); 2325 2326 setLocation(VD->getLocation()); 2327 2328 T = VD->getType(); 2329 if (T->isIncompleteArrayType()) { 2330 // CodeGen turns int[] into int[1] so we'll do the same here. 2331 llvm::APInt ConstVal(32, 1); 2332 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); 2333 2334 T = CGM.getContext().getConstantArrayType(ET, ConstVal, 2335 ArrayType::Normal, 0); 2336 } 2337 2338 Name = VD->getName(); 2339 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) && 2340 !isa<ObjCMethodDecl>(VD->getDeclContext())) 2341 LinkageName = CGM.getMangledName(VD); 2342 if (LinkageName == Name) 2343 LinkageName = StringRef(); 2344 2345 // Since we emit declarations (DW_AT_members) for static members, place the 2346 // definition of those static members in the namespace they were declared in 2347 // in the source code (the lexical decl context). 2348 // FIXME: Generalize this for even non-member global variables where the 2349 // declaration and definition may have different lexical decl contexts, once 2350 // we have support for emitting declarations of (non-member) global variables. 2351 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext() 2352 : VD->getDeclContext(); 2353 // When a record type contains an in-line initialization of a static data 2354 // member, and the record type is marked as __declspec(dllexport), an implicit 2355 // definition of the member will be created in the record context. DWARF 2356 // doesn't seem to have a nice way to describe this in a form that consumers 2357 // are likely to understand, so fake the "normal" situation of a definition 2358 // outside the class by putting it in the global scope. 2359 if (DC->isRecord()) 2360 DC = CGM.getContext().getTranslationUnitDecl(); 2361 VDContext = getContextDescriptor(dyn_cast<Decl>(DC)); 2362 } 2363 2364 llvm::DISubprogram * 2365 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) { 2366 llvm::DINodeArray TParamsArray; 2367 StringRef Name, LinkageName; 2368 unsigned Flags = 0; 2369 SourceLocation Loc = FD->getLocation(); 2370 llvm::DIFile *Unit = getOrCreateFile(Loc); 2371 llvm::DIScope *DContext = Unit; 2372 unsigned Line = getLineNumber(Loc); 2373 2374 collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext, 2375 TParamsArray, Flags); 2376 // Build function type. 2377 SmallVector<QualType, 16> ArgTypes; 2378 for (const ParmVarDecl *Parm: FD->parameters()) 2379 ArgTypes.push_back(Parm->getType()); 2380 QualType FnType = 2381 CGM.getContext().getFunctionType(FD->getReturnType(), ArgTypes, 2382 FunctionProtoType::ExtProtoInfo()); 2383 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl( 2384 DContext, Name, LinkageName, Unit, Line, 2385 getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(), 2386 false /*declaration*/, 0, Flags, CGM.getLangOpts().Optimize, nullptr, 2387 TParamsArray.get(), getFunctionDeclaration(FD)); 2388 const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl()); 2389 FwdDeclReplaceMap.emplace_back(std::piecewise_construct, 2390 std::make_tuple(CanonDecl), 2391 std::make_tuple(SP)); 2392 return SP; 2393 } 2394 2395 llvm::DIGlobalVariable * 2396 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) { 2397 QualType T; 2398 StringRef Name, LinkageName; 2399 SourceLocation Loc = VD->getLocation(); 2400 llvm::DIFile *Unit = getOrCreateFile(Loc); 2401 llvm::DIScope *DContext = Unit; 2402 unsigned Line = getLineNumber(Loc); 2403 2404 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext); 2405 auto *GV = DBuilder.createTempGlobalVariableFwdDecl( 2406 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit), 2407 !VD->isExternallyVisible(), nullptr, nullptr); 2408 FwdDeclReplaceMap.emplace_back( 2409 std::piecewise_construct, 2410 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())), 2411 std::make_tuple(static_cast<llvm::Metadata *>(GV))); 2412 return GV; 2413 } 2414 2415 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { 2416 // We only need a declaration (not a definition) of the type - so use whatever 2417 // we would otherwise do to get a type for a pointee. (forward declarations in 2418 // limited debug info, full definitions (if the type definition is available) 2419 // in unlimited debug info) 2420 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) 2421 return getOrCreateType(CGM.getContext().getTypeDeclType(TD), 2422 getOrCreateFile(TD->getLocation())); 2423 auto I = DeclCache.find(D->getCanonicalDecl()); 2424 2425 if (I != DeclCache.end()) 2426 return dyn_cast_or_null<llvm::DINode>(I->second); 2427 2428 // No definition for now. Emit a forward definition that might be 2429 // merged with a potential upcoming definition. 2430 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 2431 return getFunctionForwardDeclaration(FD); 2432 else if (const auto *VD = dyn_cast<VarDecl>(D)) 2433 return getGlobalVariableForwardDeclaration(VD); 2434 2435 return nullptr; 2436 } 2437 2438 /// getFunctionDeclaration - Return debug info descriptor to describe method 2439 /// declaration for the given method definition. 2440 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) { 2441 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2442 return nullptr; 2443 2444 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 2445 if (!FD) 2446 return nullptr; 2447 2448 // Setup context. 2449 auto *S = getContextDescriptor(cast<Decl>(D->getDeclContext())); 2450 2451 auto MI = SPCache.find(FD->getCanonicalDecl()); 2452 if (MI == SPCache.end()) { 2453 if (const CXXMethodDecl *MD = 2454 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) { 2455 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), 2456 cast<llvm::DICompositeType>(S)); 2457 } 2458 } 2459 if (MI != SPCache.end()) { 2460 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 2461 if (SP && !SP->isDefinition()) 2462 return SP; 2463 } 2464 2465 for (auto NextFD : FD->redecls()) { 2466 auto MI = SPCache.find(NextFD->getCanonicalDecl()); 2467 if (MI != SPCache.end()) { 2468 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); 2469 if (SP && !SP->isDefinition()) 2470 return SP; 2471 } 2472 } 2473 return nullptr; 2474 } 2475 2476 // getOrCreateFunctionType - Construct type. If it is a c++ method, include 2477 // implicit parameter "this". 2478 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D, 2479 QualType FnType, 2480 llvm::DIFile *F) { 2481 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2482 // Create fake but valid subroutine type. Otherwise -verify would fail, and 2483 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields. 2484 return DBuilder.createSubroutineType(F, 2485 DBuilder.getOrCreateTypeArray(None)); 2486 2487 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 2488 return getOrCreateMethodType(Method, F); 2489 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) { 2490 // Add "self" and "_cmd" 2491 SmallVector<llvm::Metadata *, 16> Elts; 2492 2493 // First element is always return type. For 'void' functions it is NULL. 2494 QualType ResultTy = OMethod->getReturnType(); 2495 2496 // Replace the instancetype keyword with the actual type. 2497 if (ResultTy == CGM.getContext().getObjCInstanceType()) 2498 ResultTy = CGM.getContext().getPointerType( 2499 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); 2500 2501 Elts.push_back(getOrCreateType(ResultTy, F)); 2502 // "self" pointer is always first argument. 2503 QualType SelfDeclTy = OMethod->getSelfDecl()->getType(); 2504 Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F))); 2505 // "_cmd" pointer is always second argument. 2506 Elts.push_back(DBuilder.createArtificialType( 2507 getOrCreateType(OMethod->getCmdDecl()->getType(), F))); 2508 // Get rest of the arguments. 2509 for (const auto *PI : OMethod->params()) 2510 Elts.push_back(getOrCreateType(PI->getType(), F)); 2511 // Variadic methods need a special marker at the end of the type list. 2512 if (OMethod->isVariadic()) 2513 Elts.push_back(DBuilder.createUnspecifiedParameter()); 2514 2515 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts); 2516 return DBuilder.createSubroutineType(F, EltTypeArray); 2517 } 2518 2519 // Handle variadic function types; they need an additional 2520 // unspecified parameter. 2521 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2522 if (FD->isVariadic()) { 2523 SmallVector<llvm::Metadata *, 16> EltTys; 2524 EltTys.push_back(getOrCreateType(FD->getReturnType(), F)); 2525 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType)) 2526 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i) 2527 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F)); 2528 EltTys.push_back(DBuilder.createUnspecifiedParameter()); 2529 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys); 2530 return DBuilder.createSubroutineType(F, EltTypeArray); 2531 } 2532 2533 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F)); 2534 } 2535 2536 /// EmitFunctionStart - Constructs the debug code for entering a function. 2537 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc, 2538 SourceLocation ScopeLoc, QualType FnType, 2539 llvm::Function *Fn, CGBuilderTy &Builder) { 2540 2541 StringRef Name; 2542 StringRef LinkageName; 2543 2544 FnBeginRegionCount.push_back(LexicalBlockStack.size()); 2545 2546 const Decl *D = GD.getDecl(); 2547 bool HasDecl = (D != nullptr); 2548 2549 unsigned Flags = 0; 2550 llvm::DIFile *Unit = getOrCreateFile(Loc); 2551 llvm::DIScope *FDContext = Unit; 2552 llvm::DINodeArray TParamsArray; 2553 if (!HasDecl) { 2554 // Use llvm function name. 2555 LinkageName = Fn->getName(); 2556 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2557 // If there is a subprogram for this function available then use it. 2558 auto FI = SPCache.find(FD->getCanonicalDecl()); 2559 if (FI != SPCache.end()) { 2560 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second); 2561 if (SP && SP->isDefinition()) { 2562 LexicalBlockStack.emplace_back(SP); 2563 RegionMap[D].reset(SP); 2564 return; 2565 } 2566 } 2567 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, 2568 TParamsArray, Flags); 2569 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) { 2570 Name = getObjCMethodName(OMD); 2571 Flags |= llvm::DINode::FlagPrototyped; 2572 } else { 2573 // Use llvm function name. 2574 Name = Fn->getName(); 2575 Flags |= llvm::DINode::FlagPrototyped; 2576 } 2577 if (!Name.empty() && Name[0] == '\01') 2578 Name = Name.substr(1); 2579 2580 if (!HasDecl || D->isImplicit()) { 2581 Flags |= llvm::DINode::FlagArtificial; 2582 // Artificial functions without a location should not silently reuse CurLoc. 2583 if (Loc.isInvalid()) 2584 CurLoc = SourceLocation(); 2585 } 2586 unsigned LineNo = getLineNumber(Loc); 2587 unsigned ScopeLine = getLineNumber(ScopeLoc); 2588 2589 // FIXME: The function declaration we're constructing here is mostly reusing 2590 // declarations from CXXMethodDecl and not constructing new ones for arbitrary 2591 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for 2592 // all subprograms instead of the actual context since subprogram definitions 2593 // are emitted as CU level entities by the backend. 2594 llvm::DISubprogram *SP = DBuilder.createFunction( 2595 FDContext, Name, LinkageName, Unit, LineNo, 2596 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(), 2597 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize, Fn, 2598 TParamsArray.get(), getFunctionDeclaration(D)); 2599 // We might get here with a VarDecl in the case we're generating 2600 // code for the initialization of globals. Do not record these decls 2601 // as they will overwrite the actual VarDecl Decl in the cache. 2602 if (HasDecl && isa<FunctionDecl>(D)) 2603 DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP)); 2604 2605 // Push the function onto the lexical block stack. 2606 LexicalBlockStack.emplace_back(SP); 2607 2608 if (HasDecl) 2609 RegionMap[D].reset(SP); 2610 } 2611 2612 /// EmitLocation - Emit metadata to indicate a change in line/column 2613 /// information in the source file. If the location is invalid, the 2614 /// previous location will be reused. 2615 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) { 2616 // Update our current location 2617 setLocation(Loc); 2618 2619 if (CurLoc.isInvalid() || CurLoc.isMacroID()) 2620 return; 2621 2622 llvm::MDNode *Scope = LexicalBlockStack.back(); 2623 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 2624 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope)); 2625 } 2626 2627 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on 2628 /// the stack. 2629 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { 2630 llvm::MDNode *Back = nullptr; 2631 if (!LexicalBlockStack.empty()) 2632 Back = LexicalBlockStack.back().get(); 2633 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock( 2634 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc), 2635 getColumnNumber(CurLoc))); 2636 } 2637 2638 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative 2639 /// region - beginning of a DW_TAG_lexical_block. 2640 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, 2641 SourceLocation Loc) { 2642 // Set our current location. 2643 setLocation(Loc); 2644 2645 // Emit a line table change for the current location inside the new scope. 2646 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get( 2647 getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back())); 2648 2649 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2650 return; 2651 2652 // Create a new lexical block and push it on the stack. 2653 CreateLexicalBlock(Loc); 2654 } 2655 2656 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative 2657 /// region - end of a DW_TAG_lexical_block. 2658 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, 2659 SourceLocation Loc) { 2660 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2661 2662 // Provide an entry in the line table for the end of the block. 2663 EmitLocation(Builder, Loc); 2664 2665 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly) 2666 return; 2667 2668 LexicalBlockStack.pop_back(); 2669 } 2670 2671 /// EmitFunctionEnd - Constructs the debug code for exiting a function. 2672 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) { 2673 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2674 unsigned RCount = FnBeginRegionCount.back(); 2675 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch"); 2676 2677 // Pop all regions for this function. 2678 while (LexicalBlockStack.size() != RCount) { 2679 // Provide an entry in the line table for the end of the block. 2680 EmitLocation(Builder, CurLoc); 2681 LexicalBlockStack.pop_back(); 2682 } 2683 FnBeginRegionCount.pop_back(); 2684 } 2685 2686 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref. 2687 // See BuildByRefType. 2688 llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, 2689 uint64_t *XOffset) { 2690 2691 SmallVector<llvm::Metadata *, 5> EltTys; 2692 QualType FType; 2693 uint64_t FieldSize, FieldOffset; 2694 unsigned FieldAlign; 2695 2696 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 2697 QualType Type = VD->getType(); 2698 2699 FieldOffset = 0; 2700 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2701 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); 2702 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset)); 2703 FType = CGM.getContext().IntTy; 2704 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); 2705 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); 2706 2707 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD); 2708 if (HasCopyAndDispose) { 2709 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2710 EltTys.push_back( 2711 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset)); 2712 EltTys.push_back( 2713 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset)); 2714 } 2715 bool HasByrefExtendedLayout; 2716 Qualifiers::ObjCLifetime Lifetime; 2717 if (CGM.getContext().getByrefLifetime(Type, Lifetime, 2718 HasByrefExtendedLayout) && 2719 HasByrefExtendedLayout) { 2720 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); 2721 EltTys.push_back( 2722 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset)); 2723 } 2724 2725 CharUnits Align = CGM.getContext().getDeclAlign(VD); 2726 if (Align > CGM.getContext().toCharUnitsFromBits( 2727 CGM.getTarget().getPointerAlign(0))) { 2728 CharUnits FieldOffsetInBytes = 2729 CGM.getContext().toCharUnitsFromBits(FieldOffset); 2730 CharUnits AlignedOffsetInBytes = 2731 FieldOffsetInBytes.RoundUpToAlignment(Align); 2732 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes; 2733 2734 if (NumPaddingBytes.isPositive()) { 2735 llvm::APInt pad(32, NumPaddingBytes.getQuantity()); 2736 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy, 2737 pad, ArrayType::Normal, 0); 2738 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset)); 2739 } 2740 } 2741 2742 FType = Type; 2743 llvm::DIType *FieldTy = getOrCreateType(FType, Unit); 2744 FieldSize = CGM.getContext().getTypeSize(FType); 2745 FieldAlign = CGM.getContext().toBits(Align); 2746 2747 *XOffset = FieldOffset; 2748 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize, 2749 FieldAlign, FieldOffset, 0, FieldTy); 2750 EltTys.push_back(FieldTy); 2751 FieldOffset += FieldSize; 2752 2753 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys); 2754 2755 unsigned Flags = llvm::DINode::FlagBlockByrefStruct; 2756 2757 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags, 2758 nullptr, Elements); 2759 } 2760 2761 /// EmitDeclare - Emit local variable declaration debug info. 2762 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::dwarf::Tag Tag, 2763 llvm::Value *Storage, unsigned ArgNo, 2764 CGBuilderTy &Builder) { 2765 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2766 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2767 2768 bool Unwritten = 2769 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) && 2770 cast<Decl>(VD->getDeclContext())->isImplicit()); 2771 llvm::DIFile *Unit = nullptr; 2772 if (!Unwritten) 2773 Unit = getOrCreateFile(VD->getLocation()); 2774 llvm::DIType *Ty; 2775 uint64_t XOffset = 0; 2776 if (VD->hasAttr<BlocksAttr>()) 2777 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2778 else 2779 Ty = getOrCreateType(VD->getType(), Unit); 2780 2781 // If there is no debug info for this type then do not emit debug info 2782 // for this variable. 2783 if (!Ty) 2784 return; 2785 2786 // Get location information. 2787 unsigned Line = 0; 2788 unsigned Column = 0; 2789 if (!Unwritten) { 2790 Line = getLineNumber(VD->getLocation()); 2791 Column = getColumnNumber(VD->getLocation()); 2792 } 2793 SmallVector<int64_t, 9> Expr; 2794 unsigned Flags = 0; 2795 if (VD->isImplicit()) 2796 Flags |= llvm::DINode::FlagArtificial; 2797 // If this is the first argument and it is implicit then 2798 // give it an object pointer flag. 2799 // FIXME: There has to be a better way to do this, but for static 2800 // functions there won't be an implicit param at arg1 and 2801 // otherwise it is 'self' or 'this'. 2802 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1) 2803 Flags |= llvm::DINode::FlagObjectPointer; 2804 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) 2805 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() && 2806 !VD->getType()->isPointerType()) 2807 Expr.push_back(llvm::dwarf::DW_OP_deref); 2808 2809 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back()); 2810 2811 StringRef Name = VD->getName(); 2812 if (!Name.empty()) { 2813 if (VD->hasAttr<BlocksAttr>()) { 2814 CharUnits offset = CharUnits::fromQuantity(32); 2815 Expr.push_back(llvm::dwarf::DW_OP_plus); 2816 // offset of __forwarding field 2817 offset = CGM.getContext().toCharUnitsFromBits( 2818 CGM.getTarget().getPointerWidth(0)); 2819 Expr.push_back(offset.getQuantity()); 2820 Expr.push_back(llvm::dwarf::DW_OP_deref); 2821 Expr.push_back(llvm::dwarf::DW_OP_plus); 2822 // offset of x field 2823 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2824 Expr.push_back(offset.getQuantity()); 2825 2826 // Create the descriptor for the variable. 2827 auto *D = DBuilder.createLocalVariable(Tag, Scope, VD->getName(), Unit, 2828 Line, Ty, ArgNo); 2829 2830 // Insert an llvm.dbg.declare into the current block. 2831 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 2832 llvm::DebugLoc::get(Line, Column, Scope), 2833 Builder.GetInsertBlock()); 2834 return; 2835 } else if (isa<VariableArrayType>(VD->getType())) 2836 Expr.push_back(llvm::dwarf::DW_OP_deref); 2837 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) { 2838 // If VD is an anonymous union then Storage represents value for 2839 // all union fields. 2840 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2841 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { 2842 // GDB has trouble finding local variables in anonymous unions, so we emit 2843 // artifical local variables for each of the members. 2844 // 2845 // FIXME: Remove this code as soon as GDB supports this. 2846 // The debug info verifier in LLVM operates based on the assumption that a 2847 // variable has the same size as its storage and we had to disable the check 2848 // for artificial variables. 2849 for (const auto *Field : RD->fields()) { 2850 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 2851 StringRef FieldName = Field->getName(); 2852 2853 // Ignore unnamed fields. Do not ignore unnamed records. 2854 if (FieldName.empty() && !isa<RecordType>(Field->getType())) 2855 continue; 2856 2857 // Use VarDecl's Tag, Scope and Line number. 2858 auto *D = DBuilder.createLocalVariable( 2859 Tag, Scope, FieldName, Unit, Line, FieldTy, 2860 CGM.getLangOpts().Optimize, Flags | llvm::DINode::FlagArtificial, 2861 ArgNo); 2862 2863 // Insert an llvm.dbg.declare into the current block. 2864 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 2865 llvm::DebugLoc::get(Line, Column, Scope), 2866 Builder.GetInsertBlock()); 2867 } 2868 } 2869 } 2870 2871 // Create the descriptor for the variable. 2872 auto *D = 2873 DBuilder.createLocalVariable(Tag, Scope, Name, Unit, Line, Ty, 2874 CGM.getLangOpts().Optimize, Flags, ArgNo); 2875 2876 // Insert an llvm.dbg.declare into the current block. 2877 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), 2878 llvm::DebugLoc::get(Line, Column, Scope), 2879 Builder.GetInsertBlock()); 2880 } 2881 2882 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, 2883 llvm::Value *Storage, 2884 CGBuilderTy &Builder) { 2885 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2886 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder); 2887 } 2888 2889 /// Look up the completed type for a self pointer in the TypeCache and 2890 /// create a copy of it with the ObjectPointer and Artificial flags 2891 /// set. If the type is not cached, a new one is created. This should 2892 /// never happen though, since creating a type for the implicit self 2893 /// argument implies that we already parsed the interface definition 2894 /// and the ivar declarations in the implementation. 2895 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy, 2896 llvm::DIType *Ty) { 2897 llvm::DIType *CachedTy = getTypeOrNull(QualTy); 2898 if (CachedTy) 2899 Ty = CachedTy; 2900 return DBuilder.createObjectPointerType(Ty); 2901 } 2902 2903 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( 2904 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder, 2905 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) { 2906 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2907 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!"); 2908 2909 if (Builder.GetInsertBlock() == nullptr) 2910 return; 2911 2912 bool isByRef = VD->hasAttr<BlocksAttr>(); 2913 2914 uint64_t XOffset = 0; 2915 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 2916 llvm::DIType *Ty; 2917 if (isByRef) 2918 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset); 2919 else 2920 Ty = getOrCreateType(VD->getType(), Unit); 2921 2922 // Self is passed along as an implicit non-arg variable in a 2923 // block. Mark it as the object pointer. 2924 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self") 2925 Ty = CreateSelfType(VD->getType(), Ty); 2926 2927 // Get location information. 2928 unsigned Line = getLineNumber(VD->getLocation()); 2929 unsigned Column = getColumnNumber(VD->getLocation()); 2930 2931 const llvm::DataLayout &target = CGM.getDataLayout(); 2932 2933 CharUnits offset = CharUnits::fromQuantity( 2934 target.getStructLayout(blockInfo.StructureType) 2935 ->getElementOffset(blockInfo.getCapture(VD).getIndex())); 2936 2937 SmallVector<int64_t, 9> addr; 2938 if (isa<llvm::AllocaInst>(Storage)) 2939 addr.push_back(llvm::dwarf::DW_OP_deref); 2940 addr.push_back(llvm::dwarf::DW_OP_plus); 2941 addr.push_back(offset.getQuantity()); 2942 if (isByRef) { 2943 addr.push_back(llvm::dwarf::DW_OP_deref); 2944 addr.push_back(llvm::dwarf::DW_OP_plus); 2945 // offset of __forwarding field 2946 offset = 2947 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0)); 2948 addr.push_back(offset.getQuantity()); 2949 addr.push_back(llvm::dwarf::DW_OP_deref); 2950 addr.push_back(llvm::dwarf::DW_OP_plus); 2951 // offset of x field 2952 offset = CGM.getContext().toCharUnitsFromBits(XOffset); 2953 addr.push_back(offset.getQuantity()); 2954 } 2955 2956 // Create the descriptor for the variable. 2957 auto *D = DBuilder.createLocalVariable( 2958 llvm::dwarf::DW_TAG_auto_variable, 2959 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit, 2960 Line, Ty); 2961 2962 // Insert an llvm.dbg.declare into the current block. 2963 auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back()); 2964 if (InsertPoint) 2965 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL, 2966 InsertPoint); 2967 else 2968 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL, 2969 Builder.GetInsertBlock()); 2970 } 2971 2972 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument 2973 /// variable declaration. 2974 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, 2975 unsigned ArgNo, 2976 CGBuilderTy &Builder) { 2977 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2978 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder); 2979 } 2980 2981 namespace { 2982 struct BlockLayoutChunk { 2983 uint64_t OffsetInBits; 2984 const BlockDecl::Capture *Capture; 2985 }; 2986 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { 2987 return l.OffsetInBits < r.OffsetInBits; 2988 } 2989 } 2990 2991 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, 2992 llvm::Value *Arg, 2993 unsigned ArgNo, 2994 llvm::Value *LocalAddr, 2995 CGBuilderTy &Builder) { 2996 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 2997 ASTContext &C = CGM.getContext(); 2998 const BlockDecl *blockDecl = block.getBlockDecl(); 2999 3000 // Collect some general information about the block's location. 3001 SourceLocation loc = blockDecl->getCaretLocation(); 3002 llvm::DIFile *tunit = getOrCreateFile(loc); 3003 unsigned line = getLineNumber(loc); 3004 unsigned column = getColumnNumber(loc); 3005 3006 // Build the debug-info type for the block literal. 3007 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext())); 3008 3009 const llvm::StructLayout *blockLayout = 3010 CGM.getDataLayout().getStructLayout(block.StructureType); 3011 3012 SmallVector<llvm::Metadata *, 16> fields; 3013 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public, 3014 blockLayout->getElementOffsetInBits(0), 3015 tunit, tunit)); 3016 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public, 3017 blockLayout->getElementOffsetInBits(1), 3018 tunit, tunit)); 3019 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public, 3020 blockLayout->getElementOffsetInBits(2), 3021 tunit, tunit)); 3022 auto *FnTy = block.getBlockExpr()->getFunctionType(); 3023 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); 3024 fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public, 3025 blockLayout->getElementOffsetInBits(3), 3026 tunit, tunit)); 3027 fields.push_back(createFieldType( 3028 "__descriptor", C.getPointerType(block.NeedsCopyDispose 3029 ? C.getBlockDescriptorExtendedType() 3030 : C.getBlockDescriptorType()), 3031 0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit)); 3032 3033 // We want to sort the captures by offset, not because DWARF 3034 // requires this, but because we're paranoid about debuggers. 3035 SmallVector<BlockLayoutChunk, 8> chunks; 3036 3037 // 'this' capture. 3038 if (blockDecl->capturesCXXThis()) { 3039 BlockLayoutChunk chunk; 3040 chunk.OffsetInBits = 3041 blockLayout->getElementOffsetInBits(block.CXXThisIndex); 3042 chunk.Capture = nullptr; 3043 chunks.push_back(chunk); 3044 } 3045 3046 // Variable captures. 3047 for (const auto &capture : blockDecl->captures()) { 3048 const VarDecl *variable = capture.getVariable(); 3049 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable); 3050 3051 // Ignore constant captures. 3052 if (captureInfo.isConstant()) 3053 continue; 3054 3055 BlockLayoutChunk chunk; 3056 chunk.OffsetInBits = 3057 blockLayout->getElementOffsetInBits(captureInfo.getIndex()); 3058 chunk.Capture = &capture; 3059 chunks.push_back(chunk); 3060 } 3061 3062 // Sort by offset. 3063 llvm::array_pod_sort(chunks.begin(), chunks.end()); 3064 3065 for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(), 3066 e = chunks.end(); 3067 i != e; ++i) { 3068 uint64_t offsetInBits = i->OffsetInBits; 3069 const BlockDecl::Capture *capture = i->Capture; 3070 3071 // If we have a null capture, this must be the C++ 'this' capture. 3072 if (!capture) { 3073 const CXXMethodDecl *method = 3074 cast<CXXMethodDecl>(blockDecl->getNonClosureContext()); 3075 QualType type = method->getThisType(C); 3076 3077 fields.push_back(createFieldType("this", type, 0, loc, AS_public, 3078 offsetInBits, tunit, tunit)); 3079 continue; 3080 } 3081 3082 const VarDecl *variable = capture->getVariable(); 3083 StringRef name = variable->getName(); 3084 3085 llvm::DIType *fieldType; 3086 if (capture->isByRef()) { 3087 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy); 3088 3089 // FIXME: this creates a second copy of this type! 3090 uint64_t xoffset; 3091 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset); 3092 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width); 3093 fieldType = 3094 DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width, 3095 PtrInfo.Align, offsetInBits, 0, fieldType); 3096 } else { 3097 fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public, 3098 offsetInBits, tunit, tunit); 3099 } 3100 fields.push_back(fieldType); 3101 } 3102 3103 SmallString<36> typeName; 3104 llvm::raw_svector_ostream(typeName) << "__block_literal_" 3105 << CGM.getUniqueBlockCount(); 3106 3107 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields); 3108 3109 llvm::DIType *type = DBuilder.createStructType( 3110 tunit, typeName.str(), tunit, line, 3111 CGM.getContext().toBits(block.BlockSize), 3112 CGM.getContext().toBits(block.BlockAlign), 0, nullptr, fieldsArray); 3113 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits); 3114 3115 // Get overall information about the block. 3116 unsigned flags = llvm::DINode::FlagArtificial; 3117 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back()); 3118 3119 // Create the descriptor for the parameter. 3120 auto *debugVar = DBuilder.createLocalVariable( 3121 llvm::dwarf::DW_TAG_arg_variable, scope, Arg->getName(), tunit, line, 3122 type, CGM.getLangOpts().Optimize, flags, ArgNo); 3123 3124 if (LocalAddr) { 3125 // Insert an llvm.dbg.value into the current block. 3126 DBuilder.insertDbgValueIntrinsic( 3127 LocalAddr, 0, debugVar, DBuilder.createExpression(), 3128 llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock()); 3129 } 3130 3131 // Insert an llvm.dbg.declare into the current block. 3132 DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(), 3133 llvm::DebugLoc::get(line, column, scope), 3134 Builder.GetInsertBlock()); 3135 } 3136 3137 /// If D is an out-of-class definition of a static data member of a class, find 3138 /// its corresponding in-class declaration. 3139 llvm::DIDerivedType * 3140 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) { 3141 if (!D->isStaticDataMember()) 3142 return nullptr; 3143 3144 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl()); 3145 if (MI != StaticDataMemberCache.end()) { 3146 assert(MI->second && "Static data member declaration should still exist"); 3147 return cast<llvm::DIDerivedType>(MI->second); 3148 } 3149 3150 // If the member wasn't found in the cache, lazily construct and add it to the 3151 // type (used when a limited form of the type is emitted). 3152 auto DC = D->getDeclContext(); 3153 auto *Ctxt = 3154 cast<llvm::DICompositeType>(getContextDescriptor(cast<Decl>(DC))); 3155 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC)); 3156 } 3157 3158 /// Recursively collect all of the member fields of a global anonymous decl and 3159 /// create static variables for them. The first time this is called it needs 3160 /// to be on a union and then from there we can have additional unnamed fields. 3161 llvm::DIGlobalVariable *CGDebugInfo::CollectAnonRecordDecls( 3162 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo, 3163 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) { 3164 llvm::DIGlobalVariable *GV = nullptr; 3165 3166 for (const auto *Field : RD->fields()) { 3167 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); 3168 StringRef FieldName = Field->getName(); 3169 3170 // Ignore unnamed fields, but recurse into anonymous records. 3171 if (FieldName.empty()) { 3172 const RecordType *RT = dyn_cast<RecordType>(Field->getType()); 3173 if (RT) 3174 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName, 3175 Var, DContext); 3176 continue; 3177 } 3178 // Use VarDecl's Tag, Scope and Line number. 3179 GV = DBuilder.createGlobalVariable(DContext, FieldName, LinkageName, Unit, 3180 LineNo, FieldTy, 3181 Var->hasInternalLinkage(), Var, nullptr); 3182 } 3183 return GV; 3184 } 3185 3186 /// EmitGlobalVariable - Emit information about a global variable. 3187 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 3188 const VarDecl *D) { 3189 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3190 // Create global variable debug descriptor. 3191 llvm::DIFile *Unit = nullptr; 3192 llvm::DIScope *DContext = nullptr; 3193 unsigned LineNo; 3194 StringRef DeclName, LinkageName; 3195 QualType T; 3196 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext); 3197 3198 // Attempt to store one global variable for the declaration - even if we 3199 // emit a lot of fields. 3200 llvm::DIGlobalVariable *GV = nullptr; 3201 3202 // If this is an anonymous union then we'll want to emit a global 3203 // variable for each member of the anonymous union so that it's possible 3204 // to find the name of any field in the union. 3205 if (T->isUnionType() && DeclName.empty()) { 3206 const RecordDecl *RD = cast<RecordType>(T)->getDecl(); 3207 assert(RD->isAnonymousStructOrUnion() && 3208 "unnamed non-anonymous struct or union?"); 3209 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext); 3210 } else { 3211 GV = DBuilder.createGlobalVariable( 3212 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit), 3213 Var->hasInternalLinkage(), Var, 3214 getOrCreateStaticDataMemberDeclarationOrNull(D)); 3215 } 3216 DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV)); 3217 } 3218 3219 /// EmitGlobalVariable - Emit global variable's debug info. 3220 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 3221 llvm::Constant *Init) { 3222 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo); 3223 // Create the descriptor for the variable. 3224 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation()); 3225 StringRef Name = VD->getName(); 3226 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit); 3227 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) { 3228 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext()); 3229 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?"); 3230 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit); 3231 } 3232 // Do not use global variables for enums. 3233 // 3234 // FIXME: why not? 3235 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type) 3236 return; 3237 // Do not emit separate definitions for function local const/statics. 3238 if (isa<FunctionDecl>(VD->getDeclContext())) 3239 return; 3240 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 3241 auto *VarD = cast<VarDecl>(VD); 3242 if (VarD->isStaticDataMember()) { 3243 auto *RD = cast<RecordDecl>(VarD->getDeclContext()); 3244 getContextDescriptor(RD); 3245 // Ensure that the type is retained even though it's otherwise unreferenced. 3246 RetainedTypes.push_back( 3247 CGM.getContext().getRecordType(RD).getAsOpaquePtr()); 3248 return; 3249 } 3250 3251 llvm::DIScope *DContext = 3252 getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext())); 3253 3254 auto &GV = DeclCache[VD]; 3255 if (GV) 3256 return; 3257 GV.reset(DBuilder.createGlobalVariable( 3258 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty, 3259 true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD))); 3260 } 3261 3262 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { 3263 if (!LexicalBlockStack.empty()) 3264 return LexicalBlockStack.back(); 3265 return getContextDescriptor(D); 3266 } 3267 3268 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { 3269 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3270 return; 3271 DBuilder.createImportedModule( 3272 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())), 3273 getOrCreateNameSpace(UD.getNominatedNamespace()), 3274 getLineNumber(UD.getLocation())); 3275 } 3276 3277 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { 3278 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3279 return; 3280 assert(UD.shadow_size() && 3281 "We shouldn't be codegening an invalid UsingDecl containing no decls"); 3282 // Emitting one decl is sufficient - debuggers can detect that this is an 3283 // overloaded name & provide lookup for all the overloads. 3284 const UsingShadowDecl &USD = **UD.shadow_begin(); 3285 if (llvm::DINode *Target = 3286 getDeclarationOrDefinition(USD.getUnderlyingDecl())) 3287 DBuilder.createImportedDeclaration( 3288 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target, 3289 getLineNumber(USD.getLocation())); 3290 } 3291 3292 llvm::DIImportedEntity * 3293 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { 3294 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3295 return nullptr; 3296 auto &VH = NamespaceAliasCache[&NA]; 3297 if (VH) 3298 return cast<llvm::DIImportedEntity>(VH); 3299 llvm::DIImportedEntity *R; 3300 if (const NamespaceAliasDecl *Underlying = 3301 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace())) 3302 // This could cache & dedup here rather than relying on metadata deduping. 3303 R = DBuilder.createImportedDeclaration( 3304 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 3305 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()), 3306 NA.getName()); 3307 else 3308 R = DBuilder.createImportedDeclaration( 3309 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())), 3310 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())), 3311 getLineNumber(NA.getLocation()), NA.getName()); 3312 VH.reset(R); 3313 return R; 3314 } 3315 3316 /// getOrCreateNamesSpace - Return namespace descriptor for the given 3317 /// namespace decl. 3318 llvm::DINamespace * 3319 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) { 3320 NSDecl = NSDecl->getCanonicalDecl(); 3321 auto I = NameSpaceCache.find(NSDecl); 3322 if (I != NameSpaceCache.end()) 3323 return cast<llvm::DINamespace>(I->second); 3324 3325 unsigned LineNo = getLineNumber(NSDecl->getLocation()); 3326 llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation()); 3327 llvm::DIScope *Context = 3328 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext())); 3329 llvm::DINamespace *NS = 3330 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo); 3331 NameSpaceCache[NSDecl].reset(NS); 3332 return NS; 3333 } 3334 3335 void CGDebugInfo::finalize() { 3336 // Creating types might create further types - invalidating the current 3337 // element and the size(), so don't cache/reference them. 3338 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) { 3339 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i]; 3340 llvm::DIType *Ty = E.Type->getDecl()->getDefinition() 3341 ? CreateTypeDefinition(E.Type, E.Unit) 3342 : E.Decl; 3343 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty); 3344 } 3345 3346 for (auto p : ReplaceMap) { 3347 assert(p.second); 3348 auto *Ty = cast<llvm::DIType>(p.second); 3349 assert(Ty->isForwardDecl()); 3350 3351 auto it = TypeCache.find(p.first); 3352 assert(it != TypeCache.end()); 3353 assert(it->second); 3354 3355 DBuilder.replaceTemporary(llvm::TempDIType(Ty), 3356 cast<llvm::DIType>(it->second)); 3357 } 3358 3359 for (const auto &p : FwdDeclReplaceMap) { 3360 assert(p.second); 3361 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second)); 3362 llvm::Metadata *Repl; 3363 3364 auto it = DeclCache.find(p.first); 3365 // If there has been no definition for the declaration, call RAUW 3366 // with ourselves, that will destroy the temporary MDNode and 3367 // replace it with a standard one, avoiding leaking memory. 3368 if (it == DeclCache.end()) 3369 Repl = p.second; 3370 else 3371 Repl = it->second; 3372 3373 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl)); 3374 } 3375 3376 // We keep our own list of retained types, because we need to look 3377 // up the final type in the type cache. 3378 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(), 3379 RE = RetainedTypes.end(); RI != RE; ++RI) 3380 DBuilder.retainType(cast<llvm::DIType>(TypeCache[*RI])); 3381 3382 DBuilder.finalize(); 3383 } 3384 3385 void CGDebugInfo::EmitExplicitCastType(QualType Ty) { 3386 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo) 3387 return; 3388 3389 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile())) 3390 // Don't ignore in case of explicit cast where it is referenced indirectly. 3391 DBuilder.retainType(DieTy); 3392 } 3393