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