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