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