1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the debug information generation while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.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;
44 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
45 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
50 CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
55 SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF,
57 : DI(CGF.getDebugInfo()), Builder(B) {
59 SavedLoc = DI->getLocation();
60 DI->CurLoc = SourceLocation();
64 SaveAndRestoreLocation::~SaveAndRestoreLocation() {
66 DI->EmitLocation(Builder, SavedLoc);
69 NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
70 : SaveAndRestoreLocation(CGF, B) {
72 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
75 NoLocation::~NoLocation() {
77 assert(Builder.getCurrentDebugLocation().isUnknown());
80 ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
81 : SaveAndRestoreLocation(CGF, B) {
83 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
86 void ArtificialLocation::Emit() {
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));
98 ArtificialLocation::~ArtificialLocation() {
100 assert(Builder.getCurrentDebugLocation().getLine() == 0);
103 void CGDebugInfo::setLocation(SourceLocation Loc) {
104 // If the new location isn't valid return.
105 if (Loc.isInvalid()) return;
107 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
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;
114 SourceManager &SM = CGM.getContext().getSourceManager();
115 llvm::DIScope Scope(LexicalBlockStack.back());
116 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
118 if (PCLoc.isInvalid() || Scope.getFilename() == PCLoc.getFilename())
121 if (Scope.isLexicalBlockFile()) {
122 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(Scope);
124 = DBuilder.createLexicalBlockFile(LBF.getScope(),
125 getOrCreateFile(CurLoc));
127 LexicalBlockStack.pop_back();
128 LexicalBlockStack.push_back(N);
129 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
131 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
133 LexicalBlockStack.pop_back();
134 LexicalBlockStack.push_back(N);
138 /// getContextDescriptor - Get context info for the decl.
139 llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
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));
151 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
152 return getOrCreateNameSpace(NSDecl);
154 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
155 if (!RDecl->isDependentType())
156 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
157 getOrCreateMainFile());
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();
170 return FII->getName();
172 // Otherwise construct human readable name for debug info.
174 llvm::raw_svector_ostream OS(NS);
177 // Add any template specialization args.
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,
187 // Copy this name on the side and use its reference.
188 return internString(OS.str());
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()) {
210 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
211 ClassTy.print(OS, PrintingPolicy(LangOptions()));
214 OS << ' ' << OMD->getSelector().getAsString() << ']';
216 return internString(OS.str());
219 /// getSelectorName - Return selector name. This is used for debugging
221 StringRef CGDebugInfo::getSelectorName(Selector S) {
222 return internString(S.getAsString());
225 /// getClassName - Get class name including template argument list.
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();
233 SmallString<128> Name;
235 llvm::raw_svector_ostream OS(Name);
236 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
237 /*Qualified*/ false);
240 // Copy this name on the side and use its reference.
241 return internString(Name);
244 /// getOrCreateFile - Get the file debug info descriptor for the input location.
245 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
247 // If Location is not valid then use main input file.
248 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
250 SourceManager &SM = CGM.getContext().getSourceManager();
251 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
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());
257 // Cache the results.
258 const char *fname = PLoc.getFilename();
259 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
260 DIFileCache.find(fname);
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));
268 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
270 DIFileCache[fname] = F;
274 /// getOrCreateMainFile - Get the file info for main compile unit.
275 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
276 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
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())
284 SourceManager &SM = CGM.getContext().getSourceManager();
285 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
286 return PLoc.isValid()? PLoc.getLine() : 0;
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)
295 // If the location is invalid then use the current column.
296 if (Loc.isInvalid() && CurLoc.isInvalid())
298 SourceManager &SM = CGM.getContext().getSourceManager();
299 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
300 return PLoc.isValid()? PLoc.getColumn() : 0;
303 StringRef CGDebugInfo::getCurrentDirname() {
304 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
305 return CGM.getCodeGenOpts().DebugCompilationDir;
307 if (!CWDName.empty())
309 SmallString<256> CWD;
310 llvm::sys::fs::current_path(CWD);
311 return CWDName = internString(CWD);
314 /// CreateCompileUnit - Create new compile unit.
315 void CGDebugInfo::CreateCompileUnit() {
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)
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>";
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();
344 // Save filename string.
345 StringRef Filename = internString(MainFileName);
347 // Save split dwarf file string.
348 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
349 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
351 llvm::dwarf::SourceLanguage LangTag;
352 const LangOptions &LO = CGM.getLangOpts();
355 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
357 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
358 } else if (LO.ObjC1) {
359 LangTag = llvm::dwarf::DW_LANG_ObjC;
361 LangTag = llvm::dwarf::DW_LANG_C99;
363 LangTag = llvm::dwarf::DW_LANG_C89;
366 std::string Producer = getClangFullVersion();
368 // Figure out which version of the ObjC runtime we have.
369 unsigned RuntimeVers = 0;
371 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
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);
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;
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:
402 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
404 getOrCreateMainFile(), 0);
406 case BuiltinType::ObjCId: {
407 // typedef struct objc_class *Class;
408 // typedef struct objc_object {
416 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
418 getOrCreateMainFile(), 0);
420 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
422 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
425 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
426 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
428 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
429 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
432 case BuiltinType::ObjCSel: {
434 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
435 "objc_selector", TheCU,
436 getOrCreateMainFile(), 0);
440 case BuiltinType::OCLImage1d:
441 return getOrCreateStructPtrType("opencl_image1d_t",
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",
452 case BuiltinType::OCLImage2dArray:
453 return getOrCreateStructPtrType("opencl_image2d_array_t",
454 OCLImage2dArrayDITy);
455 case BuiltinType::OCLImage3d:
456 return getOrCreateStructPtrType("opencl_image3d_t",
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",
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;
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;
498 BTName = BT->getName(CGM.getLangOpts());
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);
505 DBuilder.createBasicType(BTName, Size, Align, Encoding);
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;
515 uint64_t Size = CGM.getContext().getTypeSize(Ty);
516 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
518 DBuilder.createBasicType("complex", Size, Align, Encoding);
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);
529 // Ignore these qualifiers for now.
530 Qc.removeObjCGCAttr();
531 Qc.removeAddressSpace();
532 Qc.removeObjCLifetime();
534 // We will create one Derived type for one qualifier and recurse to handle any
536 llvm::dwarf::Tag Tag;
538 Tag = llvm::dwarf::DW_TAG_const_type;
540 } else if (Qc.hasVolatile()) {
541 Tag = llvm::dwarf::DW_TAG_volatile_type;
543 } else if (Qc.hasRestrict()) {
544 Tag = llvm::dwarf::DW_TAG_restrict_type;
547 assert(Qc.empty() && "Unknown type qualifier for debug info");
548 return getOrCreateType(QualType(T, 0), Unit);
551 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
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);
560 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
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);
570 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
571 Ty->getPointeeType(), Unit);
575 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
577 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
578 Ty->getPointeeType(), Unit);
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())
593 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
594 if (CGM.getTarget().getCXXABI().isMicrosoft())
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);
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);
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;
622 assert(RD->isClass());
623 Tag = llvm::dwarf::DW_TAG_class_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)));
634 llvm::DIType CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
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));
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);
649 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
653 llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
654 llvm::DIType &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);
664 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
666 if (BlockLiteralGeneric)
667 return BlockLiteralGeneric;
669 SmallVector<llvm::Value *, 8> EltTys;
670 llvm::DIType FieldTy;
672 uint64_t FieldSize, FieldOffset;
674 llvm::DIArray Elements;
675 llvm::DIType EltTy, DescTy;
678 FType = CGM.getContext().UnsignedLongTy;
679 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
680 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
682 Elements = DBuilder.getOrCreateArray(EltTys);
685 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
686 unsigned LineNo = getLineNumber(CurLoc);
688 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
689 Unit, LineNo, FieldOffset, 0,
690 Flags, llvm::DIType(), Elements);
692 // Bit size, align and offset of the type.
693 uint64_t Size = CGM.getContext().getTypeSize(Ty);
695 DescTy = DBuilder.createPointerType(EltTy, Size);
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));
706 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
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);
715 FieldOffset += FieldSize;
716 Elements = DBuilder.getOrCreateArray(EltTys);
718 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
719 Unit, LineNo, FieldOffset, 0,
720 Flags, llvm::DIType(), Elements);
722 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
723 return BlockLiteralGeneric;
726 llvm::DIType CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, llvm::DIFile Unit) {
727 assert(Ty->isTypeAlias());
728 llvm::DIType Src = getOrCreateType(Ty->getAliasedType(), Unit);
731 llvm::raw_svector_ostream OS(NS);
732 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(), /*qualified*/ false);
734 TemplateSpecializationType::PrintTemplateArgumentList(
735 OS, Ty->getArgs(), Ty->getNumArgs(),
736 CGM.getContext().getPrintingPolicy());
738 TypeAliasDecl *AliasDecl =
739 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
740 ->getTemplatedDecl();
742 SourceLocation Loc = AliasDecl->getLocation();
743 llvm::DIFile File = getOrCreateFile(Loc);
744 unsigned Line = getLineNumber(Loc);
746 llvm::DIDescriptor Ctxt = getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext()));
748 return DBuilder.createTypedef(Src, internString(OS.str()), File, Line, Ctxt);
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
757 SourceLocation Loc = Ty->getDecl()->getLocation();
758 llvm::DIFile File = getOrCreateFile(Loc);
759 unsigned Line = getLineNumber(Loc);
760 const TypedefNameDecl *TyDecl = Ty->getDecl();
762 llvm::DIDescriptor TypedefContext =
763 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
766 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
769 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
771 SmallVector<llvm::Value *, 16> EltTys;
773 // Add the result type at least.
774 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
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());
787 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
788 return DBuilder.createSubroutineType(Unit, EltTypeArray);
792 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
794 uint64_t sizeInBitsOverride,
797 uint64_t offsetInBits,
799 llvm::DIScope scope) {
800 llvm::DIType debugType = getOrCreateType(type, tunit);
802 // Get the location for the field.
803 llvm::DIFile file = getOrCreateFile(loc);
804 unsigned line = getLineNumber(loc);
806 uint64_t sizeInBits = 0;
807 unsigned alignInBits = 0;
808 if (!type->isIncompleteArrayType()) {
809 std::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
811 if (sizeInBitsOverride)
812 sizeInBits = sizeInBitsOverride;
816 if (AS == clang::AS_private)
817 flags |= llvm::DIDescriptor::FlagPrivate;
818 else if (AS == clang::AS_protected)
819 flags |= llvm::DIDescriptor::FlagProtected;
821 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
822 alignInBits, offsetInBits, flags, debugType);
825 /// CollectRecordLambdaFields - Helper for CollectRecordFields.
827 CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
828 SmallVectorImpl<llvm::Value *> &elements,
829 llvm::DIType RecordTy) {
830 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
831 // has the name and the location of the variable so we should iterate over
832 // both concurrently.
833 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
834 RecordDecl::field_iterator Field = CXXDecl->field_begin();
835 unsigned fieldno = 0;
836 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
837 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
838 const LambdaCapture &C = *I;
839 if (C.capturesVariable()) {
840 VarDecl *V = C.getCapturedVar();
841 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
842 StringRef VName = V->getName();
843 uint64_t SizeInBitsOverride = 0;
844 if (Field->isBitField()) {
845 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
846 assert(SizeInBitsOverride && "found named 0-width bitfield");
848 llvm::DIType fieldType
849 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
850 C.getLocation(), Field->getAccess(),
851 layout.getFieldOffset(fieldno), VUnit, RecordTy);
852 elements.push_back(fieldType);
854 // TODO: Need to handle 'this' in some way by probably renaming the
855 // this of the lambda class and having a field member of 'this' or
856 // by using AT_object_pointer for the function and having that be
857 // used as 'this' for semantic references.
858 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
859 FieldDecl *f = *Field;
860 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
861 QualType type = f->getType();
862 llvm::DIType fieldType
863 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
864 layout.getFieldOffset(fieldno), VUnit, RecordTy);
866 elements.push_back(fieldType);
871 /// Helper for CollectRecordFields.
873 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
874 llvm::DIType RecordTy) {
875 // Create the descriptor for the static variable, with or without
876 // constant initializers.
877 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
878 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
880 unsigned LineNumber = getLineNumber(Var->getLocation());
881 StringRef VName = Var->getName();
882 llvm::Constant *C = nullptr;
883 if (Var->getInit()) {
884 const APValue *Value = Var->evaluateValue();
887 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
888 if (Value->isFloat())
889 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
894 AccessSpecifier Access = Var->getAccess();
895 if (Access == clang::AS_private)
896 Flags |= llvm::DIDescriptor::FlagPrivate;
897 else if (Access == clang::AS_protected)
898 Flags |= llvm::DIDescriptor::FlagProtected;
900 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
901 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
902 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
906 /// CollectRecordNormalField - Helper for CollectRecordFields.
908 CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
910 SmallVectorImpl<llvm::Value *> &elements,
911 llvm::DIType RecordTy) {
912 StringRef name = field->getName();
913 QualType type = field->getType();
915 // Ignore unnamed fields unless they're anonymous structs/unions.
916 if (name.empty() && !type->isRecordType())
919 uint64_t SizeInBitsOverride = 0;
920 if (field->isBitField()) {
921 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
922 assert(SizeInBitsOverride && "found named 0-width bitfield");
925 llvm::DIType fieldType
926 = createFieldType(name, type, SizeInBitsOverride,
927 field->getLocation(), field->getAccess(),
928 OffsetInBits, tunit, RecordTy);
930 elements.push_back(fieldType);
933 /// CollectRecordFields - A helper function to collect debug info for
934 /// record fields. This is used while creating debug info entry for a Record.
935 void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
937 SmallVectorImpl<llvm::Value *> &elements,
938 llvm::DICompositeType RecordTy) {
939 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
941 if (CXXDecl && CXXDecl->isLambda())
942 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
944 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
946 // Field number for non-static fields.
947 unsigned fieldNo = 0;
949 // Static and non-static members should appear in the same order as
950 // the corresponding declarations in the source program.
951 for (const auto *I : record->decls())
952 if (const auto *V = dyn_cast<VarDecl>(I)) {
953 // Reuse the existing static member declaration if one exists
954 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
955 StaticDataMemberCache.find(V->getCanonicalDecl());
956 if (MI != StaticDataMemberCache.end()) {
958 "Static data member declaration should still exist");
960 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
962 elements.push_back(CreateRecordStaticField(V, RecordTy));
963 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
964 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
965 tunit, elements, RecordTy);
967 // Bump field number for next field.
973 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
974 /// function type is not updated to include implicit "this" pointer. Use this
975 /// routine to get a method type which includes "this" pointer.
976 llvm::DICompositeType
977 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
979 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
980 if (Method->isStatic())
981 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
982 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
986 llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
987 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
988 // Add "this" pointer.
989 llvm::DIArray Args = llvm::DICompositeType(
990 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
991 assert (Args.getNumElements() && "Invalid number of arguments!");
993 SmallVector<llvm::Value *, 16> Elts;
995 // First element is always return type. For 'void' functions it is NULL.
996 Elts.push_back(Args.getElement(0));
998 // "this" pointer is always first argument.
999 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1000 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1001 // Create pointer type directly in this case.
1002 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1003 QualType PointeeTy = ThisPtrTy->getPointeeType();
1004 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1005 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1006 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1007 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
1008 llvm::DIType ThisPtrType =
1009 DBuilder.createPointerType(PointeeType, Size, Align);
1010 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1011 // TODO: This and the artificial type below are misleading, the
1012 // types aren't artificial the argument is, but the current
1013 // metadata doesn't represent that.
1014 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1015 Elts.push_back(ThisPtrType);
1017 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1018 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1019 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1020 Elts.push_back(ThisPtrType);
1023 // Copy rest of the arguments.
1024 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1025 Elts.push_back(Args.getElement(i));
1027 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1030 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1031 Flags |= llvm::DIDescriptor::FlagLValueReference;
1032 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1033 Flags |= llvm::DIDescriptor::FlagRValueReference;
1035 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
1038 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1039 /// inside a function.
1040 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1041 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1042 return isFunctionLocalClass(NRD);
1043 if (isa<FunctionDecl>(RD->getDeclContext()))
1048 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1049 /// a single member function GlobalDecl.
1051 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1053 llvm::DIType RecordTy) {
1055 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1057 StringRef MethodName = getFunctionName(Method);
1058 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
1060 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1061 // make sense to give a single ctor/dtor a linkage name.
1062 StringRef MethodLinkageName;
1063 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1064 MethodLinkageName = CGM.getMangledName(Method);
1066 // Get the location for the method.
1067 llvm::DIFile MethodDefUnit;
1068 unsigned MethodLine = 0;
1069 if (!Method->isImplicit()) {
1070 MethodDefUnit = getOrCreateFile(Method->getLocation());
1071 MethodLine = getLineNumber(Method->getLocation());
1074 // Collect virtual method info.
1075 llvm::DIType ContainingType;
1076 unsigned Virtuality = 0;
1077 unsigned VIndex = 0;
1079 if (Method->isVirtual()) {
1080 if (Method->isPure())
1081 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1083 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1085 // It doesn't make sense to give a virtual destructor a vtable index,
1086 // since a single destructor has two entries in the vtable.
1087 // FIXME: Add proper support for debug info for virtual calls in
1088 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1089 // lookup if we have multiple or virtual inheritance.
1090 if (!isa<CXXDestructorDecl>(Method) &&
1091 !CGM.getTarget().getCXXABI().isMicrosoft())
1092 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1093 ContainingType = RecordTy;
1097 if (Method->isImplicit())
1098 Flags |= llvm::DIDescriptor::FlagArtificial;
1099 AccessSpecifier Access = Method->getAccess();
1100 if (Access == clang::AS_private)
1101 Flags |= llvm::DIDescriptor::FlagPrivate;
1102 else if (Access == clang::AS_protected)
1103 Flags |= llvm::DIDescriptor::FlagProtected;
1104 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1105 if (CXXC->isExplicit())
1106 Flags |= llvm::DIDescriptor::FlagExplicit;
1107 } else if (const CXXConversionDecl *CXXC =
1108 dyn_cast<CXXConversionDecl>(Method)) {
1109 if (CXXC->isExplicit())
1110 Flags |= llvm::DIDescriptor::FlagExplicit;
1112 if (Method->hasPrototype())
1113 Flags |= llvm::DIDescriptor::FlagPrototyped;
1114 if (Method->getRefQualifier() == RQ_LValue)
1115 Flags |= llvm::DIDescriptor::FlagLValueReference;
1116 if (Method->getRefQualifier() == RQ_RValue)
1117 Flags |= llvm::DIDescriptor::FlagRValueReference;
1119 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1120 llvm::DISubprogram SP =
1121 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1122 MethodDefUnit, MethodLine,
1123 MethodTy, /*isLocalToUnit=*/false,
1124 /* isDefinition=*/ false,
1125 Virtuality, VIndex, ContainingType,
1126 Flags, CGM.getLangOpts().Optimize, nullptr,
1129 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1134 /// CollectCXXMemberFunctions - A helper function to collect debug info for
1135 /// C++ member functions. This is used while creating debug info entry for
1138 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1139 SmallVectorImpl<llvm::Value *> &EltTys,
1140 llvm::DIType RecordTy) {
1142 // Since we want more than just the individual member decls if we
1143 // have templated functions iterate over every declaration to gather
1145 for(const auto *I : RD->decls()) {
1146 if (const auto *Method = dyn_cast<CXXMethodDecl>(I)) {
1147 // Reuse the existing member function declaration if it exists.
1148 // It may be associated with the declaration of the type & should be
1149 // reused as we're building the definition.
1151 // This situation can arise in the vtable-based debug info reduction where
1152 // implicit members are emitted in a non-vtable TU.
1153 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1154 SPCache.find(Method->getCanonicalDecl());
1155 if (MI == SPCache.end()) {
1156 // If the member is implicit, lazily create it when we see the
1157 // definition, not before. (an ODR-used implicit default ctor that's
1158 // never actually code generated should not produce debug info)
1159 if (!Method->isImplicit())
1160 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1162 EltTys.push_back(MI->second);
1163 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(I)) {
1164 // Add any template specializations that have already been seen. Like
1165 // implicit member functions, these may have been added to a declaration
1166 // in the case of vtable-based debug info reduction.
1167 for (const auto *SI : FTD->specializations()) {
1168 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1169 SPCache.find(cast<CXXMethodDecl>(SI)->getCanonicalDecl());
1170 if (MI != SPCache.end())
1171 EltTys.push_back(MI->second);
1177 /// CollectCXXBases - A helper function to collect debug info for
1178 /// C++ base classes. This is used while creating debug info entry for
1181 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1182 SmallVectorImpl<llvm::Value *> &EltTys,
1183 llvm::DIType RecordTy) {
1185 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1186 for (const auto &BI : RD->bases()) {
1187 unsigned BFlags = 0;
1188 uint64_t BaseOffset;
1190 const CXXRecordDecl *Base =
1191 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1193 if (BI.isVirtual()) {
1194 // virtual base offset offset is -ve. The code generator emits dwarf
1195 // expression where it expects +ve number.
1197 0 - CGM.getItaniumVTableContext()
1198 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1199 BFlags = llvm::DIDescriptor::FlagVirtual;
1201 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1202 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1203 // BI->isVirtual() and bits when not.
1205 AccessSpecifier Access = BI.getAccessSpecifier();
1206 if (Access == clang::AS_private)
1207 BFlags |= llvm::DIDescriptor::FlagPrivate;
1208 else if (Access == clang::AS_protected)
1209 BFlags |= llvm::DIDescriptor::FlagProtected;
1212 DBuilder.createInheritance(RecordTy,
1213 getOrCreateType(BI.getType(), Unit),
1214 BaseOffset, BFlags);
1215 EltTys.push_back(DTy);
1219 /// CollectTemplateParams - A helper function to collect template parameters.
1220 llvm::DIArray CGDebugInfo::
1221 CollectTemplateParams(const TemplateParameterList *TPList,
1222 ArrayRef<TemplateArgument> TAList,
1223 llvm::DIFile Unit) {
1224 SmallVector<llvm::Value *, 16> TemplateParams;
1225 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1226 const TemplateArgument &TA = TAList[i];
1229 Name = TPList->getParam(i)->getName();
1230 switch (TA.getKind()) {
1231 case TemplateArgument::Type: {
1232 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1233 llvm::DITemplateTypeParameter TTP =
1234 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
1235 TemplateParams.push_back(TTP);
1237 case TemplateArgument::Integral: {
1238 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1239 llvm::DITemplateValueParameter TVP =
1240 DBuilder.createTemplateValueParameter(
1242 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1243 TemplateParams.push_back(TVP);
1245 case TemplateArgument::Declaration: {
1246 const ValueDecl *D = TA.getAsDecl();
1247 bool InstanceMember = D->isCXXInstanceMember();
1248 QualType T = InstanceMember
1249 ? CGM.getContext().getMemberPointerType(
1250 D->getType(), cast<RecordDecl>(D->getDeclContext())
1252 : CGM.getContext().getPointerType(D->getType());
1253 llvm::DIType TTy = getOrCreateType(T, Unit);
1254 llvm::Value *V = nullptr;
1255 // Variable pointer template parameters have a value that is the address
1257 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1258 V = CGM.GetAddrOfGlobalVar(VD);
1259 // Member function pointers have special support for building them, though
1260 // this is currently unsupported in LLVM CodeGen.
1261 if (InstanceMember) {
1262 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1263 V = CGM.getCXXABI().EmitMemberPointer(method);
1264 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1265 V = CGM.GetAddrOfFunction(FD);
1266 // Member data pointers have special handling too to compute the fixed
1267 // offset within the object.
1268 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
1269 // These five lines (& possibly the above member function pointer
1270 // handling) might be able to be refactored to use similar code in
1271 // CodeGenModule::getMemberPointerConstant
1272 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1274 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1275 V = CGM.getCXXABI().EmitMemberDataPointer(
1276 cast<MemberPointerType>(T.getTypePtr()), chars);
1278 llvm::DITemplateValueParameter TVP =
1279 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1280 V->stripPointerCasts());
1281 TemplateParams.push_back(TVP);
1283 case TemplateArgument::NullPtr: {
1284 QualType T = TA.getNullPtrType();
1285 llvm::DIType TTy = getOrCreateType(T, Unit);
1286 llvm::Value *V = nullptr;
1287 // Special case member data pointer null values since they're actually -1
1289 if (const MemberPointerType *MPT =
1290 dyn_cast<MemberPointerType>(T.getTypePtr()))
1291 // But treat member function pointers as simple zero integers because
1292 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1293 // CodeGen grows handling for values of non-null member function
1294 // pointers then perhaps we could remove this special case and rely on
1295 // EmitNullMemberPointer for member function pointers.
1296 if (MPT->isMemberDataPointer())
1297 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1299 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1300 llvm::DITemplateValueParameter TVP =
1301 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
1302 TemplateParams.push_back(TVP);
1304 case TemplateArgument::Template: {
1305 llvm::DITemplateValueParameter TVP =
1306 DBuilder.createTemplateTemplateParameter(
1307 TheCU, Name, llvm::DIType(),
1308 TA.getAsTemplate().getAsTemplateDecl()
1309 ->getQualifiedNameAsString());
1310 TemplateParams.push_back(TVP);
1312 case TemplateArgument::Pack: {
1313 llvm::DITemplateValueParameter TVP =
1314 DBuilder.createTemplateParameterPack(
1315 TheCU, Name, llvm::DIType(),
1316 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit));
1317 TemplateParams.push_back(TVP);
1319 case TemplateArgument::Expression: {
1320 const Expr *E = TA.getAsExpr();
1321 QualType T = E->getType();
1322 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1323 assert(V && "Expression in template argument isn't constant");
1324 llvm::DIType TTy = getOrCreateType(T, Unit);
1325 llvm::DITemplateValueParameter TVP =
1326 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1327 V->stripPointerCasts());
1328 TemplateParams.push_back(TVP);
1330 // And the following should never occur:
1331 case TemplateArgument::TemplateExpansion:
1332 case TemplateArgument::Null:
1334 "These argument types shouldn't exist in concrete types");
1337 return DBuilder.getOrCreateArray(TemplateParams);
1340 /// CollectFunctionTemplateParams - A helper function to collect debug
1341 /// info for function template parameters.
1342 llvm::DIArray CGDebugInfo::
1343 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1344 if (FD->getTemplatedKind() ==
1345 FunctionDecl::TK_FunctionTemplateSpecialization) {
1346 const TemplateParameterList *TList =
1347 FD->getTemplateSpecializationInfo()->getTemplate()
1348 ->getTemplateParameters();
1349 return CollectTemplateParams(
1350 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1352 return llvm::DIArray();
1355 /// CollectCXXTemplateParams - A helper function to collect debug info for
1356 /// template parameters.
1357 llvm::DIArray CGDebugInfo::
1358 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1359 llvm::DIFile Unit) {
1360 // Always get the full list of parameters, not just the ones from
1361 // the specialization.
1362 TemplateParameterList *TPList =
1363 TSpecial->getSpecializedTemplate()->getTemplateParameters();
1364 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1365 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1368 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1369 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1370 if (VTablePtrType.isValid())
1371 return VTablePtrType;
1373 ASTContext &Context = CGM.getContext();
1376 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1377 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1378 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1379 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1380 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1382 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1383 return VTablePtrType;
1386 /// getVTableName - Get vtable name for the given Class.
1387 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1388 // Copy the gdb compatible name on the side and use its reference.
1389 return internString("_vptr$", RD->getNameAsString());
1393 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1394 /// debug info entry in EltTys vector.
1396 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1397 SmallVectorImpl<llvm::Value *> &EltTys) {
1398 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1400 // If there is a primary base then it will hold vtable info.
1401 if (RL.getPrimaryBase())
1404 // If this class is not dynamic then there is not any vtable info to collect.
1405 if (!RD->isDynamicClass())
1408 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1410 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1412 llvm::DIDescriptor::FlagArtificial,
1413 getOrCreateVTablePtrType(Unit));
1414 EltTys.push_back(VPTR);
1417 /// getOrCreateRecordType - Emit record type's standalone debug info.
1418 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1419 SourceLocation Loc) {
1420 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1421 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1425 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1427 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1428 SourceLocation Loc) {
1429 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1430 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1431 RetainedTypes.push_back(D.getAsOpaquePtr());
1435 void CGDebugInfo::completeType(const EnumDecl *ED) {
1436 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1438 QualType Ty = CGM.getContext().getEnumType(ED);
1439 void* TyPtr = Ty.getAsOpaquePtr();
1440 auto I = TypeCache.find(TyPtr);
1441 if (I == TypeCache.end() ||
1442 !llvm::DIType(cast<llvm::MDNode>(static_cast<llvm::Value *>(I->second)))
1445 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1446 assert(!Res.isForwardDecl());
1447 TypeCache[TyPtr] = Res;
1450 void CGDebugInfo::completeType(const RecordDecl *RD) {
1451 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1452 !CGM.getLangOpts().CPlusPlus)
1453 completeRequiredType(RD);
1456 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1457 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1460 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1461 if (CXXDecl->isDynamicClass())
1464 QualType Ty = CGM.getContext().getRecordType(RD);
1465 llvm::DIType T = getTypeOrNull(Ty);
1466 if (T && T.isForwardDecl())
1467 completeClassData(RD);
1470 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1471 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1473 QualType Ty = CGM.getContext().getRecordType(RD);
1474 void* TyPtr = Ty.getAsOpaquePtr();
1475 auto I = TypeCache.find(TyPtr);
1476 if (I != TypeCache.end() &&
1477 !llvm::DIType(cast<llvm::MDNode>(static_cast<llvm::Value *>(I->second)))
1480 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1481 assert(!Res.isForwardDecl());
1482 TypeCache[TyPtr] = Res;
1485 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1486 CXXRecordDecl::method_iterator End) {
1487 for (; I != End; ++I)
1488 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
1489 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1490 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
1495 static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1496 const RecordDecl *RD,
1497 const LangOptions &LangOpts) {
1498 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1501 if (!LangOpts.CPlusPlus)
1504 if (!RD->isCompleteDefinitionRequired())
1507 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1512 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1515 TemplateSpecializationKind Spec = TSK_Undeclared;
1516 if (const ClassTemplateSpecializationDecl *SD =
1517 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1518 Spec = SD->getSpecializationKind();
1520 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1521 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1522 CXXDecl->method_end()))
1528 /// CreateType - get structure or union type.
1529 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1530 RecordDecl *RD = Ty->getDecl();
1531 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1532 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
1534 T = getOrCreateRecordFwdDecl(
1535 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
1539 return CreateTypeDefinition(Ty);
1542 llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1543 RecordDecl *RD = Ty->getDecl();
1545 // Get overall information about the record type for the debug info.
1546 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1548 // Records and classes and unions can all be recursive. To handle them, we
1549 // first generate a debug descriptor for the struct as a forward declaration.
1550 // Then (if it is a definition) we go through and get debug info for all of
1551 // its members. Finally, we create a descriptor for the complete type (which
1552 // may refer to the forward decl if the struct is recursive) and replace all
1553 // uses of the forward declaration with the final definition.
1555 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
1556 assert(FwdDecl.isCompositeType() &&
1557 "The debug type of a RecordType should be a llvm::DICompositeType");
1559 if (FwdDecl.isForwardDecl())
1562 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1563 CollectContainingType(CXXDecl, FwdDecl);
1565 // Push the struct on region stack.
1566 LexicalBlockStack.push_back(&*FwdDecl);
1567 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1569 // Convert all the elements.
1570 SmallVector<llvm::Value *, 16> EltTys;
1571 // what about nested types?
1573 // Note: The split of CXXDecl information here is intentional, the
1574 // gdb tests will depend on a certain ordering at printout. The debug
1575 // information offsets are still correct if we merge them all together
1577 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1579 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1580 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1583 // Collect data fields (including static variables and any initializers).
1584 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1586 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1588 LexicalBlockStack.pop_back();
1589 RegionMap.erase(Ty->getDecl());
1591 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1592 FwdDecl.setTypeArray(Elements);
1594 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1598 /// CreateType - get objective-c object type.
1599 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1600 llvm::DIFile Unit) {
1601 // Ignore protocols.
1602 return getOrCreateType(Ty->getBaseType(), Unit);
1606 /// \return true if Getter has the default name for the property PD.
1607 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1608 const ObjCMethodDecl *Getter) {
1613 assert(Getter->getDeclName().isObjCZeroArgSelector());
1614 return PD->getName() ==
1615 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1618 /// \return true if Setter has the default name for the property PD.
1619 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1620 const ObjCMethodDecl *Setter) {
1625 assert(Setter->getDeclName().isObjCOneArgSelector());
1626 return SelectorTable::constructSetterName(PD->getName()) ==
1627 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1630 /// CreateType - get objective-c interface type.
1631 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1632 llvm::DIFile Unit) {
1633 ObjCInterfaceDecl *ID = Ty->getDecl();
1635 return llvm::DIType();
1637 // Get overall information about the record type for the debug info.
1638 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1639 unsigned Line = getLineNumber(ID->getLocation());
1640 llvm::dwarf::SourceLanguage RuntimeLang = TheCU.getLanguage();
1642 // If this is just a forward declaration return a special forward-declaration
1643 // debug type since we won't be able to lay out the entire type.
1644 ObjCInterfaceDecl *Def = ID->getDefinition();
1645 if (!Def || !Def->getImplementation()) {
1646 llvm::DIType FwdDecl = DBuilder.createReplaceableForwardDecl(
1647 llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line,
1649 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
1654 return CreateTypeDefinition(Ty, Unit);
1657 llvm::DIType CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty, llvm::DIFile Unit) {
1658 ObjCInterfaceDecl *ID = Ty->getDecl();
1659 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1660 unsigned Line = getLineNumber(ID->getLocation());
1661 unsigned RuntimeLang = TheCU.getLanguage();
1663 // Bit size, align and offset of the type.
1664 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1665 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1668 if (ID->getImplementation())
1669 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1671 llvm::DICompositeType RealDecl =
1672 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1673 Line, Size, Align, Flags,
1674 llvm::DIType(), llvm::DIArray(), RuntimeLang);
1676 QualType QTy(Ty, 0);
1677 TypeCache[QTy.getAsOpaquePtr()] = RealDecl;
1679 // Push the struct on region stack.
1680 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
1681 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1683 // Convert all the elements.
1684 SmallVector<llvm::Value *, 16> EltTys;
1686 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1688 llvm::DIType SClassTy =
1689 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1690 if (!SClassTy.isValid())
1691 return llvm::DIType();
1693 llvm::DIType InhTag =
1694 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1695 EltTys.push_back(InhTag);
1698 // Create entries for all of the properties.
1699 for (const auto *PD : ID->properties()) {
1700 SourceLocation Loc = PD->getLocation();
1701 llvm::DIFile PUnit = getOrCreateFile(Loc);
1702 unsigned PLine = getLineNumber(Loc);
1703 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1704 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1705 llvm::MDNode *PropertyNode =
1706 DBuilder.createObjCProperty(PD->getName(),
1708 hasDefaultGetterName(PD, Getter) ? "" :
1709 getSelectorName(PD->getGetterName()),
1710 hasDefaultSetterName(PD, Setter) ? "" :
1711 getSelectorName(PD->getSetterName()),
1712 PD->getPropertyAttributes(),
1713 getOrCreateType(PD->getType(), PUnit));
1714 EltTys.push_back(PropertyNode);
1717 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1718 unsigned FieldNo = 0;
1719 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1720 Field = Field->getNextIvar(), ++FieldNo) {
1721 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1722 if (!FieldTy.isValid())
1723 return llvm::DIType();
1725 StringRef FieldName = Field->getName();
1727 // Ignore unnamed fields.
1728 if (FieldName.empty())
1731 // Get the location for the field.
1732 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1733 unsigned FieldLine = getLineNumber(Field->getLocation());
1734 QualType FType = Field->getType();
1735 uint64_t FieldSize = 0;
1736 unsigned FieldAlign = 0;
1738 if (!FType->isIncompleteArrayType()) {
1740 // Bit size, align and offset of the type.
1741 FieldSize = Field->isBitField()
1742 ? Field->getBitWidthValue(CGM.getContext())
1743 : CGM.getContext().getTypeSize(FType);
1744 FieldAlign = CGM.getContext().getTypeAlign(FType);
1747 uint64_t FieldOffset;
1748 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1749 // We don't know the runtime offset of an ivar if we're using the
1750 // non-fragile ABI. For bitfields, use the bit offset into the first
1751 // byte of storage of the bitfield. For other fields, use zero.
1752 if (Field->isBitField()) {
1753 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1755 FieldOffset %= CGM.getContext().getCharWidth();
1760 FieldOffset = RL.getFieldOffset(FieldNo);
1764 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1765 Flags = llvm::DIDescriptor::FlagProtected;
1766 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1767 Flags = llvm::DIDescriptor::FlagPrivate;
1769 llvm::MDNode *PropertyNode = nullptr;
1770 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1771 if (ObjCPropertyImplDecl *PImpD =
1772 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1773 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1774 SourceLocation Loc = PD->getLocation();
1775 llvm::DIFile PUnit = getOrCreateFile(Loc);
1776 unsigned PLine = getLineNumber(Loc);
1777 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1778 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1780 DBuilder.createObjCProperty(PD->getName(),
1782 hasDefaultGetterName(PD, Getter) ? "" :
1783 getSelectorName(PD->getGetterName()),
1784 hasDefaultSetterName(PD, Setter) ? "" :
1785 getSelectorName(PD->getSetterName()),
1786 PD->getPropertyAttributes(),
1787 getOrCreateType(PD->getType(), PUnit));
1791 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1792 FieldLine, FieldSize, FieldAlign,
1793 FieldOffset, Flags, FieldTy,
1795 EltTys.push_back(FieldTy);
1798 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1799 RealDecl.setTypeArray(Elements);
1801 LexicalBlockStack.pop_back();
1805 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1806 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1807 int64_t Count = Ty->getNumElements();
1809 // If number of elements are not known then this is an unbounded array.
1810 // Use Count == -1 to express such arrays.
1813 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1814 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1816 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1817 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1819 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1822 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1823 llvm::DIFile Unit) {
1827 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1828 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1831 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1832 } else if (Ty->isIncompleteArrayType()) {
1834 if (Ty->getElementType()->isIncompleteType())
1837 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1838 } else if (Ty->isIncompleteType()) {
1842 // Size and align of the whole array, not the element type.
1843 Size = CGM.getContext().getTypeSize(Ty);
1844 Align = CGM.getContext().getTypeAlign(Ty);
1847 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1848 // interior arrays, do we care? Why aren't nested arrays represented the
1849 // obvious/recursive way?
1850 SmallVector<llvm::Value *, 8> Subscripts;
1851 QualType EltTy(Ty, 0);
1852 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1853 // If the number of elements is known, then count is that number. Otherwise,
1854 // it's -1. This allows us to represent a subrange with an array of 0
1855 // elements, like this:
1860 int64_t Count = -1; // Count == -1 is an unbounded array.
1861 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1862 Count = CAT->getSize().getZExtValue();
1864 // FIXME: Verify this is right for VLAs.
1865 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1866 EltTy = Ty->getElementType();
1869 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1871 llvm::DIType DbgTy =
1872 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1877 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1878 llvm::DIFile Unit) {
1879 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1880 Ty, Ty->getPointeeType(), Unit);
1883 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1884 llvm::DIFile Unit) {
1885 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1886 Ty, Ty->getPointeeType(), Unit);
1889 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1891 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1892 if (!Ty->getPointeeType()->isFunctionType())
1893 return DBuilder.createMemberPointerType(
1894 getOrCreateType(Ty->getPointeeType(), U), ClassType);
1896 const FunctionProtoType *FPT =
1897 Ty->getPointeeType()->getAs<FunctionProtoType>();
1898 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1899 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1900 FPT->getTypeQuals())),
1901 FPT, U), ClassType);
1904 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1906 // Ignore the atomic wrapping
1907 // FIXME: What is the correct representation?
1908 return getOrCreateType(Ty->getValueType(), U);
1911 /// CreateEnumType - get enumeration type.
1912 llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
1913 const EnumDecl *ED = Ty->getDecl();
1916 if (!ED->getTypeForDecl()->isIncompleteType()) {
1917 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1918 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1921 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1923 // If this is just a forward declaration, construct an appropriately
1924 // marked node and just return it.
1925 if (!ED->getDefinition()) {
1926 llvm::DIDescriptor EDContext;
1927 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1928 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1929 unsigned Line = getLineNumber(ED->getLocation());
1930 StringRef EDName = ED->getName();
1931 llvm::DIType RetTy = DBuilder.createReplaceableForwardDecl(
1932 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
1933 0, Size, Align, FullName);
1934 ReplaceMap.push_back(std::make_pair(Ty, static_cast<llvm::Value *>(RetTy)));
1938 return CreateTypeDefinition(Ty);
1941 llvm::DIType CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
1942 const EnumDecl *ED = Ty->getDecl();
1945 if (!ED->getTypeForDecl()->isIncompleteType()) {
1946 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1947 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1950 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1952 // Create DIEnumerator elements for each enumerator.
1953 SmallVector<llvm::Value *, 16> Enumerators;
1954 ED = ED->getDefinition();
1955 for (const auto *Enum : ED->enumerators()) {
1956 Enumerators.push_back(
1957 DBuilder.createEnumerator(Enum->getName(),
1958 Enum->getInitVal().getSExtValue()));
1961 // Return a CompositeType for the enum itself.
1962 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1964 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1965 unsigned Line = getLineNumber(ED->getLocation());
1966 llvm::DIDescriptor EnumContext =
1967 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1968 llvm::DIType ClassTy = ED->isFixed() ?
1969 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1970 llvm::DIType DbgTy =
1971 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1972 Size, Align, EltArray,
1977 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1980 Qualifiers InnerQuals = T.getLocalQualifiers();
1981 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1982 // that is already there.
1983 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1984 Quals += InnerQuals;
1986 switch (T->getTypeClass()) {
1988 return C.getQualifiedType(T.getTypePtr(), Quals);
1989 case Type::TemplateSpecialization: {
1990 const auto *Spec = cast<TemplateSpecializationType>(T);
1991 if (Spec->isTypeAlias())
1992 return C.getQualifiedType(T.getTypePtr(), Quals);
1993 T = Spec->desugar();
1995 case Type::TypeOfExpr:
1996 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1999 T = cast<TypeOfType>(T)->getUnderlyingType();
2001 case Type::Decltype:
2002 T = cast<DecltypeType>(T)->getUnderlyingType();
2004 case Type::UnaryTransform:
2005 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2007 case Type::Attributed:
2008 T = cast<AttributedType>(T)->getEquivalentType();
2010 case Type::Elaborated:
2011 T = cast<ElaboratedType>(T)->getNamedType();
2014 T = cast<ParenType>(T)->getInnerType();
2016 case Type::SubstTemplateTypeParm:
2017 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2020 QualType DT = cast<AutoType>(T)->getDeducedType();
2027 assert(T != LastT && "Type unwrapping failed to unwrap!");
2032 /// getType - Get the type from the cache or return null type if it doesn't
2034 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
2036 // Unwrap the type as needed for debug information.
2037 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2039 auto it = TypeCache.find(Ty.getAsOpaquePtr());
2040 if (it != TypeCache.end()) {
2041 // Verify that the debug info still exists.
2042 if (llvm::Value *V = it->second)
2043 return llvm::DIType(cast<llvm::MDNode>(V));
2046 return llvm::DIType();
2049 void CGDebugInfo::completeTemplateDefinition(
2050 const ClassTemplateSpecializationDecl &SD) {
2051 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2054 completeClassData(&SD);
2055 // In case this type has no member function definitions being emitted, ensure
2057 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2060 /// getOrCreateType - Get the type from the cache or create a new
2061 /// one if necessary.
2062 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
2064 return llvm::DIType();
2066 // Unwrap the type as needed for debug information.
2067 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2069 if (llvm::DIType T = getTypeOrNull(Ty))
2072 // Otherwise create the type.
2073 llvm::DIType Res = CreateTypeNode(Ty, Unit);
2074 void* TyPtr = Ty.getAsOpaquePtr();
2076 // And update the type cache.
2077 TypeCache[TyPtr] = Res;
2082 /// Currently the checksum of an interface includes the number of
2083 /// ivars and property accessors.
2084 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
2085 // The assumption is that the number of ivars can only increase
2086 // monotonically, so it is safe to just use their current number as
2089 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2090 Ivar != nullptr; Ivar = Ivar->getNextIvar())
2096 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2097 switch (Ty->getTypeClass()) {
2098 case Type::ObjCObjectPointer:
2099 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2100 ->getPointeeType());
2101 case Type::ObjCInterface:
2102 return cast<ObjCInterfaceType>(Ty)->getDecl();
2108 /// CreateTypeNode - Create a new debug type node.
2109 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
2110 // Handle qualifiers, which recursively handles what they refer to.
2111 if (Ty.hasLocalQualifiers())
2112 return CreateQualifiedType(Ty, Unit);
2114 const char *Diag = nullptr;
2116 // Work out details of type.
2117 switch (Ty->getTypeClass()) {
2118 #define TYPE(Class, Base)
2119 #define ABSTRACT_TYPE(Class, Base)
2120 #define NON_CANONICAL_TYPE(Class, Base)
2121 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2122 #include "clang/AST/TypeNodes.def"
2123 llvm_unreachable("Dependent types cannot show up in debug information");
2125 case Type::ExtVector:
2127 return CreateType(cast<VectorType>(Ty), Unit);
2128 case Type::ObjCObjectPointer:
2129 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2130 case Type::ObjCObject:
2131 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2132 case Type::ObjCInterface:
2133 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2135 return CreateType(cast<BuiltinType>(Ty));
2137 return CreateType(cast<ComplexType>(Ty));
2139 return CreateType(cast<PointerType>(Ty), Unit);
2140 case Type::Adjusted:
2142 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2144 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
2145 case Type::BlockPointer:
2146 return CreateType(cast<BlockPointerType>(Ty), Unit);
2148 return CreateType(cast<TypedefType>(Ty), Unit);
2150 return CreateType(cast<RecordType>(Ty));
2152 return CreateEnumType(cast<EnumType>(Ty));
2153 case Type::FunctionProto:
2154 case Type::FunctionNoProto:
2155 return CreateType(cast<FunctionType>(Ty), Unit);
2156 case Type::ConstantArray:
2157 case Type::VariableArray:
2158 case Type::IncompleteArray:
2159 return CreateType(cast<ArrayType>(Ty), Unit);
2161 case Type::LValueReference:
2162 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2163 case Type::RValueReference:
2164 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2166 case Type::MemberPointer:
2167 return CreateType(cast<MemberPointerType>(Ty), Unit);
2170 return CreateType(cast<AtomicType>(Ty), Unit);
2172 case Type::TemplateSpecialization:
2173 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2175 case Type::Attributed:
2176 case Type::Elaborated:
2178 case Type::SubstTemplateTypeParm:
2179 case Type::TypeOfExpr:
2181 case Type::Decltype:
2182 case Type::UnaryTransform:
2183 case Type::PackExpansion:
2184 llvm_unreachable("type should have been unwrapped!");
2190 assert(Diag && "Fall through without a diagnostic?");
2191 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2192 "debug information for %0 is not yet supported");
2193 CGM.getDiags().Report(DiagID)
2195 return llvm::DIType();
2198 /// getOrCreateLimitedType - Get the type from the cache or create a new
2199 /// limited type if necessary.
2200 llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2201 llvm::DIFile Unit) {
2202 QualType QTy(Ty, 0);
2204 llvm::DICompositeType T(getTypeOrNull(QTy));
2206 // We may have cached a forward decl when we could have created
2207 // a non-forward decl. Go ahead and create a non-forward decl
2209 if (T && !T.isForwardDecl()) return T;
2211 // Otherwise create the type.
2212 llvm::DICompositeType Res = CreateLimitedType(Ty);
2214 // Propagate members from the declaration to the definition
2215 // CreateType(const RecordType*) will overwrite this with the members in the
2216 // correct order if the full type is needed.
2217 Res.setTypeArray(T.getTypeArray());
2219 // And update the type cache.
2220 TypeCache[QTy.getAsOpaquePtr()] = Res;
2224 // TODO: Currently used for context chains when limiting debug info.
2225 llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2226 RecordDecl *RD = Ty->getDecl();
2228 // Get overall information about the record type for the debug info.
2229 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2230 unsigned Line = getLineNumber(RD->getLocation());
2231 StringRef RDName = getClassName(RD);
2233 llvm::DIDescriptor RDContext =
2234 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2236 // If we ended up creating the type during the context chain construction,
2237 // just return that.
2238 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2239 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
2242 // If this is just a forward or incomplete declaration, construct an
2243 // appropriately marked node and just return it.
2244 const RecordDecl *D = RD->getDefinition();
2245 if (!D || !D->isCompleteDefinition())
2246 return getOrCreateRecordFwdDecl(Ty, RDContext);
2248 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2249 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2250 llvm::DICompositeType RealDecl;
2252 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2255 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
2256 Size, Align, 0, llvm::DIArray(), 0,
2258 else if (RD->isClass()) {
2259 // FIXME: This could be a struct type giving a default visibility different
2260 // than C++ class type, but needs llvm metadata changes first.
2261 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
2262 Size, Align, 0, 0, llvm::DIType(),
2263 llvm::DIArray(), llvm::DIType(),
2264 llvm::DIArray(), FullName);
2266 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
2267 Size, Align, 0, llvm::DIType(),
2268 llvm::DIArray(), 0, llvm::DIType(),
2271 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
2272 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
2274 if (const ClassTemplateSpecializationDecl *TSpecial =
2275 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2276 RealDecl.setTypeArray(llvm::DIArray(),
2277 CollectCXXTemplateParams(TSpecial, DefUnit));
2281 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2282 llvm::DICompositeType RealDecl) {
2283 // A class's primary base or the class itself contains the vtable.
2284 llvm::DICompositeType ContainingType;
2285 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2286 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2287 // Seek non-virtual primary base root.
2289 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2290 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2291 if (PBT && !BRL.isPrimaryBaseVirtual())
2296 ContainingType = llvm::DICompositeType(
2297 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2298 getOrCreateFile(RD->getLocation())));
2299 } else if (RD->isDynamicClass())
2300 ContainingType = RealDecl;
2302 RealDecl.setContainingType(ContainingType);
2305 /// CreateMemberType - Create new member and increase Offset by FType's size.
2306 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2309 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2310 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2311 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2312 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2313 FieldSize, FieldAlign,
2314 *Offset, 0, FieldTy);
2315 *Offset += FieldSize;
2319 llvm::DIScope CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2320 // We only need a declaration (not a definition) of the type - so use whatever
2321 // we would otherwise do to get a type for a pointee. (forward declarations in
2322 // limited debug info, full definitions (if the type definition is available)
2323 // in unlimited debug info)
2324 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2325 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2326 getOrCreateFile(TD->getLocation()));
2327 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2328 // This doesn't handle providing declarations (for functions or variables) for
2329 // entities without definitions in this TU, nor when the definition proceeds
2330 // the call to this function.
2331 // FIXME: This should be split out into more specific maps with support for
2332 // emitting forward declarations and merging definitions with declarations,
2333 // the same way as we do for types.
2334 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2335 DeclCache.find(D->getCanonicalDecl());
2336 if (I == DeclCache.end())
2337 return llvm::DIScope();
2338 llvm::Value *V = I->second;
2339 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
2342 /// getFunctionDeclaration - Return debug info descriptor to describe method
2343 /// declaration for the given method definition.
2344 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2345 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2346 return llvm::DISubprogram();
2348 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2349 if (!FD) return llvm::DISubprogram();
2352 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
2354 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2355 MI = SPCache.find(FD->getCanonicalDecl());
2356 if (MI == SPCache.end()) {
2357 if (const CXXMethodDecl *MD =
2358 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2359 llvm::DICompositeType T(S);
2360 llvm::DISubprogram SP =
2361 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
2365 if (MI != SPCache.end()) {
2366 llvm::Value *V = MI->second;
2367 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2368 if (SP.isSubprogram() && !SP.isDefinition())
2372 for (auto NextFD : FD->redecls()) {
2373 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2374 MI = SPCache.find(NextFD->getCanonicalDecl());
2375 if (MI != SPCache.end()) {
2376 llvm::Value *V = MI->second;
2377 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2378 if (SP.isSubprogram() && !SP.isDefinition())
2382 return llvm::DISubprogram();
2385 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2386 // implicit parameter "this".
2387 llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2390 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2391 // Create fake but valid subroutine type. Otherwise
2392 // llvm::DISubprogram::Verify() would return false, and
2393 // subprogram DIE will miss DW_AT_decl_file and
2394 // DW_AT_decl_line fields.
2395 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
2397 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2398 return getOrCreateMethodType(Method, F);
2399 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2400 // Add "self" and "_cmd"
2401 SmallVector<llvm::Value *, 16> Elts;
2403 // First element is always return type. For 'void' functions it is NULL.
2404 QualType ResultTy = OMethod->getReturnType();
2406 // Replace the instancetype keyword with the actual type.
2407 if (ResultTy == CGM.getContext().getObjCInstanceType())
2408 ResultTy = CGM.getContext().getPointerType(
2409 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2411 Elts.push_back(getOrCreateType(ResultTy, F));
2412 // "self" pointer is always first argument.
2413 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2414 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2415 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
2416 // "_cmd" pointer is always second argument.
2417 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2418 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2419 // Get rest of the arguments.
2420 for (const auto *PI : OMethod->params())
2421 Elts.push_back(getOrCreateType(PI->getType(), F));
2423 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2424 return DBuilder.createSubroutineType(F, EltTypeArray);
2427 // Handle variadic function types; they need an additional
2428 // unspecified parameter.
2429 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2430 if (FD->isVariadic()) {
2431 SmallVector<llvm::Value *, 16> EltTys;
2432 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2433 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2434 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2435 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2436 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2437 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2438 return DBuilder.createSubroutineType(F, EltTypeArray);
2441 return llvm::DICompositeType(getOrCreateType(FnType, F));
2444 /// EmitFunctionStart - Constructs the debug code for entering a function.
2445 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD,
2447 SourceLocation ScopeLoc,
2450 CGBuilderTy &Builder) {
2453 StringRef LinkageName;
2455 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2457 const Decl *D = GD.getDecl();
2458 bool HasDecl = (D != nullptr);
2461 llvm::DIFile Unit = getOrCreateFile(Loc);
2462 llvm::DIDescriptor FDContext(Unit);
2463 llvm::DIArray TParamsArray;
2465 // Use llvm function name.
2466 LinkageName = Fn->getName();
2467 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2468 // If there is a DISubprogram for this function available then use it.
2469 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2470 FI = SPCache.find(FD->getCanonicalDecl());
2471 if (FI != SPCache.end()) {
2472 llvm::Value *V = FI->second;
2473 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2474 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2475 llvm::MDNode *SPN = SP;
2476 LexicalBlockStack.push_back(SPN);
2477 RegionMap[D] = llvm::WeakVH(SP);
2481 Name = getFunctionName(FD);
2482 // Use mangled name as linkage name for C/C++ functions.
2483 if (FD->hasPrototype()) {
2484 LinkageName = CGM.getMangledName(GD);
2485 Flags |= llvm::DIDescriptor::FlagPrototyped;
2487 // No need to replicate the linkage name if it isn't different from the
2488 // subprogram name, no need to have it at all unless coverage is enabled or
2489 // debug is set to more than just line tables.
2490 if (LinkageName == Name ||
2491 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2492 !CGM.getCodeGenOpts().EmitGcovNotes &&
2493 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
2494 LinkageName = StringRef();
2496 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2497 if (const NamespaceDecl *NSDecl =
2498 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2499 FDContext = getOrCreateNameSpace(NSDecl);
2500 else if (const RecordDecl *RDecl =
2501 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2502 FDContext = getContextDescriptor(cast<Decl>(RDecl));
2504 // Collect template parameters.
2505 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2507 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2508 Name = getObjCMethodName(OMD);
2509 Flags |= llvm::DIDescriptor::FlagPrototyped;
2511 // Use llvm function name.
2512 Name = Fn->getName();
2513 Flags |= llvm::DIDescriptor::FlagPrototyped;
2515 if (!Name.empty() && Name[0] == '\01')
2516 Name = Name.substr(1);
2518 if (!HasDecl || D->isImplicit()) {
2519 Flags |= llvm::DIDescriptor::FlagArtificial;
2520 // Artificial functions without a location should not silently reuse CurLoc.
2521 if (Loc.isInvalid())
2522 CurLoc = SourceLocation();
2524 unsigned LineNo = getLineNumber(Loc);
2525 unsigned ScopeLine = getLineNumber(ScopeLoc);
2527 // FIXME: The function declaration we're constructing here is mostly reusing
2528 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2529 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2530 // all subprograms instead of the actual context since subprogram definitions
2531 // are emitted as CU level entities by the backend.
2532 llvm::DISubprogram SP =
2533 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2534 getOrCreateFunctionType(D, FnType, Unit),
2535 Fn->hasInternalLinkage(), true /*definition*/,
2537 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2538 getFunctionDeclaration(D));
2540 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
2542 // Push the function onto the lexical block stack.
2543 llvm::MDNode *SPN = SP;
2544 LexicalBlockStack.push_back(SPN);
2547 RegionMap[D] = llvm::WeakVH(SP);
2550 /// EmitLocation - Emit metadata to indicate a change in line/column
2551 /// information in the source file. If the location is invalid, the
2552 /// previous location will be reused.
2553 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2554 bool ForceColumnInfo) {
2555 // Update our current location
2558 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2560 // Don't bother if things are the same as last time.
2561 SourceManager &SM = CGM.getContext().getSourceManager();
2562 if (CurLoc == PrevLoc ||
2563 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2564 // New Builder may not be in sync with CGDebugInfo.
2565 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2566 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2567 LexicalBlockStack.back())
2570 // Update last state.
2573 llvm::MDNode *Scope = LexicalBlockStack.back();
2574 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2575 (getLineNumber(CurLoc),
2576 getColumnNumber(CurLoc, ForceColumnInfo),
2580 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2582 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2583 llvm::DIDescriptor D = DBuilder.createLexicalBlock(
2584 llvm::DIDescriptor(LexicalBlockStack.empty() ? nullptr
2585 : LexicalBlockStack.back()),
2586 getOrCreateFile(CurLoc), getLineNumber(CurLoc), getColumnNumber(CurLoc),
2588 llvm::MDNode *DN = D;
2589 LexicalBlockStack.push_back(DN);
2592 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2593 /// region - beginning of a DW_TAG_lexical_block.
2594 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2595 SourceLocation Loc) {
2596 // Set our current location.
2599 // Create a new lexical block and push it on the stack.
2600 CreateLexicalBlock(Loc);
2602 // Emit a line table change for the current location inside the new scope.
2603 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2604 getColumnNumber(Loc),
2605 LexicalBlockStack.back()));
2608 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2609 /// region - end of a DW_TAG_lexical_block.
2610 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2611 SourceLocation Loc) {
2612 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2614 // Provide an entry in the line table for the end of the block.
2615 EmitLocation(Builder, Loc);
2617 LexicalBlockStack.pop_back();
2620 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2621 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2622 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2623 unsigned RCount = FnBeginRegionCount.back();
2624 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2626 // Pop all regions for this function.
2627 while (LexicalBlockStack.size() != RCount)
2628 EmitLexicalBlockEnd(Builder, CurLoc);
2629 FnBeginRegionCount.pop_back();
2632 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2633 // See BuildByRefType.
2634 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2635 uint64_t *XOffset) {
2637 SmallVector<llvm::Value *, 5> EltTys;
2639 uint64_t FieldSize, FieldOffset;
2640 unsigned FieldAlign;
2642 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2643 QualType Type = VD->getType();
2646 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2647 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2648 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2649 FType = CGM.getContext().IntTy;
2650 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2651 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2653 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2654 if (HasCopyAndDispose) {
2655 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2656 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2658 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2661 bool HasByrefExtendedLayout;
2662 Qualifiers::ObjCLifetime Lifetime;
2663 if (CGM.getContext().getByrefLifetime(Type,
2664 Lifetime, HasByrefExtendedLayout)
2665 && HasByrefExtendedLayout) {
2666 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2667 EltTys.push_back(CreateMemberType(Unit, FType,
2668 "__byref_variable_layout",
2672 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2673 if (Align > CGM.getContext().toCharUnitsFromBits(
2674 CGM.getTarget().getPointerAlign(0))) {
2675 CharUnits FieldOffsetInBytes
2676 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2677 CharUnits AlignedOffsetInBytes
2678 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2679 CharUnits NumPaddingBytes
2680 = AlignedOffsetInBytes - FieldOffsetInBytes;
2682 if (NumPaddingBytes.isPositive()) {
2683 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2684 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2685 pad, ArrayType::Normal, 0);
2686 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2691 llvm::DIType FieldTy = getOrCreateType(FType, Unit);
2692 FieldSize = CGM.getContext().getTypeSize(FType);
2693 FieldAlign = CGM.getContext().toBits(Align);
2695 *XOffset = FieldOffset;
2696 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2697 0, FieldSize, FieldAlign,
2698 FieldOffset, 0, FieldTy);
2699 EltTys.push_back(FieldTy);
2700 FieldOffset += FieldSize;
2702 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2704 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2706 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2707 llvm::DIType(), Elements);
2710 /// EmitDeclare - Emit local variable declaration debug info.
2711 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::dwarf::LLVMConstants Tag,
2712 llvm::Value *Storage,
2713 unsigned ArgNo, CGBuilderTy &Builder) {
2714 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2715 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2718 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2719 cast<Decl>(VD->getDeclContext())->isImplicit());
2722 Unit = getOrCreateFile(VD->getLocation());
2724 uint64_t XOffset = 0;
2725 if (VD->hasAttr<BlocksAttr>())
2726 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2728 Ty = getOrCreateType(VD->getType(), Unit);
2730 // If there is no debug info for this type then do not emit debug info
2731 // for this variable.
2735 // Get location information.
2737 unsigned Column = 0;
2739 Line = getLineNumber(VD->getLocation());
2740 Column = getColumnNumber(VD->getLocation());
2743 if (VD->isImplicit())
2744 Flags |= llvm::DIDescriptor::FlagArtificial;
2745 // If this is the first argument and it is implicit then
2746 // give it an object pointer flag.
2747 // FIXME: There has to be a better way to do this, but for static
2748 // functions there won't be an implicit param at arg1 and
2749 // otherwise it is 'self' or 'this'.
2750 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2751 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2752 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2753 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2754 !VD->getType()->isPointerType())
2755 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
2757 llvm::MDNode *Scope = LexicalBlockStack.back();
2759 StringRef Name = VD->getName();
2760 if (!Name.empty()) {
2761 if (VD->hasAttr<BlocksAttr>()) {
2762 CharUnits offset = CharUnits::fromQuantity(32);
2763 SmallVector<llvm::Value *, 9> addr;
2764 llvm::Type *Int64Ty = CGM.Int64Ty;
2765 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2766 // offset of __forwarding field
2767 offset = CGM.getContext().toCharUnitsFromBits(
2768 CGM.getTarget().getPointerWidth(0));
2769 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2770 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2771 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2772 // offset of x field
2773 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2774 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2776 // Create the descriptor for the variable.
2777 llvm::DIVariable D =
2778 DBuilder.createComplexVariable(Tag,
2779 llvm::DIDescriptor(Scope),
2780 VD->getName(), Unit, Line, Ty,
2783 // Insert an llvm.dbg.declare into the current block.
2784 llvm::Instruction *Call =
2785 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2786 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2788 } else if (isa<VariableArrayType>(VD->getType()))
2789 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
2790 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2791 // If VD is an anonymous union then Storage represents value for
2792 // all union fields.
2793 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2794 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2795 for (const auto *Field : RD->fields()) {
2796 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2797 StringRef FieldName = Field->getName();
2799 // Ignore unnamed fields. Do not ignore unnamed records.
2800 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2803 // Use VarDecl's Tag, Scope and Line number.
2804 llvm::DIVariable D =
2805 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2806 FieldName, Unit, Line, FieldTy,
2807 CGM.getLangOpts().Optimize, Flags,
2810 // Insert an llvm.dbg.declare into the current block.
2811 llvm::Instruction *Call =
2812 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2813 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2819 // Create the descriptor for the variable.
2820 llvm::DIVariable D =
2821 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2822 Name, Unit, Line, Ty,
2823 CGM.getLangOpts().Optimize, Flags, ArgNo);
2825 // Insert an llvm.dbg.declare into the current block.
2826 llvm::Instruction *Call =
2827 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2828 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2831 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2832 llvm::Value *Storage,
2833 CGBuilderTy &Builder) {
2834 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2835 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2838 /// Look up the completed type for a self pointer in the TypeCache and
2839 /// create a copy of it with the ObjectPointer and Artificial flags
2840 /// set. If the type is not cached, a new one is created. This should
2841 /// never happen though, since creating a type for the implicit self
2842 /// argument implies that we already parsed the interface definition
2843 /// and the ivar declarations in the implementation.
2844 llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2846 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2847 if (CachedTy) Ty = CachedTy;
2848 return DBuilder.createObjectPointerType(Ty);
2851 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2852 llvm::Value *Storage,
2853 CGBuilderTy &Builder,
2854 const CGBlockInfo &blockInfo) {
2855 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2856 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2858 if (Builder.GetInsertBlock() == nullptr)
2861 bool isByRef = VD->hasAttr<BlocksAttr>();
2863 uint64_t XOffset = 0;
2864 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2867 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2869 Ty = getOrCreateType(VD->getType(), Unit);
2871 // Self is passed along as an implicit non-arg variable in a
2872 // block. Mark it as the object pointer.
2873 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2874 Ty = CreateSelfType(VD->getType(), Ty);
2876 // Get location information.
2877 unsigned Line = getLineNumber(VD->getLocation());
2878 unsigned Column = getColumnNumber(VD->getLocation());
2880 const llvm::DataLayout &target = CGM.getDataLayout();
2882 CharUnits offset = CharUnits::fromQuantity(
2883 target.getStructLayout(blockInfo.StructureType)
2884 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2886 SmallVector<llvm::Value *, 9> addr;
2887 llvm::Type *Int64Ty = CGM.Int64Ty;
2888 if (isa<llvm::AllocaInst>(Storage))
2889 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2890 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2891 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2893 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2894 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2895 // offset of __forwarding field
2896 offset = CGM.getContext()
2897 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2898 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2899 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2900 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2901 // offset of x field
2902 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2903 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2906 // Create the descriptor for the variable.
2907 llvm::DIVariable D =
2908 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2909 llvm::DIDescriptor(LexicalBlockStack.back()),
2910 VD->getName(), Unit, Line, Ty, addr);
2912 // Insert an llvm.dbg.declare into the current block.
2913 llvm::Instruction *Call =
2914 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2915 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2916 LexicalBlockStack.back()));
2919 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2920 /// variable declaration.
2921 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2923 CGBuilderTy &Builder) {
2924 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2925 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2929 struct BlockLayoutChunk {
2930 uint64_t OffsetInBits;
2931 const BlockDecl::Capture *Capture;
2933 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2934 return l.OffsetInBits < r.OffsetInBits;
2938 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2940 llvm::Value *LocalAddr,
2941 CGBuilderTy &Builder) {
2942 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2943 ASTContext &C = CGM.getContext();
2944 const BlockDecl *blockDecl = block.getBlockDecl();
2946 // Collect some general information about the block's location.
2947 SourceLocation loc = blockDecl->getCaretLocation();
2948 llvm::DIFile tunit = getOrCreateFile(loc);
2949 unsigned line = getLineNumber(loc);
2950 unsigned column = getColumnNumber(loc);
2952 // Build the debug-info type for the block literal.
2953 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2955 const llvm::StructLayout *blockLayout =
2956 CGM.getDataLayout().getStructLayout(block.StructureType);
2958 SmallVector<llvm::Value*, 16> fields;
2959 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2960 blockLayout->getElementOffsetInBits(0),
2962 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2963 blockLayout->getElementOffsetInBits(1),
2965 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2966 blockLayout->getElementOffsetInBits(2),
2968 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2969 blockLayout->getElementOffsetInBits(3),
2971 fields.push_back(createFieldType("__descriptor",
2972 C.getPointerType(block.NeedsCopyDispose ?
2973 C.getBlockDescriptorExtendedType() :
2974 C.getBlockDescriptorType()),
2976 blockLayout->getElementOffsetInBits(4),
2979 // We want to sort the captures by offset, not because DWARF
2980 // requires this, but because we're paranoid about debuggers.
2981 SmallVector<BlockLayoutChunk, 8> chunks;
2984 if (blockDecl->capturesCXXThis()) {
2985 BlockLayoutChunk chunk;
2986 chunk.OffsetInBits =
2987 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2988 chunk.Capture = nullptr;
2989 chunks.push_back(chunk);
2992 // Variable captures.
2993 for (const auto &capture : blockDecl->captures()) {
2994 const VarDecl *variable = capture.getVariable();
2995 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2997 // Ignore constant captures.
2998 if (captureInfo.isConstant())
3001 BlockLayoutChunk chunk;
3002 chunk.OffsetInBits =
3003 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3004 chunk.Capture = &capture;
3005 chunks.push_back(chunk);
3009 llvm::array_pod_sort(chunks.begin(), chunks.end());
3011 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3012 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3013 uint64_t offsetInBits = i->OffsetInBits;
3014 const BlockDecl::Capture *capture = i->Capture;
3016 // If we have a null capture, this must be the C++ 'this' capture.
3018 const CXXMethodDecl *method =
3019 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3020 QualType type = method->getThisType(C);
3022 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3023 offsetInBits, tunit, tunit));
3027 const VarDecl *variable = capture->getVariable();
3028 StringRef name = variable->getName();
3030 llvm::DIType fieldType;
3031 if (capture->isByRef()) {
3032 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3034 // FIXME: this creates a second copy of this type!
3036 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3037 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3038 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3039 ptrInfo.first, ptrInfo.second,
3040 offsetInBits, 0, fieldType);
3042 fieldType = createFieldType(name, variable->getType(), 0,
3043 loc, AS_public, offsetInBits, tunit, tunit);
3045 fields.push_back(fieldType);
3048 SmallString<36> typeName;
3049 llvm::raw_svector_ostream(typeName)
3050 << "__block_literal_" << CGM.getUniqueBlockCount();
3052 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3055 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3056 CGM.getContext().toBits(block.BlockSize),
3057 CGM.getContext().toBits(block.BlockAlign),
3058 0, llvm::DIType(), fieldsArray);
3059 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3061 // Get overall information about the block.
3062 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3063 llvm::MDNode *scope = LexicalBlockStack.back();
3065 // Create the descriptor for the parameter.
3066 llvm::DIVariable debugVar =
3067 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
3068 llvm::DIDescriptor(scope),
3069 Arg->getName(), tunit, line, type,
3070 CGM.getLangOpts().Optimize, flags,
3071 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3074 // Insert an llvm.dbg.value into the current block.
3075 llvm::Instruction *DbgVal =
3076 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
3077 Builder.GetInsertBlock());
3078 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3081 // Insert an llvm.dbg.declare into the current block.
3082 llvm::Instruction *DbgDecl =
3083 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3084 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3087 /// If D is an out-of-class definition of a static data member of a class, find
3088 /// its corresponding in-class declaration.
3090 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3091 if (!D->isStaticDataMember())
3092 return llvm::DIDerivedType();
3093 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3094 StaticDataMemberCache.find(D->getCanonicalDecl());
3095 if (MI != StaticDataMemberCache.end()) {
3096 assert(MI->second && "Static data member declaration should still exist");
3097 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
3100 // If the member wasn't found in the cache, lazily construct and add it to the
3101 // type (used when a limited form of the type is emitted).
3102 llvm::DICompositeType Ctxt(
3103 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3104 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3108 /// Recursively collect all of the member fields of a global anonymous decl and
3109 /// create static variables for them. The first time this is called it needs
3110 /// to be on a union and then from there we can have additional unnamed fields.
3111 llvm::DIGlobalVariable
3112 CGDebugInfo::CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile Unit,
3113 unsigned LineNo, StringRef LinkageName,
3114 llvm::GlobalVariable *Var,
3115 llvm::DIDescriptor DContext) {
3116 llvm::DIGlobalVariable GV;
3118 for (const auto *Field : RD->fields()) {
3119 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
3120 StringRef FieldName = Field->getName();
3122 // Ignore unnamed fields, but recurse into anonymous records.
3123 if (FieldName.empty()) {
3124 const RecordType *RT = dyn_cast<RecordType>(Field->getType());
3126 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3130 // Use VarDecl's Tag, Scope and Line number.
3131 GV = DBuilder.createStaticVariable(DContext, FieldName, LinkageName, Unit,
3133 Var->hasInternalLinkage(), Var,
3134 llvm::DIDerivedType());
3139 /// EmitGlobalVariable - Emit information about a global variable.
3140 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3142 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3143 // Create global variable debug descriptor.
3144 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3145 unsigned LineNo = getLineNumber(D->getLocation());
3147 setLocation(D->getLocation());
3149 QualType T = D->getType();
3150 if (T->isIncompleteArrayType()) {
3152 // CodeGen turns int[] into int[1] so we'll do the same here.
3153 llvm::APInt ConstVal(32, 1);
3154 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3156 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3157 ArrayType::Normal, 0);
3160 StringRef DeclName = D->getName();
3161 StringRef LinkageName;
3162 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) &&
3163 !isa<ObjCMethodDecl>(D->getDeclContext()))
3164 LinkageName = Var->getName();
3165 if (LinkageName == DeclName)
3166 LinkageName = StringRef();
3168 llvm::DIDescriptor DContext =
3169 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
3171 // Attempt to store one global variable for the declaration - even if we
3172 // emit a lot of fields.
3173 llvm::DIGlobalVariable GV;
3175 // If this is an anonymous union then we'll want to emit a global
3176 // variable for each member of the anonymous union so that it's possible
3177 // to find the name of any field in the union.
3178 if (T->isUnionType() && DeclName.empty()) {
3179 const RecordDecl *RD = cast<RecordType>(T)->getDecl();
3180 assert(RD->isAnonymousStructOrUnion() && "unnamed non-anonymous struct or union?");
3181 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3183 GV = DBuilder.createStaticVariable(
3184 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3185 Var->hasInternalLinkage(), Var,
3186 getOrCreateStaticDataMemberDeclarationOrNull(D));
3188 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
3191 /// EmitGlobalVariable - Emit global variable's debug info.
3192 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3193 llvm::Constant *Init) {
3194 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3195 // Create the descriptor for the variable.
3196 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3197 StringRef Name = VD->getName();
3198 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3199 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3200 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3201 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3202 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3204 // Do not use DIGlobalVariable for enums.
3205 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3207 // Do not emit separate definitions for function local const/statics.
3208 if (isa<FunctionDecl>(VD->getDeclContext()))
3210 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3211 auto pair = DeclCache.insert(std::make_pair(VD, llvm::WeakVH()));
3214 llvm::DIDescriptor DContext =
3215 getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
3216 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3217 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3219 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3220 pair.first->second = llvm::WeakVH(GV);
3223 llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3224 if (!LexicalBlockStack.empty())
3225 return llvm::DIScope(LexicalBlockStack.back());
3226 return getContextDescriptor(D);
3229 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3230 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3232 DBuilder.createImportedModule(
3233 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3234 getOrCreateNameSpace(UD.getNominatedNamespace()),
3235 getLineNumber(UD.getLocation()));
3238 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3239 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3241 assert(UD.shadow_size() &&
3242 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3243 // Emitting one decl is sufficient - debuggers can detect that this is an
3244 // overloaded name & provide lookup for all the overloads.
3245 const UsingShadowDecl &USD = **UD.shadow_begin();
3246 if (llvm::DIScope Target =
3247 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3248 DBuilder.createImportedDeclaration(
3249 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3250 getLineNumber(USD.getLocation()));
3253 llvm::DIImportedEntity
3254 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3255 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3256 return llvm::DIImportedEntity(nullptr);
3257 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3259 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3260 llvm::DIImportedEntity R(nullptr);
3261 if (const NamespaceAliasDecl *Underlying =
3262 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3263 // This could cache & dedup here rather than relying on metadata deduping.
3264 R = DBuilder.createImportedDeclaration(
3265 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3266 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3269 R = DBuilder.createImportedDeclaration(
3270 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3271 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3272 getLineNumber(NA.getLocation()), NA.getName());
3277 /// getOrCreateNamesSpace - Return namespace descriptor for the given
3280 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3281 NSDecl = NSDecl->getCanonicalDecl();
3282 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
3283 NameSpaceCache.find(NSDecl);
3284 if (I != NameSpaceCache.end())
3285 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
3287 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3288 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3289 llvm::DIDescriptor Context =
3290 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3291 llvm::DINameSpace NS =
3292 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3293 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3297 void CGDebugInfo::finalize() {
3298 // Creating types might create further types - invalidating the current
3299 // element and the size(), so don't cache/reference them.
3300 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
3301 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
3302 E.Decl.replaceAllUsesWith(CGM.getLLVMContext(),
3303 E.Type->getDecl()->getDefinition()
3304 ? CreateTypeDefinition(E.Type, E.Unit)
3308 for (auto p : ReplaceMap) {
3310 llvm::DIType Ty(cast<llvm::MDNode>(p.second));
3311 assert(Ty.isForwardDecl());
3313 auto it = TypeCache.find(p.first);
3314 assert(it != TypeCache.end());
3317 llvm::DIType RepTy(cast<llvm::MDNode>(it->second));
3318 Ty.replaceAllUsesWith(CGM.getLLVMContext(), RepTy);
3321 // We keep our own list of retained types, because we need to look
3322 // up the final type in the type cache.
3323 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3324 RE = RetainedTypes.end(); RI != RE; ++RI)
3325 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3327 DBuilder.finalize();