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