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