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"
\r
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!");
56 NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
57 : DI(CGF.getDebugInfo()), Builder(B) {
59 SavedLoc = DI->getLocation();
60 DI->CurLoc = SourceLocation();
61 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
65 NoLocation::~NoLocation() {
67 assert(Builder.getCurrentDebugLocation().isUnknown());
68 DI->CurLoc = SavedLoc;
72 ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
73 : DI(CGF.getDebugInfo()), Builder(B) {
75 SavedLoc = DI->getLocation();
76 DI->CurLoc = SourceLocation();
77 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
81 void ArtificialLocation::Emit() {
84 DI->EmitLocation(Builder, SavedLoc);
85 DI->CurLoc = SourceLocation();
86 // Construct a location that has a valid scope, but no line info.
87 assert(!DI->LexicalBlockStack.empty());
88 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
89 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
93 ArtificialLocation::~ArtificialLocation() {
95 assert(Builder.getCurrentDebugLocation().getLine() == 0);
96 DI->CurLoc = SavedLoc;
100 void CGDebugInfo::setLocation(SourceLocation Loc) {
101 // If the new location isn't valid return.
102 if (Loc.isInvalid()) return;
104 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
106 // If we've changed files in the middle of a lexical scope go ahead
107 // and create a new lexical scope with file node if it's different
108 // from the one in the scope.
109 if (LexicalBlockStack.empty()) return;
111 SourceManager &SM = CGM.getContext().getSourceManager();
112 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
113 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
115 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
116 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
119 llvm::MDNode *LB = LexicalBlockStack.back();
120 llvm::DIScope Scope = llvm::DIScope(LB);
121 if (Scope.isLexicalBlockFile()) {
122 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
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 const ClassTemplateSpecializationDecl *Spec
229 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
231 return RD->getName();
233 const TemplateArgument *Args;
235 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
236 const TemplateSpecializationType *TST =
237 cast<TemplateSpecializationType>(TAW->getType());
238 Args = TST->getArgs();
239 NumArgs = TST->getNumArgs();
241 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
242 Args = TemplateArgs.data();
243 NumArgs = TemplateArgs.size();
245 StringRef Name = RD->getIdentifier()->getName();
246 PrintingPolicy Policy(CGM.getLangOpts());
247 SmallString<128> TemplateArgList;
249 llvm::raw_svector_ostream OS(TemplateArgList);
250 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
254 // Copy this name on the side and use its reference.
255 return internString(Name, TemplateArgList);
258 /// getOrCreateFile - Get the file debug info descriptor for the input location.
259 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
261 // If Location is not valid then use main input file.
262 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
264 SourceManager &SM = CGM.getContext().getSourceManager();
265 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
267 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
268 // If the location is not valid then use main input file.
269 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
271 // Cache the results.
272 const char *fname = PLoc.getFilename();
273 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
274 DIFileCache.find(fname);
276 if (it != DIFileCache.end()) {
277 // Verify that the information still exists.
278 if (llvm::Value *V = it->second)
279 return llvm::DIFile(cast<llvm::MDNode>(V));
282 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
284 DIFileCache[fname] = F;
288 /// getOrCreateMainFile - Get the file info for main compile unit.
289 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
290 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
293 /// getLineNumber - Get line number for the location. If location is invalid
294 /// then use current location.
295 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
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.getLine() : 0;
303 /// getColumnNumber - Get column number for the location.
304 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
305 // We may not want column information at all.
306 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
309 // If the location is invalid then use the current column.
310 if (Loc.isInvalid() && CurLoc.isInvalid())
312 SourceManager &SM = CGM.getContext().getSourceManager();
313 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
314 return PLoc.isValid()? PLoc.getColumn() : 0;
317 StringRef CGDebugInfo::getCurrentDirname() {
318 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
319 return CGM.getCodeGenOpts().DebugCompilationDir;
321 if (!CWDName.empty())
323 SmallString<256> CWD;
324 llvm::sys::fs::current_path(CWD);
325 return CWDName = internString(CWD);
328 /// CreateCompileUnit - Create new compile unit.
329 void CGDebugInfo::CreateCompileUnit() {
331 // Get absolute path name.
332 SourceManager &SM = CGM.getContext().getSourceManager();
333 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
334 if (MainFileName.empty())
335 MainFileName = "<unknown>";
337 // The main file name provided via the "-main-file-name" option contains just
338 // the file name itself with no path information. This file name may have had
339 // a relative path, so we look into the actual file entry for the main
340 // file to determine the real absolute path for the file.
341 std::string MainFileDir;
342 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
343 MainFileDir = MainFile->getDir()->getName();
344 if (MainFileDir != ".") {
345 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
\r
346 llvm::sys::path::append(MainFileDirSS, MainFileName);
\r
347 MainFileName = MainFileDirSS.str();
\r
351 // Save filename string.
352 StringRef Filename = internString(MainFileName);
354 // Save split dwarf file string.
355 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
356 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
359 const LangOptions &LO = CGM.getLangOpts();
362 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
364 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
365 } else if (LO.ObjC1) {
366 LangTag = llvm::dwarf::DW_LANG_ObjC;
368 LangTag = llvm::dwarf::DW_LANG_C99;
370 LangTag = llvm::dwarf::DW_LANG_C89;
373 std::string Producer = getClangFullVersion();
375 // Figure out which version of the ObjC runtime we have.
376 unsigned RuntimeVers = 0;
378 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
380 // Create new compile unit.
381 // FIXME - Eliminate TheCU.
382 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
383 Producer, LO.Optimize,
384 CGM.getCodeGenOpts().DwarfDebugFlags,
385 RuntimeVers, SplitDwarfFilename);
388 /// CreateType - Get the Basic type from the cache or create a new
389 /// one if necessary.
390 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
391 unsigned Encoding = 0;
393 switch (BT->getKind()) {
394 #define BUILTIN_TYPE(Id, SingletonId)
395 #define PLACEHOLDER_TYPE(Id, SingletonId) \
396 case BuiltinType::Id:
397 #include "clang/AST/BuiltinTypes.def"
398 case BuiltinType::Dependent:
399 llvm_unreachable("Unexpected builtin type");
400 case BuiltinType::NullPtr:
401 return DBuilder.createNullPtrType();
402 case BuiltinType::Void:
403 return llvm::DIType();
404 case BuiltinType::ObjCClass:
407 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
409 getOrCreateMainFile(), 0);
411 case BuiltinType::ObjCId: {
412 // typedef struct objc_class *Class;
413 // typedef struct objc_object {
421 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
423 getOrCreateMainFile(), 0);
425 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
427 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
430 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
431 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
433 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
434 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
437 case BuiltinType::ObjCSel: {
441 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
442 "objc_selector", TheCU, getOrCreateMainFile(),
447 case BuiltinType::OCLImage1d:
448 return getOrCreateStructPtrType("opencl_image1d_t",
450 case BuiltinType::OCLImage1dArray:
451 return getOrCreateStructPtrType("opencl_image1d_array_t",
452 OCLImage1dArrayDITy);
453 case BuiltinType::OCLImage1dBuffer:
454 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
455 OCLImage1dBufferDITy);
456 case BuiltinType::OCLImage2d:
457 return getOrCreateStructPtrType("opencl_image2d_t",
459 case BuiltinType::OCLImage2dArray:
460 return getOrCreateStructPtrType("opencl_image2d_array_t",
461 OCLImage2dArrayDITy);
462 case BuiltinType::OCLImage3d:
463 return getOrCreateStructPtrType("opencl_image3d_t",
465 case BuiltinType::OCLSampler:
466 return DBuilder.createBasicType("opencl_sampler_t",
467 CGM.getContext().getTypeSize(BT),
468 CGM.getContext().getTypeAlign(BT),
469 llvm::dwarf::DW_ATE_unsigned);
470 case BuiltinType::OCLEvent:
471 return getOrCreateStructPtrType("opencl_event_t",
474 case BuiltinType::UChar:
475 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
476 case BuiltinType::Char_S:
477 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
478 case BuiltinType::Char16:
479 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
480 case BuiltinType::UShort:
481 case BuiltinType::UInt:
482 case BuiltinType::UInt128:
483 case BuiltinType::ULong:
484 case BuiltinType::WChar_U:
485 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
486 case BuiltinType::Short:
487 case BuiltinType::Int:
488 case BuiltinType::Int128:
489 case BuiltinType::Long:
490 case BuiltinType::WChar_S:
491 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
492 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
493 case BuiltinType::Half:
494 case BuiltinType::Float:
495 case BuiltinType::LongDouble:
496 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
499 switch (BT->getKind()) {
500 case BuiltinType::Long: BTName = "long int"; break;
501 case BuiltinType::LongLong: BTName = "long long int"; break;
502 case BuiltinType::ULong: BTName = "long unsigned int"; break;
503 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
505 BTName = BT->getName(CGM.getLangOpts());
508 // Bit size, align and offset of the type.
509 uint64_t Size = CGM.getContext().getTypeSize(BT);
510 uint64_t Align = CGM.getContext().getTypeAlign(BT);
512 DBuilder.createBasicType(BTName, Size, Align, Encoding);
516 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
517 // Bit size, align and offset of the type.
518 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
519 if (Ty->isComplexIntegerType())
520 Encoding = llvm::dwarf::DW_ATE_lo_user;
522 uint64_t Size = CGM.getContext().getTypeSize(Ty);
523 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
525 DBuilder.createBasicType("complex", Size, Align, Encoding);
530 /// CreateCVRType - Get the qualified type from the cache or create
531 /// a new one if necessary.
532 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
533 QualifierCollector Qc;
534 const Type *T = Qc.strip(Ty);
536 // Ignore these qualifiers for now.
537 Qc.removeObjCGCAttr();
538 Qc.removeAddressSpace();
539 Qc.removeObjCLifetime();
541 // We will create one Derived type for one qualifier and recurse to handle any
545 Tag = llvm::dwarf::DW_TAG_const_type;
547 } else if (Qc.hasVolatile()) {
548 Tag = llvm::dwarf::DW_TAG_volatile_type;
550 } else if (Qc.hasRestrict()) {
551 Tag = llvm::dwarf::DW_TAG_restrict_type;
554 assert(Qc.empty() && "Unknown type qualifier for debug info");
555 return getOrCreateType(QualType(T, 0), Unit);
558 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
560 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
561 // CVR derived types.
562 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
567 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
570 // The frontend treats 'id' as a typedef to an ObjCObjectType,
571 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
572 // debug info, we want to emit 'id' in both cases.
573 if (Ty->isObjCQualifiedIdType())
574 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
577 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
578 Ty->getPointeeType(), Unit);
582 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
584 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
585 Ty->getPointeeType(), Unit);
588 /// In C++ mode, types have linkage, so we can rely on the ODR and
589 /// on their mangled names, if they're external.
590 static SmallString<256>
591 getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
592 llvm::DICompileUnit TheCU) {
593 SmallString<256> FullName;
594 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
595 // For now, only apply ODR with C++.
596 const TagDecl *TD = Ty->getDecl();
597 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
598 !TD->isExternallyVisible())
600 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
601 if (CGM.getTarget().getCXXABI().isMicrosoft())
604 // TODO: This is using the RTTI name. Is there a better way to get
605 // a unique string for a type?
606 llvm::raw_svector_ostream Out(FullName);
607 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
612 // Creates a forward declaration for a RecordDecl in the given context.
613 llvm::DICompositeType
614 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
615 llvm::DIDescriptor Ctx) {
616 const RecordDecl *RD = Ty->getDecl();
617 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
618 return llvm::DICompositeType(T);
619 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
620 unsigned Line = getLineNumber(RD->getLocation());
621 StringRef RDName = getClassName(RD);
624 if (RD->isStruct() || RD->isInterface())
625 Tag = llvm::dwarf::DW_TAG_structure_type;
626 else if (RD->isUnion())
627 Tag = llvm::dwarf::DW_TAG_union_type;
629 assert(RD->isClass());
630 Tag = llvm::dwarf::DW_TAG_class_type;
634 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
635 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
639 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
643 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
644 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
645 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
647 // Bit size, align and offset of the type.
648 // Size is always the size of a pointer. We can't use getTypeSize here
649 // because that does not return the correct value for references.
650 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
651 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
652 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
654 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
658 llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
659 llvm::DIType &Cache) {
662 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
663 TheCU, getOrCreateMainFile(), 0);
664 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
665 Cache = DBuilder.createPointerType(Cache, Size);
669 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
671 if (BlockLiteralGeneric)
672 return BlockLiteralGeneric;
674 SmallVector<llvm::Value *, 8> EltTys;
675 llvm::DIType FieldTy;
677 uint64_t FieldSize, FieldOffset;
679 llvm::DIArray Elements;
680 llvm::DIType EltTy, DescTy;
683 FType = CGM.getContext().UnsignedLongTy;
684 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
685 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
687 Elements = DBuilder.getOrCreateArray(EltTys);
690 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
691 unsigned LineNo = getLineNumber(CurLoc);
693 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
694 Unit, LineNo, FieldOffset, 0,
695 Flags, llvm::DIType(), Elements);
697 // Bit size, align and offset of the type.
698 uint64_t Size = CGM.getContext().getTypeSize(Ty);
700 DescTy = DBuilder.createPointerType(EltTy, Size);
703 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
704 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
705 FType = CGM.getContext().IntTy;
706 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
707 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
708 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
709 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
711 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
713 FieldSize = CGM.getContext().getTypeSize(Ty);
714 FieldAlign = CGM.getContext().getTypeAlign(Ty);
715 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
716 LineNo, FieldSize, FieldAlign,
717 FieldOffset, 0, FieldTy);
718 EltTys.push_back(FieldTy);
720 FieldOffset += FieldSize;
721 Elements = DBuilder.getOrCreateArray(EltTys);
723 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
724 Unit, LineNo, FieldOffset, 0,
725 Flags, llvm::DIType(), Elements);
727 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
728 return BlockLiteralGeneric;
731 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
732 // Typedefs are derived from some other type. If we have a typedef of a
733 // typedef, make sure to emit the whole chain.
734 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
736 return llvm::DIType();
737 // We don't set size information, but do specify where the typedef was
739 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
740 const TypedefNameDecl *TyDecl = Ty->getDecl();
742 llvm::DIDescriptor TypedefContext =
743 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
746 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
749 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
751 SmallVector<llvm::Value *, 16> EltTys;
753 // Add the result type at least.
754 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
756 // Set up remainder of arguments if there is a prototype.
757 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
758 if (isa<FunctionNoProtoType>(Ty))
759 EltTys.push_back(DBuilder.createUnspecifiedParameter());
760 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
761 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
762 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
765 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
766 return DBuilder.createSubroutineType(Unit, EltTypeArray);
770 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
772 uint64_t sizeInBitsOverride,
775 uint64_t offsetInBits,
777 llvm::DIScope scope) {
778 llvm::DIType debugType = getOrCreateType(type, tunit);
780 // Get the location for the field.
781 llvm::DIFile file = getOrCreateFile(loc);
782 unsigned line = getLineNumber(loc);
784 uint64_t sizeInBits = 0;
785 unsigned alignInBits = 0;
786 if (!type->isIncompleteArrayType()) {
787 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
789 if (sizeInBitsOverride)
790 sizeInBits = sizeInBitsOverride;
794 if (AS == clang::AS_private)
795 flags |= llvm::DIDescriptor::FlagPrivate;
796 else if (AS == clang::AS_protected)
797 flags |= llvm::DIDescriptor::FlagProtected;
799 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
800 alignInBits, offsetInBits, flags, debugType);
803 /// CollectRecordLambdaFields - Helper for CollectRecordFields.
805 CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
806 SmallVectorImpl<llvm::Value *> &elements,
807 llvm::DIType RecordTy) {
808 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
809 // has the name and the location of the variable so we should iterate over
810 // both concurrently.
811 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
812 RecordDecl::field_iterator Field = CXXDecl->field_begin();
813 unsigned fieldno = 0;
814 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
815 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
816 const LambdaExpr::Capture C = *I;
817 if (C.capturesVariable()) {
818 VarDecl *V = C.getCapturedVar();
819 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
820 StringRef VName = V->getName();
821 uint64_t SizeInBitsOverride = 0;
822 if (Field->isBitField()) {
823 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
824 assert(SizeInBitsOverride && "found named 0-width bitfield");
826 llvm::DIType fieldType
827 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
828 C.getLocation(), Field->getAccess(),
829 layout.getFieldOffset(fieldno), VUnit, RecordTy);
830 elements.push_back(fieldType);
832 // TODO: Need to handle 'this' in some way by probably renaming the
833 // this of the lambda class and having a field member of 'this' or
834 // by using AT_object_pointer for the function and having that be
835 // used as 'this' for semantic references.
836 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
837 FieldDecl *f = *Field;
838 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
839 QualType type = f->getType();
840 llvm::DIType fieldType
841 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
842 layout.getFieldOffset(fieldno), VUnit, RecordTy);
844 elements.push_back(fieldType);
849 /// Helper for CollectRecordFields.
851 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
852 llvm::DIType RecordTy) {
853 // Create the descriptor for the static variable, with or without
854 // constant initializers.
855 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
856 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
858 unsigned LineNumber = getLineNumber(Var->getLocation());
859 StringRef VName = Var->getName();
860 llvm::Constant *C = NULL;
861 if (Var->getInit()) {
862 const APValue *Value = Var->evaluateValue();
865 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
866 if (Value->isFloat())
867 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
872 AccessSpecifier Access = Var->getAccess();
873 if (Access == clang::AS_private)
874 Flags |= llvm::DIDescriptor::FlagPrivate;
875 else if (Access == clang::AS_protected)
876 Flags |= llvm::DIDescriptor::FlagProtected;
878 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
879 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
880 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
884 /// CollectRecordNormalField - Helper for CollectRecordFields.
886 CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
888 SmallVectorImpl<llvm::Value *> &elements,
889 llvm::DIType RecordTy) {
890 StringRef name = field->getName();
891 QualType type = field->getType();
893 // Ignore unnamed fields unless they're anonymous structs/unions.
894 if (name.empty() && !type->isRecordType())
897 uint64_t SizeInBitsOverride = 0;
898 if (field->isBitField()) {
899 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
900 assert(SizeInBitsOverride && "found named 0-width bitfield");
903 llvm::DIType fieldType
904 = createFieldType(name, type, SizeInBitsOverride,
905 field->getLocation(), field->getAccess(),
906 OffsetInBits, tunit, RecordTy);
908 elements.push_back(fieldType);
911 /// CollectRecordFields - A helper function to collect debug info for
912 /// record fields. This is used while creating debug info entry for a Record.
913 void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
915 SmallVectorImpl<llvm::Value *> &elements,
916 llvm::DICompositeType RecordTy) {
917 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
919 if (CXXDecl && CXXDecl->isLambda())
920 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
922 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
924 // Field number for non-static fields.
925 unsigned fieldNo = 0;
927 // Static and non-static members should appear in the same order as
928 // the corresponding declarations in the source program.
929 for (RecordDecl::decl_iterator I = record->decls_begin(),
930 E = record->decls_end(); I != E; ++I)
931 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
932 // Reuse the existing static member declaration if one exists
933 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
934 StaticDataMemberCache.find(V->getCanonicalDecl());
935 if (MI != StaticDataMemberCache.end()) {
937 "Static data member declaration should still exist");
939 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
941 elements.push_back(CreateRecordStaticField(V, RecordTy));
942 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
943 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
944 tunit, elements, RecordTy);
946 // Bump field number for next field.
952 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
953 /// function type is not updated to include implicit "this" pointer. Use this
954 /// routine to get a method type which includes "this" pointer.
955 llvm::DICompositeType
956 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
958 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
959 if (Method->isStatic())
960 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
961 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
965 llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
966 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
967 // Add "this" pointer.
968 llvm::DIArray Args = llvm::DICompositeType(
969 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
970 assert (Args.getNumElements() && "Invalid number of arguments!");
972 SmallVector<llvm::Value *, 16> Elts;
974 // First element is always return type. For 'void' functions it is NULL.
975 Elts.push_back(Args.getElement(0));
977 // "this" pointer is always first argument.
978 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
979 if (isa<ClassTemplateSpecializationDecl>(RD)) {
980 // Create pointer type directly in this case.
981 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
982 QualType PointeeTy = ThisPtrTy->getPointeeType();
983 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
984 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
985 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
986 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
987 llvm::DIType ThisPtrType =
988 DBuilder.createPointerType(PointeeType, Size, Align);
989 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
990 // TODO: This and the artificial type below are misleading, the
991 // types aren't artificial the argument is, but the current
992 // metadata doesn't represent that.
993 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
994 Elts.push_back(ThisPtrType);
996 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
997 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
998 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
999 Elts.push_back(ThisPtrType);
1002 // Copy rest of the arguments.
1003 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1004 Elts.push_back(Args.getElement(i));
1006 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1008 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1011 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1012 /// inside a function.
1013 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1014 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1015 return isFunctionLocalClass(NRD);
1016 if (isa<FunctionDecl>(RD->getDeclContext()))
1021 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1022 /// a single member function GlobalDecl.
1024 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1026 llvm::DIType RecordTy) {
1028 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1030 StringRef MethodName = getFunctionName(Method);
1031 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
1033 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1034 // make sense to give a single ctor/dtor a linkage name.
1035 StringRef MethodLinkageName;
1036 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1037 MethodLinkageName = CGM.getMangledName(Method);
1039 // Get the location for the method.
1040 llvm::DIFile MethodDefUnit;
1041 unsigned MethodLine = 0;
1042 if (!Method->isImplicit()) {
1043 MethodDefUnit = getOrCreateFile(Method->getLocation());
1044 MethodLine = getLineNumber(Method->getLocation());
1047 // Collect virtual method info.
1048 llvm::DIType ContainingType;
1049 unsigned Virtuality = 0;
1050 unsigned VIndex = 0;
1052 if (Method->isVirtual()) {
1053 if (Method->isPure())
1054 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1056 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1058 // It doesn't make sense to give a virtual destructor a vtable index,
1059 // since a single destructor has two entries in the vtable.
1060 // FIXME: Add proper support for debug info for virtual calls in
1061 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1062 // lookup if we have multiple or virtual inheritance.
1063 if (!isa<CXXDestructorDecl>(Method) &&
1064 !CGM.getTarget().getCXXABI().isMicrosoft())
1065 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1066 ContainingType = RecordTy;
1070 if (Method->isImplicit())
1071 Flags |= llvm::DIDescriptor::FlagArtificial;
1072 AccessSpecifier Access = Method->getAccess();
1073 if (Access == clang::AS_private)
1074 Flags |= llvm::DIDescriptor::FlagPrivate;
1075 else if (Access == clang::AS_protected)
1076 Flags |= llvm::DIDescriptor::FlagProtected;
1077 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1078 if (CXXC->isExplicit())
1079 Flags |= llvm::DIDescriptor::FlagExplicit;
1080 } else if (const CXXConversionDecl *CXXC =
1081 dyn_cast<CXXConversionDecl>(Method)) {
1082 if (CXXC->isExplicit())
1083 Flags |= llvm::DIDescriptor::FlagExplicit;
1085 if (Method->hasPrototype())
1086 Flags |= llvm::DIDescriptor::FlagPrototyped;
1088 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1089 llvm::DISubprogram SP =
1090 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1091 MethodDefUnit, MethodLine,
1092 MethodTy, /*isLocalToUnit=*/false,
1093 /* isDefinition=*/ false,
1094 Virtuality, VIndex, ContainingType,
1095 Flags, CGM.getLangOpts().Optimize, NULL,
1098 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1103 /// CollectCXXMemberFunctions - A helper function to collect debug info for
1104 /// C++ member functions. This is used while creating debug info entry for
1107 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1108 SmallVectorImpl<llvm::Value *> &EltTys,
1109 llvm::DIType RecordTy) {
1111 // Since we want more than just the individual member decls if we
1112 // have templated functions iterate over every declaration to gather
1114 for(DeclContext::decl_iterator I = RD->decls_begin(),
1115 E = RD->decls_end(); I != E; ++I) {
1116 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
1117 // Reuse the existing member function declaration if it exists.
1118 // It may be associated with the declaration of the type & should be
1119 // reused as we're building the definition.
1121 // This situation can arise in the vtable-based debug info reduction where
1122 // implicit members are emitted in a non-vtable TU.
1123 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1124 SPCache.find(Method->getCanonicalDecl());
1125 if (MI == SPCache.end()) {
1126 // If the member is implicit, lazily create it when we see the
1127 // definition, not before. (an ODR-used implicit default ctor that's
1128 // never actually code generated should not produce debug info)
1129 if (!Method->isImplicit())
1130 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1132 EltTys.push_back(MI->second);
1133 } else if (const FunctionTemplateDecl *FTD =
1134 dyn_cast<FunctionTemplateDecl>(*I)) {
1135 // Add any template specializations that have already been seen. Like
1136 // implicit member functions, these may have been added to a declaration
1137 // in the case of vtable-based debug info reduction.
1138 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1139 SE = FTD->spec_end();
1141 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1142 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1143 if (MI != SPCache.end())
1144 EltTys.push_back(MI->second);
1150 /// CollectCXXBases - A helper function to collect debug info for
1151 /// C++ base classes. This is used while creating debug info entry for
1154 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1155 SmallVectorImpl<llvm::Value *> &EltTys,
1156 llvm::DIType RecordTy) {
1158 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1159 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1160 BE = RD->bases_end(); BI != BE; ++BI) {
1161 unsigned BFlags = 0;
1162 uint64_t BaseOffset;
1164 const CXXRecordDecl *Base =
1165 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1167 if (BI->isVirtual()) {
1168 // virtual base offset offset is -ve. The code generator emits dwarf
1169 // expression where it expects +ve number.
1171 0 - CGM.getItaniumVTableContext()
1172 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1173 BFlags = llvm::DIDescriptor::FlagVirtual;
1175 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1176 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1177 // BI->isVirtual() and bits when not.
1179 AccessSpecifier Access = BI->getAccessSpecifier();
1180 if (Access == clang::AS_private)
1181 BFlags |= llvm::DIDescriptor::FlagPrivate;
1182 else if (Access == clang::AS_protected)
1183 BFlags |= llvm::DIDescriptor::FlagProtected;
1186 DBuilder.createInheritance(RecordTy,
1187 getOrCreateType(BI->getType(), Unit),
1188 BaseOffset, BFlags);
1189 EltTys.push_back(DTy);
1193 /// CollectTemplateParams - A helper function to collect template parameters.
1194 llvm::DIArray CGDebugInfo::
1195 CollectTemplateParams(const TemplateParameterList *TPList,
1196 ArrayRef<TemplateArgument> TAList,
1197 llvm::DIFile Unit) {
1198 SmallVector<llvm::Value *, 16> TemplateParams;
1199 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1200 const TemplateArgument &TA = TAList[i];
1203 Name = TPList->getParam(i)->getName();
1204 switch (TA.getKind()) {
1205 case TemplateArgument::Type: {
1206 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1207 llvm::DITemplateTypeParameter TTP =
1208 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
1209 TemplateParams.push_back(TTP);
1211 case TemplateArgument::Integral: {
1212 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1213 llvm::DITemplateValueParameter TVP =
1214 DBuilder.createTemplateValueParameter(
1216 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1217 TemplateParams.push_back(TVP);
1219 case TemplateArgument::Declaration: {
1220 const ValueDecl *D = TA.getAsDecl();
1221 bool InstanceMember = D->isCXXInstanceMember();
1222 QualType T = InstanceMember
1223 ? CGM.getContext().getMemberPointerType(
1224 D->getType(), cast<RecordDecl>(D->getDeclContext())
1226 : CGM.getContext().getPointerType(D->getType());
1227 llvm::DIType TTy = getOrCreateType(T, Unit);
1229 // Variable pointer template parameters have a value that is the address
1231 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1232 V = CGM.GetAddrOfGlobalVar(VD);
1233 // Member function pointers have special support for building them, though
1234 // this is currently unsupported in LLVM CodeGen.
1235 if (InstanceMember) {
1236 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1237 V = CGM.getCXXABI().EmitMemberPointer(method);
1238 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1239 V = CGM.GetAddrOfFunction(FD);
1240 // Member data pointers have special handling too to compute the fixed
1241 // offset within the object.
1242 if (isa<FieldDecl>(D)) {
1243 // These five lines (& possibly the above member function pointer
1244 // handling) might be able to be refactored to use similar code in
1245 // CodeGenModule::getMemberPointerConstant
1246 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1248 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1249 V = CGM.getCXXABI().EmitMemberDataPointer(
1250 cast<MemberPointerType>(T.getTypePtr()), chars);
1252 llvm::DITemplateValueParameter TVP =
1253 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1254 V->stripPointerCasts());
1255 TemplateParams.push_back(TVP);
1257 case TemplateArgument::NullPtr: {
1258 QualType T = TA.getNullPtrType();
1259 llvm::DIType TTy = getOrCreateType(T, Unit);
1261 // Special case member data pointer null values since they're actually -1
1263 if (const MemberPointerType *MPT =
1264 dyn_cast<MemberPointerType>(T.getTypePtr()))
1265 // But treat member function pointers as simple zero integers because
1266 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1267 // CodeGen grows handling for values of non-null member function
1268 // pointers then perhaps we could remove this special case and rely on
1269 // EmitNullMemberPointer for member function pointers.
1270 if (MPT->isMemberDataPointer())
1271 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1273 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1274 llvm::DITemplateValueParameter TVP =
1275 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
1276 TemplateParams.push_back(TVP);
1278 case TemplateArgument::Template: {
1279 llvm::DITemplateValueParameter TVP =
1280 DBuilder.createTemplateTemplateParameter(
1281 TheCU, Name, llvm::DIType(),
1282 TA.getAsTemplate().getAsTemplateDecl()
1283 ->getQualifiedNameAsString());
1284 TemplateParams.push_back(TVP);
1286 case TemplateArgument::Pack: {
1287 llvm::DITemplateValueParameter TVP =
1288 DBuilder.createTemplateParameterPack(
1289 TheCU, Name, llvm::DIType(),
1290 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1291 TemplateParams.push_back(TVP);
1293 case TemplateArgument::Expression: {
1294 const Expr *E = TA.getAsExpr();
1295 QualType T = E->getType();
1296 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1297 assert(V && "Expression in template argument isn't constant");
1298 llvm::DIType TTy = getOrCreateType(T, Unit);
1299 llvm::DITemplateValueParameter TVP =
1300 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1301 V->stripPointerCasts());
1302 TemplateParams.push_back(TVP);
1304 // And the following should never occur:
1305 case TemplateArgument::TemplateExpansion:
1306 case TemplateArgument::Null:
1308 "These argument types shouldn't exist in concrete types");
1311 return DBuilder.getOrCreateArray(TemplateParams);
1314 /// CollectFunctionTemplateParams - A helper function to collect debug
1315 /// info for function template parameters.
1316 llvm::DIArray CGDebugInfo::
1317 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1318 if (FD->getTemplatedKind() ==
1319 FunctionDecl::TK_FunctionTemplateSpecialization) {
1320 const TemplateParameterList *TList =
1321 FD->getTemplateSpecializationInfo()->getTemplate()
1322 ->getTemplateParameters();
1323 return CollectTemplateParams(
1324 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1326 return llvm::DIArray();
1329 /// CollectCXXTemplateParams - A helper function to collect debug info for
1330 /// template parameters.
1331 llvm::DIArray CGDebugInfo::
1332 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1333 llvm::DIFile Unit) {
1334 llvm::PointerUnion<ClassTemplateDecl *,
1335 ClassTemplatePartialSpecializationDecl *>
1336 PU = TSpecial->getSpecializedTemplateOrPartial();
1338 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1339 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1340 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1341 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1342 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1345 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1346 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1347 if (VTablePtrType.isValid())
1348 return VTablePtrType;
1350 ASTContext &Context = CGM.getContext();
1353 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1354 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1355 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1356 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1357 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1359 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1360 return VTablePtrType;
1363 /// getVTableName - Get vtable name for the given Class.
1364 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1365 // Copy the gdb compatible name on the side and use its reference.
1366 return internString("_vptr$", RD->getNameAsString());
1370 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1371 /// debug info entry in EltTys vector.
1373 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1374 SmallVectorImpl<llvm::Value *> &EltTys) {
1375 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1377 // If there is a primary base then it will hold vtable info.
1378 if (RL.getPrimaryBase())
1381 // If this class is not dynamic then there is not any vtable info to collect.
1382 if (!RD->isDynamicClass())
1385 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1387 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1389 llvm::DIDescriptor::FlagArtificial,
1390 getOrCreateVTablePtrType(Unit));
1391 EltTys.push_back(VPTR);
1394 /// getOrCreateRecordType - Emit record type's standalone debug info.
1395 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1396 SourceLocation Loc) {
1397 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1398 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1402 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1404 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1405 SourceLocation Loc) {
1406 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1407 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1408 RetainedTypes.push_back(D.getAsOpaquePtr());
1412 void CGDebugInfo::completeType(const RecordDecl *RD) {
1413 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1414 !CGM.getLangOpts().CPlusPlus)
1415 completeRequiredType(RD);
1418 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1419 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1420 if (CXXDecl->isDynamicClass())
1423 QualType Ty = CGM.getContext().getRecordType(RD);
1424 llvm::DIType T = getTypeOrNull(Ty);
1425 if (T && T.isForwardDecl())
1426 completeClassData(RD);
1429 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1430 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1432 QualType Ty = CGM.getContext().getRecordType(RD);
1433 void* TyPtr = Ty.getAsOpaquePtr();
1434 if (CompletedTypeCache.count(TyPtr))
1436 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1437 assert(!Res.isForwardDecl());
1438 CompletedTypeCache[TyPtr] = Res;
1439 TypeCache[TyPtr] = Res;
1442 /// CreateType - get structure or union type.
1443 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1444 RecordDecl *RD = Ty->getDecl();
1445 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1446 // Always emit declarations for types that aren't required to be complete when
1447 // in limit-debug-info mode. If the type is later found to be required to be
1448 // complete this declaration will be upgraded to a definition by
1449 // `completeRequiredType`.
1450 // If the type is dynamic, only emit the definition in TUs that require class
1451 // data. This is handled by `completeClassData`.
1452 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1453 // If we've already emitted the type, just use that, even if it's only a
1454 // declaration. The completeType, completeRequiredType, and completeClassData
1455 // callbacks will handle promoting the declaration to a definition.
1457 (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
1458 // Under -flimit-debug-info, emit only a declaration unless the type is
1459 // required to be complete.
1460 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1461 // If the class is dynamic, only emit a declaration. A definition will be
1462 // emitted whenever the vtable is emitted.
1463 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass()) || T) {
1464 llvm::DIDescriptor FDContext =
1465 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1467 T = getOrCreateRecordFwdDecl(Ty, FDContext);
1471 return CreateTypeDefinition(Ty);
1474 llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1475 RecordDecl *RD = Ty->getDecl();
1477 // Get overall information about the record type for the debug info.
1478 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1480 // Records and classes and unions can all be recursive. To handle them, we
1481 // first generate a debug descriptor for the struct as a forward declaration.
1482 // Then (if it is a definition) we go through and get debug info for all of
1483 // its members. Finally, we create a descriptor for the complete type (which
1484 // may refer to the forward decl if the struct is recursive) and replace all
1485 // uses of the forward declaration with the final definition.
1487 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
1488 assert(FwdDecl.isCompositeType() &&
1489 "The debug type of a RecordType should be a llvm::DICompositeType");
1491 if (FwdDecl.isForwardDecl())
1494 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1495 CollectContainingType(CXXDecl, FwdDecl);
1497 // Push the struct on region stack.
1498 LexicalBlockStack.push_back(&*FwdDecl);
1499 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1501 // Add this to the completed-type cache while we're completing it recursively.
1502 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1504 // Convert all the elements.
1505 SmallVector<llvm::Value *, 16> EltTys;
1506 // what about nested types?
1508 // Note: The split of CXXDecl information here is intentional, the
1509 // gdb tests will depend on a certain ordering at printout. The debug
1510 // information offsets are still correct if we merge them all together
1512 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1514 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1515 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1518 // Collect data fields (including static variables and any initializers).
1519 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1521 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1523 LexicalBlockStack.pop_back();
1524 RegionMap.erase(Ty->getDecl());
1526 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1527 FwdDecl.setTypeArray(Elements);
1529 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1533 /// CreateType - get objective-c object type.
1534 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1535 llvm::DIFile Unit) {
1536 // Ignore protocols.
1537 return getOrCreateType(Ty->getBaseType(), Unit);
1541 /// \return true if Getter has the default name for the property PD.
1542 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1543 const ObjCMethodDecl *Getter) {
1548 assert(Getter->getDeclName().isObjCZeroArgSelector());
1549 return PD->getName() ==
1550 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1553 /// \return true if Setter has the default name for the property PD.
1554 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1555 const ObjCMethodDecl *Setter) {
1560 assert(Setter->getDeclName().isObjCOneArgSelector());
1561 return SelectorTable::constructSetterName(PD->getName()) ==
1562 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1565 /// CreateType - get objective-c interface type.
1566 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1567 llvm::DIFile Unit) {
1568 ObjCInterfaceDecl *ID = Ty->getDecl();
1570 return llvm::DIType();
1572 // Get overall information about the record type for the debug info.
1573 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1574 unsigned Line = getLineNumber(ID->getLocation());
1575 unsigned RuntimeLang = TheCU.getLanguage();
1577 // If this is just a forward declaration return a special forward-declaration
1578 // debug type since we won't be able to lay out the entire type.
1579 ObjCInterfaceDecl *Def = ID->getDefinition();
1581 llvm::DIType FwdDecl =
1582 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1583 ID->getName(), TheCU, DefUnit, Line,
1590 // Bit size, align and offset of the type.
1591 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1592 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1595 if (ID->getImplementation())
1596 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1598 llvm::DICompositeType RealDecl =
1599 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1600 Line, Size, Align, Flags,
1601 llvm::DIType(), llvm::DIArray(), RuntimeLang);
1603 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1604 // will find it and we're emitting the complete type.
1605 QualType QualTy = QualType(Ty, 0);
1606 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
1608 // Push the struct on region stack.
1609 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
1610 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1612 // Convert all the elements.
1613 SmallVector<llvm::Value *, 16> EltTys;
1615 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1617 llvm::DIType SClassTy =
1618 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1619 if (!SClassTy.isValid())
1620 return llvm::DIType();
1622 llvm::DIType InhTag =
1623 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1624 EltTys.push_back(InhTag);
1627 // Create entries for all of the properties.
1628 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1629 E = ID->prop_end(); I != E; ++I) {
1630 const ObjCPropertyDecl *PD = *I;
1631 SourceLocation Loc = PD->getLocation();
1632 llvm::DIFile PUnit = getOrCreateFile(Loc);
1633 unsigned PLine = getLineNumber(Loc);
1634 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1635 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1636 llvm::MDNode *PropertyNode =
1637 DBuilder.createObjCProperty(PD->getName(),
1639 hasDefaultGetterName(PD, Getter) ? "" :
1640 getSelectorName(PD->getGetterName()),
1641 hasDefaultSetterName(PD, Setter) ? "" :
1642 getSelectorName(PD->getSetterName()),
1643 PD->getPropertyAttributes(),
1644 getOrCreateType(PD->getType(), PUnit));
1645 EltTys.push_back(PropertyNode);
1648 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1649 unsigned FieldNo = 0;
1650 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1651 Field = Field->getNextIvar(), ++FieldNo) {
1652 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1653 if (!FieldTy.isValid())
1654 return llvm::DIType();
1656 StringRef FieldName = Field->getName();
1658 // Ignore unnamed fields.
1659 if (FieldName.empty())
1662 // Get the location for the field.
1663 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1664 unsigned FieldLine = getLineNumber(Field->getLocation());
1665 QualType FType = Field->getType();
1666 uint64_t FieldSize = 0;
1667 unsigned FieldAlign = 0;
1669 if (!FType->isIncompleteArrayType()) {
1671 // Bit size, align and offset of the type.
1672 FieldSize = Field->isBitField()
1673 ? Field->getBitWidthValue(CGM.getContext())
1674 : CGM.getContext().getTypeSize(FType);
1675 FieldAlign = CGM.getContext().getTypeAlign(FType);
1678 uint64_t FieldOffset;
1679 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1680 // We don't know the runtime offset of an ivar if we're using the
1681 // non-fragile ABI. For bitfields, use the bit offset into the first
1682 // byte of storage of the bitfield. For other fields, use zero.
1683 if (Field->isBitField()) {
1684 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1686 FieldOffset %= CGM.getContext().getCharWidth();
1691 FieldOffset = RL.getFieldOffset(FieldNo);
1695 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1696 Flags = llvm::DIDescriptor::FlagProtected;
1697 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1698 Flags = llvm::DIDescriptor::FlagPrivate;
1700 llvm::MDNode *PropertyNode = NULL;
1701 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1702 if (ObjCPropertyImplDecl *PImpD =
1703 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1704 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1705 SourceLocation Loc = PD->getLocation();
1706 llvm::DIFile PUnit = getOrCreateFile(Loc);
1707 unsigned PLine = getLineNumber(Loc);
1708 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1709 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1711 DBuilder.createObjCProperty(PD->getName(),
1713 hasDefaultGetterName(PD, Getter) ? "" :
1714 getSelectorName(PD->getGetterName()),
1715 hasDefaultSetterName(PD, Setter) ? "" :
1716 getSelectorName(PD->getSetterName()),
1717 PD->getPropertyAttributes(),
1718 getOrCreateType(PD->getType(), PUnit));
1722 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1723 FieldLine, FieldSize, FieldAlign,
1724 FieldOffset, Flags, FieldTy,
1726 EltTys.push_back(FieldTy);
1729 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1730 RealDecl.setTypeArray(Elements);
1732 // If the implementation is not yet set, we do not want to mark it
1733 // as complete. An implementation may declare additional
1734 // private ivars that we would miss otherwise.
1735 if (ID->getImplementation() == 0)
1736 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
1738 LexicalBlockStack.pop_back();
1742 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1743 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1744 int64_t Count = Ty->getNumElements();
1746 // If number of elements are not known then this is an unbounded array.
1747 // Use Count == -1 to express such arrays.
1750 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1751 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1753 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1754 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1756 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1759 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1760 llvm::DIFile Unit) {
1764 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1765 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1768 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1769 } else if (Ty->isIncompleteArrayType()) {
1771 if (Ty->getElementType()->isIncompleteType())
1774 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1775 } else if (Ty->isIncompleteType()) {
1779 // Size and align of the whole array, not the element type.
1780 Size = CGM.getContext().getTypeSize(Ty);
1781 Align = CGM.getContext().getTypeAlign(Ty);
1784 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1785 // interior arrays, do we care? Why aren't nested arrays represented the
1786 // obvious/recursive way?
1787 SmallVector<llvm::Value *, 8> Subscripts;
1788 QualType EltTy(Ty, 0);
1789 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1790 // If the number of elements is known, then count is that number. Otherwise,
1791 // it's -1. This allows us to represent a subrange with an array of 0
1792 // elements, like this:
1797 int64_t Count = -1; // Count == -1 is an unbounded array.
1798 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1799 Count = CAT->getSize().getZExtValue();
1801 // FIXME: Verify this is right for VLAs.
1802 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1803 EltTy = Ty->getElementType();
1806 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1808 llvm::DIType DbgTy =
1809 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1814 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1815 llvm::DIFile Unit) {
1816 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1817 Ty, Ty->getPointeeType(), Unit);
1820 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1821 llvm::DIFile Unit) {
1822 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1823 Ty, Ty->getPointeeType(), Unit);
1826 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1828 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1829 if (!Ty->getPointeeType()->isFunctionType())
1830 return DBuilder.createMemberPointerType(
1831 getOrCreateType(Ty->getPointeeType(), U), ClassType);
1832 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1833 CGM.getContext().getPointerType(
1834 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1835 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1839 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1841 // Ignore the atomic wrapping
1842 // FIXME: What is the correct representation?
1843 return getOrCreateType(Ty->getValueType(), U);
1846 /// CreateEnumType - get enumeration type.
1847 llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
1848 const EnumDecl *ED = Ty->getDecl();
1851 if (!ED->getTypeForDecl()->isIncompleteType()) {
1852 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1853 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1856 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1858 // If this is just a forward declaration, construct an appropriately
1859 // marked node and just return it.
1860 if (!ED->getDefinition()) {
1861 llvm::DIDescriptor EDContext;
1862 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1863 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1864 unsigned Line = getLineNumber(ED->getLocation());
1865 StringRef EDName = ED->getName();
1866 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1867 EDName, EDContext, DefUnit, Line, 0,
1868 Size, Align, FullName);
1871 // Create DIEnumerator elements for each enumerator.
1872 SmallVector<llvm::Value *, 16> Enumerators;
1873 ED = ED->getDefinition();
1874 for (EnumDecl::enumerator_iterator
1875 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1876 Enum != EnumEnd; ++Enum) {
1877 Enumerators.push_back(
1878 DBuilder.createEnumerator(Enum->getName(),
1879 Enum->getInitVal().getSExtValue()));
1882 // Return a CompositeType for the enum itself.
1883 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1885 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1886 unsigned Line = getLineNumber(ED->getLocation());
1887 llvm::DIDescriptor EnumContext =
1888 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1889 llvm::DIType ClassTy = ED->isFixed() ?
1890 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1891 llvm::DIType DbgTy =
1892 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1893 Size, Align, EltArray,
1898 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1901 Qualifiers InnerQuals = T.getLocalQualifiers();
1902 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1903 // that is already there.
1904 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1905 Quals += InnerQuals;
1907 switch (T->getTypeClass()) {
1909 return C.getQualifiedType(T.getTypePtr(), Quals);
1910 case Type::TemplateSpecialization:
1911 T = cast<TemplateSpecializationType>(T)->desugar();
1913 case Type::TypeOfExpr:
1914 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1917 T = cast<TypeOfType>(T)->getUnderlyingType();
1919 case Type::Decltype:
1920 T = cast<DecltypeType>(T)->getUnderlyingType();
1922 case Type::UnaryTransform:
1923 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1925 case Type::Attributed:
1926 T = cast<AttributedType>(T)->getEquivalentType();
1928 case Type::Elaborated:
1929 T = cast<ElaboratedType>(T)->getNamedType();
1932 T = cast<ParenType>(T)->getInnerType();
1934 case Type::SubstTemplateTypeParm:
1935 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1938 QualType DT = cast<AutoType>(T)->getDeducedType();
1945 assert(T != LastT && "Type unwrapping failed to unwrap!");
1950 /// getType - Get the type from the cache or return null type if it doesn't
1952 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1954 // Unwrap the type as needed for debug information.
1955 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1957 // Check for existing entry.
1958 if (Ty->getTypeClass() == Type::ObjCInterface) {
1959 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1961 return llvm::DIType(cast<llvm::MDNode>(V));
1962 else return llvm::DIType();
1965 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1966 TypeCache.find(Ty.getAsOpaquePtr());
1967 if (it != TypeCache.end()) {
1968 // Verify that the debug info still exists.
1969 if (llvm::Value *V = it->second)
1970 return llvm::DIType(cast<llvm::MDNode>(V));
1973 return llvm::DIType();
1976 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
1978 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1980 // Unwrap the type as needed for debug information.
1981 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1983 // Check for existing entry.
1985 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1986 CompletedTypeCache.find(Ty.getAsOpaquePtr());
1987 if (it != CompletedTypeCache.end())
1990 V = getCachedInterfaceTypeOrNull(Ty);
1993 // Verify that any cached debug info still exists.
1994 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
1997 /// getCachedInterfaceTypeOrNull - Get the type from the interface
1998 /// cache, unless it needs to regenerated. Otherwise return null.
1999 llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2000 // Is there a cached interface that hasn't changed?
2001 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2002 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2004 if (it1 != ObjCInterfaceCache.end())
2005 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2006 if (Checksum(Decl) == it1->second.second)
2007 // Return cached forward declaration.
2008 return it1->second.first;
2013 /// getOrCreateType - Get the type from the cache or create a new
2014 /// one if necessary.
2015 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
2017 return llvm::DIType();
2019 // Unwrap the type as needed for debug information.
2020 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2022 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
2025 // Otherwise create the type.
2026 llvm::DIType Res = CreateTypeNode(Ty, Unit);
2027 void* TyPtr = Ty.getAsOpaquePtr();
2029 // And update the type cache.
2030 TypeCache[TyPtr] = Res;
2032 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2033 // into the cache - but getTypeOrNull has a special case for cached interface
2034 // types. We should probably just pull that out as a special case for the
2035 // "else" block below & skip the otherwise needless lookup.
2036 llvm::DIType TC = getTypeOrNull(Ty);
2037 if (TC && TC.isForwardDecl())
2038 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2039 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2040 // Interface types may have elements added to them by a
2041 // subsequent implementation or extension, so we keep them in
2042 // the ObjCInterfaceCache together with a checksum. Instead of
2043 // the (possibly) incomplete interface type, we return a forward
2044 // declaration that gets RAUW'd in CGDebugInfo::finalize().
2045 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2047 return llvm::DIType(cast<llvm::MDNode>(V.first));
2048 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2049 Decl->getName(), TheCU, Unit,
2050 getLineNumber(Decl->getLocation()),
2051 TheCU.getLanguage());
2052 // Store the forward declaration in the cache.
2054 V.second = Checksum(Decl);
2056 // Register the type for replacement in finalize().
2057 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2062 if (!Res.isForwardDecl())
2063 CompletedTypeCache[TyPtr] = Res;
2068 /// Currently the checksum of an interface includes the number of
2069 /// ivars and property accessors.
2070 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
2071 // The assumption is that the number of ivars can only increase
2072 // monotonically, so it is safe to just use their current number as
2075 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2076 Ivar != 0; Ivar = Ivar->getNextIvar())
2082 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2083 switch (Ty->getTypeClass()) {
2084 case Type::ObjCObjectPointer:
2085 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2086 ->getPointeeType());
2087 case Type::ObjCInterface:
2088 return cast<ObjCInterfaceType>(Ty)->getDecl();
2094 /// CreateTypeNode - Create a new debug type node.
2095 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
2096 // Handle qualifiers, which recursively handles what they refer to.
2097 if (Ty.hasLocalQualifiers())
2098 return CreateQualifiedType(Ty, Unit);
2100 const char *Diag = 0;
2102 // Work out details of type.
2103 switch (Ty->getTypeClass()) {
2104 #define TYPE(Class, Base)
2105 #define ABSTRACT_TYPE(Class, Base)
2106 #define NON_CANONICAL_TYPE(Class, Base)
2107 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2108 #include "clang/AST/TypeNodes.def"
2109 llvm_unreachable("Dependent types cannot show up in debug information");
2111 case Type::ExtVector:
2113 return CreateType(cast<VectorType>(Ty), Unit);
2114 case Type::ObjCObjectPointer:
2115 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2116 case Type::ObjCObject:
2117 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2118 case Type::ObjCInterface:
2119 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2121 return CreateType(cast<BuiltinType>(Ty));
2123 return CreateType(cast<ComplexType>(Ty));
2125 return CreateType(cast<PointerType>(Ty), Unit);
2127 // Decayed types are just pointers in LLVM and DWARF.
2129 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
2130 case Type::BlockPointer:
2131 return CreateType(cast<BlockPointerType>(Ty), Unit);
2133 return CreateType(cast<TypedefType>(Ty), Unit);
2135 return CreateType(cast<RecordType>(Ty));
2137 return CreateEnumType(cast<EnumType>(Ty));
2138 case Type::FunctionProto:
2139 case Type::FunctionNoProto:
2140 return CreateType(cast<FunctionType>(Ty), Unit);
2141 case Type::ConstantArray:
2142 case Type::VariableArray:
2143 case Type::IncompleteArray:
2144 return CreateType(cast<ArrayType>(Ty), Unit);
2146 case Type::LValueReference:
2147 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2148 case Type::RValueReference:
2149 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2151 case Type::MemberPointer:
2152 return CreateType(cast<MemberPointerType>(Ty), Unit);
2155 return CreateType(cast<AtomicType>(Ty), Unit);
2157 case Type::Attributed:
2158 case Type::TemplateSpecialization:
2159 case Type::Elaborated:
2161 case Type::SubstTemplateTypeParm:
2162 case Type::TypeOfExpr:
2164 case Type::Decltype:
2165 case Type::UnaryTransform:
2166 case Type::PackExpansion:
2167 llvm_unreachable("type should have been unwrapped!");
2173 assert(Diag && "Fall through without a diagnostic?");
2174 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2175 "debug information for %0 is not yet supported");
2176 CGM.getDiags().Report(DiagID)
2178 return llvm::DIType();
2181 /// getOrCreateLimitedType - Get the type from the cache or create a new
2182 /// limited type if necessary.
2183 llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2184 llvm::DIFile Unit) {
2185 QualType QTy(Ty, 0);
2187 llvm::DICompositeType T(getTypeOrNull(QTy));
2189 // We may have cached a forward decl when we could have created
2190 // a non-forward decl. Go ahead and create a non-forward decl
2192 if (T && !T.isForwardDecl()) return T;
2194 // Otherwise create the type.
2195 llvm::DICompositeType Res = CreateLimitedType(Ty);
2197 // Propagate members from the declaration to the definition
2198 // CreateType(const RecordType*) will overwrite this with the members in the
2199 // correct order if the full type is needed.
2200 Res.setTypeArray(T.getTypeArray());
2202 if (T && T.isForwardDecl())
2203 ReplaceMap.push_back(
2204 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
2206 // And update the type cache.
2207 TypeCache[QTy.getAsOpaquePtr()] = Res;
2211 // TODO: Currently used for context chains when limiting debug info.
2212 llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2213 RecordDecl *RD = Ty->getDecl();
2215 // Get overall information about the record type for the debug info.
2216 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2217 unsigned Line = getLineNumber(RD->getLocation());
2218 StringRef RDName = getClassName(RD);
2220 llvm::DIDescriptor RDContext =
2221 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2223 // If we ended up creating the type during the context chain construction,
2224 // just return that.
2225 // FIXME: this could be dealt with better if the type was recorded as
2226 // completed before we started this (see the CompletedTypeCache usage in
2227 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2228 // be pushed to before context creation, but after it was known to be
2229 // destined for completion (might still have an issue if this caller only
2230 // required a declaration but the context construction ended up creating a
2232 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2233 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
2236 // If this is just a forward declaration, construct an appropriately
2237 // marked node and just return it.
2238 if (!RD->getDefinition())
2239 return getOrCreateRecordFwdDecl(Ty, RDContext);
2241 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2242 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2243 llvm::DICompositeType RealDecl;
2245 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2248 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
2249 Size, Align, 0, llvm::DIArray(), 0,
2251 else if (RD->isClass()) {
2252 // FIXME: This could be a struct type giving a default visibility different
2253 // than C++ class type, but needs llvm metadata changes first.
2254 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
2255 Size, Align, 0, 0, llvm::DIType(),
2256 llvm::DIArray(), llvm::DIType(),
2257 llvm::DIArray(), FullName);
2259 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
2260 Size, Align, 0, llvm::DIType(),
2261 llvm::DIArray(), 0, llvm::DIType(),
2264 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
2265 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
2267 if (const ClassTemplateSpecializationDecl *TSpecial =
2268 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2269 RealDecl.setTypeArray(llvm::DIArray(),
2270 CollectCXXTemplateParams(TSpecial, DefUnit));
2274 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2275 llvm::DICompositeType RealDecl) {
2276 // A class's primary base or the class itself contains the vtable.
2277 llvm::DICompositeType ContainingType;
2278 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2279 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2280 // Seek non virtual primary base root.
2282 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2283 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2284 if (PBT && !BRL.isPrimaryBaseVirtual())
2289 ContainingType = llvm::DICompositeType(
2290 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2291 getOrCreateFile(RD->getLocation())));
2292 } else if (RD->isDynamicClass())
2293 ContainingType = RealDecl;
2295 RealDecl.setContainingType(ContainingType);
2298 /// CreateMemberType - Create new member and increase Offset by FType's size.
2299 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2302 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2303 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2304 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2305 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2306 FieldSize, FieldAlign,
2307 *Offset, 0, FieldTy);
2308 *Offset += FieldSize;
2312 llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2313 // We only need a declaration (not a definition) of the type - so use whatever
2314 // we would otherwise do to get a type for a pointee. (forward declarations in
2315 // limited debug info, full definitions (if the type definition is available)
2316 // in unlimited debug info)
2317 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2318 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2319 getOrCreateFile(TD->getLocation()));
2320 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2321 // This doesn't handle providing declarations (for functions or variables) for
2322 // entities without definitions in this TU, nor when the definition proceeds
2323 // the call to this function.
2324 // FIXME: This should be split out into more specific maps with support for
2325 // emitting forward declarations and merging definitions with declarations,
2326 // the same way as we do for types.
2327 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2328 DeclCache.find(D->getCanonicalDecl());
2329 if (I == DeclCache.end())
2330 return llvm::DIDescriptor();
2331 llvm::Value *V = I->second;
2332 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2335 /// getFunctionDeclaration - Return debug info descriptor to describe method
2336 /// declaration for the given method definition.
2337 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2338 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2339 return llvm::DISubprogram();
2341 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2342 if (!FD) return llvm::DISubprogram();
2345 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
2347 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2348 MI = SPCache.find(FD->getCanonicalDecl());
2349 if (MI == SPCache.end()) {
2350 if (const CXXMethodDecl *MD =
2351 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2352 llvm::DICompositeType T(S);
2353 llvm::DISubprogram SP =
2354 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
2359 if (MI != SPCache.end()) {
2360 llvm::Value *V = MI->second;
2361 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2362 if (SP.isSubprogram() && !SP.isDefinition())
2366 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2367 E = FD->redecls_end(); I != E; ++I) {
2368 const FunctionDecl *NextFD = *I;
2369 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2370 MI = SPCache.find(NextFD->getCanonicalDecl());
2371 if (MI != SPCache.end()) {
2372 llvm::Value *V = MI->second;
2373 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2374 if (SP.isSubprogram() && !SP.isDefinition())
2378 return llvm::DISubprogram();
2381 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2382 // implicit parameter "this".
2383 llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2386 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2387 // Create fake but valid subroutine type. Otherwise
2388 // llvm::DISubprogram::Verify() would return false, and
2389 // subprogram DIE will miss DW_AT_decl_file and
2390 // DW_AT_decl_line fields.
2391 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
2393 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2394 return getOrCreateMethodType(Method, F);
2395 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2396 // Add "self" and "_cmd"
2397 SmallVector<llvm::Value *, 16> Elts;
2399 // First element is always return type. For 'void' functions it is NULL.
2400 QualType ResultTy = OMethod->getResultType();
2402 // Replace the instancetype keyword with the actual type.
2403 if (ResultTy == CGM.getContext().getObjCInstanceType())
2404 ResultTy = CGM.getContext().getPointerType(
2405 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2407 Elts.push_back(getOrCreateType(ResultTy, F));
2408 // "self" pointer is always first argument.
2409 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2410 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2411 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
2412 // "_cmd" pointer is always second argument.
2413 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2414 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2415 // Get rest of the arguments.
2416 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2417 PE = OMethod->param_end(); PI != PE; ++PI)
2418 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2420 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2421 return DBuilder.createSubroutineType(F, EltTypeArray);
2423 return llvm::DICompositeType(getOrCreateType(FnType, F));
2426 /// EmitFunctionStart - Constructs the debug code for entering a function.
2427 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2429 CGBuilderTy &Builder) {
2432 StringRef LinkageName;
2434 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2436 const Decl *D = GD.getDecl();
2437 // Function may lack declaration in source code if it is created by Clang
2438 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2439 bool HasDecl = (D != 0);
2440 // Use the location of the declaration.
2443 Loc = D->getLocation();
2446 llvm::DIFile Unit = getOrCreateFile(Loc);
2447 llvm::DIDescriptor FDContext(Unit);
2448 llvm::DIArray TParamsArray;
2450 // Use llvm function name.
2451 LinkageName = Fn->getName();
2452 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2453 // If there is a DISubprogram for this function available then use it.
2454 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2455 FI = SPCache.find(FD->getCanonicalDecl());
2456 if (FI != SPCache.end()) {
2457 llvm::Value *V = FI->second;
2458 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2459 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2460 llvm::MDNode *SPN = SP;
2461 LexicalBlockStack.push_back(SPN);
2462 RegionMap[D] = llvm::WeakVH(SP);
2466 Name = getFunctionName(FD);
2467 // Use mangled name as linkage name for C/C++ functions.
2468 if (FD->hasPrototype()) {
2469 LinkageName = CGM.getMangledName(GD);
2470 Flags |= llvm::DIDescriptor::FlagPrototyped;
2472 // No need to replicate the linkage name if it isn't different from the
2473 // subprogram name, no need to have it at all unless coverage is enabled or
2474 // debug is set to more than just line tables.
2475 if (LinkageName == Name ||
2476 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2477 !CGM.getCodeGenOpts().EmitGcovNotes &&
2478 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
2479 LinkageName = StringRef();
2481 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2482 if (const NamespaceDecl *NSDecl =
2483 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2484 FDContext = getOrCreateNameSpace(NSDecl);
2485 else if (const RecordDecl *RDecl =
2486 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2487 FDContext = getContextDescriptor(cast<Decl>(RDecl));
2489 // Collect template parameters.
2490 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2492 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2493 Name = getObjCMethodName(OMD);
2494 Flags |= llvm::DIDescriptor::FlagPrototyped;
2496 // Use llvm function name.
2497 Name = Fn->getName();
2498 Flags |= llvm::DIDescriptor::FlagPrototyped;
2500 if (!Name.empty() && Name[0] == '\01')
2501 Name = Name.substr(1);
2503 unsigned LineNo = getLineNumber(Loc);
2504 if (!HasDecl || D->isImplicit())
2505 Flags |= llvm::DIDescriptor::FlagArtificial;
2507 llvm::DISubprogram SP =
2508 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2509 getOrCreateFunctionType(D, FnType, Unit),
2510 Fn->hasInternalLinkage(), true /*definition*/,
2511 getLineNumber(CurLoc), Flags,
2512 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2513 getFunctionDeclaration(D));
2515 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
2517 // Push function on region stack.
2518 llvm::MDNode *SPN = SP;
2519 LexicalBlockStack.push_back(SPN);
2521 RegionMap[D] = llvm::WeakVH(SP);
2524 /// EmitLocation - Emit metadata to indicate a change in line/column
2525 /// information in the source file. If the location is invalid, the
2526 /// previous location will be reused.
2527 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2528 bool ForceColumnInfo) {
2529 // Update our current location
2532 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2534 // Don't bother if things are the same as last time.
2535 SourceManager &SM = CGM.getContext().getSourceManager();
2536 if (CurLoc == PrevLoc ||
2537 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2538 // New Builder may not be in sync with CGDebugInfo.
2539 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2540 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2541 LexicalBlockStack.back())
2544 // Update last state.
2547 llvm::MDNode *Scope = LexicalBlockStack.back();
2548 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2549 (getLineNumber(CurLoc),
2550 getColumnNumber(CurLoc, ForceColumnInfo),
2554 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2556 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2557 llvm::DIDescriptor D =
2558 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2559 llvm::DIDescriptor() :
2560 llvm::DIDescriptor(LexicalBlockStack.back()),
2561 getOrCreateFile(CurLoc),
2562 getLineNumber(CurLoc),
2563 getColumnNumber(CurLoc));
2564 llvm::MDNode *DN = D;
2565 LexicalBlockStack.push_back(DN);
2568 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2569 /// region - beginning of a DW_TAG_lexical_block.
2570 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2571 SourceLocation Loc) {
2572 // Set our current location.
2575 // Create a new lexical block and push it on the stack.
2576 CreateLexicalBlock(Loc);
2578 // Emit a line table change for the current location inside the new scope.
2579 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2580 getColumnNumber(Loc),
2581 LexicalBlockStack.back()));
2584 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2585 /// region - end of a DW_TAG_lexical_block.
2586 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2587 SourceLocation Loc) {
2588 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2590 // Provide an entry in the line table for the end of the block.
2591 EmitLocation(Builder, Loc);
2593 LexicalBlockStack.pop_back();
2596 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2597 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2598 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2599 unsigned RCount = FnBeginRegionCount.back();
2600 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2602 // Pop all regions for this function.
2603 while (LexicalBlockStack.size() != RCount)
2604 EmitLexicalBlockEnd(Builder, CurLoc);
2605 FnBeginRegionCount.pop_back();
2608 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2609 // See BuildByRefType.
2610 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2611 uint64_t *XOffset) {
2613 SmallVector<llvm::Value *, 5> EltTys;
2615 uint64_t FieldSize, FieldOffset;
2616 unsigned FieldAlign;
2618 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2619 QualType Type = VD->getType();
2622 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2623 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2624 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2625 FType = CGM.getContext().IntTy;
2626 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2627 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2629 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2630 if (HasCopyAndDispose) {
2631 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2632 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2634 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2637 bool HasByrefExtendedLayout;
2638 Qualifiers::ObjCLifetime Lifetime;
2639 if (CGM.getContext().getByrefLifetime(Type,
2640 Lifetime, HasByrefExtendedLayout)
2641 && HasByrefExtendedLayout) {
2642 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2643 EltTys.push_back(CreateMemberType(Unit, FType,
2644 "__byref_variable_layout",
2648 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2649 if (Align > CGM.getContext().toCharUnitsFromBits(
2650 CGM.getTarget().getPointerAlign(0))) {
2651 CharUnits FieldOffsetInBytes
2652 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2653 CharUnits AlignedOffsetInBytes
2654 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2655 CharUnits NumPaddingBytes
2656 = AlignedOffsetInBytes - FieldOffsetInBytes;
2658 if (NumPaddingBytes.isPositive()) {
2659 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2660 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2661 pad, ArrayType::Normal, 0);
2662 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2667 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2668 FieldSize = CGM.getContext().getTypeSize(FType);
2669 FieldAlign = CGM.getContext().toBits(Align);
2671 *XOffset = FieldOffset;
2672 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2673 0, FieldSize, FieldAlign,
2674 FieldOffset, 0, FieldTy);
2675 EltTys.push_back(FieldTy);
2676 FieldOffset += FieldSize;
2678 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2680 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2682 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2683 llvm::DIType(), Elements);
2686 /// EmitDeclare - Emit local variable declaration debug info.
2687 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2688 llvm::Value *Storage,
2689 unsigned ArgNo, CGBuilderTy &Builder) {
2690 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2691 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2694 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2695 cast<Decl>(VD->getDeclContext())->isImplicit());
2698 Unit = getOrCreateFile(VD->getLocation());
2700 uint64_t XOffset = 0;
2701 if (VD->hasAttr<BlocksAttr>())
2702 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2704 Ty = getOrCreateType(VD->getType(), Unit);
2706 // If there is no debug info for this type then do not emit debug info
2707 // for this variable.
2711 // Get location information.
2713 unsigned Column = 0;
2715 Line = getLineNumber(VD->getLocation());
2716 Column = getColumnNumber(VD->getLocation());
2719 if (VD->isImplicit())
2720 Flags |= llvm::DIDescriptor::FlagArtificial;
2721 // If this is the first argument and it is implicit then
2722 // give it an object pointer flag.
2723 // FIXME: There has to be a better way to do this, but for static
2724 // functions there won't be an implicit param at arg1 and
2725 // otherwise it is 'self' or 'this'.
2726 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2727 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2728 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2729 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2730 !VD->getType()->isPointerType())
2731 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
2733 llvm::MDNode *Scope = LexicalBlockStack.back();
2735 StringRef Name = VD->getName();
2736 if (!Name.empty()) {
2737 if (VD->hasAttr<BlocksAttr>()) {
2738 CharUnits offset = CharUnits::fromQuantity(32);
2739 SmallVector<llvm::Value *, 9> addr;
2740 llvm::Type *Int64Ty = CGM.Int64Ty;
2741 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2742 // offset of __forwarding field
2743 offset = CGM.getContext().toCharUnitsFromBits(
2744 CGM.getTarget().getPointerWidth(0));
2745 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2746 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2747 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2748 // offset of x field
2749 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2750 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2752 // Create the descriptor for the variable.
2753 llvm::DIVariable D =
2754 DBuilder.createComplexVariable(Tag,
2755 llvm::DIDescriptor(Scope),
2756 VD->getName(), Unit, Line, Ty,
2759 // Insert an llvm.dbg.declare into the current block.
2760 llvm::Instruction *Call =
2761 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2762 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2764 } else if (isa<VariableArrayType>(VD->getType()))
2765 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
2766 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2767 // If VD is an anonymous union then Storage represents value for
2768 // all union fields.
2769 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2770 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2771 for (RecordDecl::field_iterator I = RD->field_begin(),
2772 E = RD->field_end();
2774 FieldDecl *Field = *I;
2775 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2776 StringRef FieldName = Field->getName();
2778 // Ignore unnamed fields. Do not ignore unnamed records.
2779 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2782 // Use VarDecl's Tag, Scope and Line number.
2783 llvm::DIVariable D =
2784 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2785 FieldName, Unit, Line, FieldTy,
2786 CGM.getLangOpts().Optimize, Flags,
2789 // Insert an llvm.dbg.declare into the current block.
2790 llvm::Instruction *Call =
2791 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2792 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2798 // Create the descriptor for the variable.
2799 llvm::DIVariable D =
2800 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2801 Name, Unit, Line, Ty,
2802 CGM.getLangOpts().Optimize, Flags, ArgNo);
2804 // Insert an llvm.dbg.declare into the current block.
2805 llvm::Instruction *Call =
2806 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2807 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2810 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2811 llvm::Value *Storage,
2812 CGBuilderTy &Builder) {
2813 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2814 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2817 /// Look up the completed type for a self pointer in the TypeCache and
2818 /// create a copy of it with the ObjectPointer and Artificial flags
2819 /// set. If the type is not cached, a new one is created. This should
2820 /// never happen though, since creating a type for the implicit self
2821 /// argument implies that we already parsed the interface definition
2822 /// and the ivar declarations in the implementation.
2823 llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2825 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2826 if (CachedTy) Ty = CachedTy;
2827 else DEBUG(llvm::dbgs() << "No cached type for self.");
2828 return DBuilder.createObjectPointerType(Ty);
2831 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2832 llvm::Value *Storage,
2833 CGBuilderTy &Builder,
2834 const CGBlockInfo &blockInfo) {
2835 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2836 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2838 if (Builder.GetInsertBlock() == 0)
2841 bool isByRef = VD->hasAttr<BlocksAttr>();
2843 uint64_t XOffset = 0;
2844 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2847 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2849 Ty = getOrCreateType(VD->getType(), Unit);
2851 // Self is passed along as an implicit non-arg variable in a
2852 // block. Mark it as the object pointer.
2853 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2854 Ty = CreateSelfType(VD->getType(), Ty);
2856 // Get location information.
2857 unsigned Line = getLineNumber(VD->getLocation());
2858 unsigned Column = getColumnNumber(VD->getLocation());
2860 const llvm::DataLayout &target = CGM.getDataLayout();
2862 CharUnits offset = CharUnits::fromQuantity(
2863 target.getStructLayout(blockInfo.StructureType)
2864 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2866 SmallVector<llvm::Value *, 9> addr;
2867 llvm::Type *Int64Ty = CGM.Int64Ty;
2868 if (isa<llvm::AllocaInst>(Storage))
2869 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2870 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2871 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2873 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2874 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2875 // offset of __forwarding field
2876 offset = CGM.getContext()
2877 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2878 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2879 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2880 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2881 // offset of x field
2882 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2883 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2886 // Create the descriptor for the variable.
2887 llvm::DIVariable D =
2888 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2889 llvm::DIDescriptor(LexicalBlockStack.back()),
2890 VD->getName(), Unit, Line, Ty, addr);
2892 // Insert an llvm.dbg.declare into the current block.
2893 llvm::Instruction *Call =
2894 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2895 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2896 LexicalBlockStack.back()));
2899 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2900 /// variable declaration.
2901 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2903 CGBuilderTy &Builder) {
2904 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2905 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2909 struct BlockLayoutChunk {
2910 uint64_t OffsetInBits;
2911 const BlockDecl::Capture *Capture;
2913 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2914 return l.OffsetInBits < r.OffsetInBits;
2918 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2920 llvm::Value *LocalAddr,
2921 CGBuilderTy &Builder) {
2922 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2923 ASTContext &C = CGM.getContext();
2924 const BlockDecl *blockDecl = block.getBlockDecl();
2926 // Collect some general information about the block's location.
2927 SourceLocation loc = blockDecl->getCaretLocation();
2928 llvm::DIFile tunit = getOrCreateFile(loc);
2929 unsigned line = getLineNumber(loc);
2930 unsigned column = getColumnNumber(loc);
2932 // Build the debug-info type for the block literal.
2933 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2935 const llvm::StructLayout *blockLayout =
2936 CGM.getDataLayout().getStructLayout(block.StructureType);
2938 SmallVector<llvm::Value*, 16> fields;
2939 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2940 blockLayout->getElementOffsetInBits(0),
2942 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2943 blockLayout->getElementOffsetInBits(1),
2945 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2946 blockLayout->getElementOffsetInBits(2),
2948 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2949 blockLayout->getElementOffsetInBits(3),
2951 fields.push_back(createFieldType("__descriptor",
2952 C.getPointerType(block.NeedsCopyDispose ?
2953 C.getBlockDescriptorExtendedType() :
2954 C.getBlockDescriptorType()),
2956 blockLayout->getElementOffsetInBits(4),
2959 // We want to sort the captures by offset, not because DWARF
2960 // requires this, but because we're paranoid about debuggers.
2961 SmallVector<BlockLayoutChunk, 8> chunks;
2964 if (blockDecl->capturesCXXThis()) {
2965 BlockLayoutChunk chunk;
2966 chunk.OffsetInBits =
2967 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2969 chunks.push_back(chunk);
2972 // Variable captures.
2973 for (BlockDecl::capture_const_iterator
2974 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2976 const BlockDecl::Capture &capture = *i;
2977 const VarDecl *variable = capture.getVariable();
2978 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2980 // Ignore constant captures.
2981 if (captureInfo.isConstant())
2984 BlockLayoutChunk chunk;
2985 chunk.OffsetInBits =
2986 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2987 chunk.Capture = &capture;
2988 chunks.push_back(chunk);
2992 llvm::array_pod_sort(chunks.begin(), chunks.end());
2994 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2995 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2996 uint64_t offsetInBits = i->OffsetInBits;
2997 const BlockDecl::Capture *capture = i->Capture;
2999 // If we have a null capture, this must be the C++ 'this' capture.
3001 const CXXMethodDecl *method =
3002 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3003 QualType type = method->getThisType(C);
3005 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3006 offsetInBits, tunit, tunit));
3010 const VarDecl *variable = capture->getVariable();
3011 StringRef name = variable->getName();
3013 llvm::DIType fieldType;
3014 if (capture->isByRef()) {
3015 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3017 // FIXME: this creates a second copy of this type!
3019 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3020 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3021 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3022 ptrInfo.first, ptrInfo.second,
3023 offsetInBits, 0, fieldType);
3025 fieldType = createFieldType(name, variable->getType(), 0,
3026 loc, AS_public, offsetInBits, tunit, tunit);
3028 fields.push_back(fieldType);
3031 SmallString<36> typeName;
3032 llvm::raw_svector_ostream(typeName)
3033 << "__block_literal_" << CGM.getUniqueBlockCount();
3035 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3038 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3039 CGM.getContext().toBits(block.BlockSize),
3040 CGM.getContext().toBits(block.BlockAlign),
3041 0, llvm::DIType(), fieldsArray);
3042 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3044 // Get overall information about the block.
3045 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3046 llvm::MDNode *scope = LexicalBlockStack.back();
3048 // Create the descriptor for the parameter.
3049 llvm::DIVariable debugVar =
3050 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
3051 llvm::DIDescriptor(scope),
3052 Arg->getName(), tunit, line, type,
3053 CGM.getLangOpts().Optimize, flags,
3054 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3057 // Insert an llvm.dbg.value into the current block.
3058 llvm::Instruction *DbgVal =
3059 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
3060 Builder.GetInsertBlock());
3061 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3064 // Insert an llvm.dbg.declare into the current block.
3065 llvm::Instruction *DbgDecl =
3066 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3067 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3070 /// If D is an out-of-class definition of a static data member of a class, find
3071 /// its corresponding in-class declaration.
3073 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3074 if (!D->isStaticDataMember())
3075 return llvm::DIDerivedType();
3076 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3077 StaticDataMemberCache.find(D->getCanonicalDecl());
3078 if (MI != StaticDataMemberCache.end()) {
3079 assert(MI->second && "Static data member declaration should still exist");
3080 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
3083 // If the member wasn't found in the cache, lazily construct and add it to the
3084 // type (used when a limited form of the type is emitted).
3085 llvm::DICompositeType Ctxt(
3086 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3087 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3092 /// EmitGlobalVariable - Emit information about a global variable.
3093 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3095 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3096 // Create global variable debug descriptor.
3097 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3098 unsigned LineNo = getLineNumber(D->getLocation());
3100 setLocation(D->getLocation());
3102 QualType T = D->getType();
3103 if (T->isIncompleteArrayType()) {
3105 // CodeGen turns int[] into int[1] so we'll do the same here.
3106 llvm::APInt ConstVal(32, 1);
3107 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3109 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3110 ArrayType::Normal, 0);
3112 StringRef DeclName = D->getName();
3113 StringRef LinkageName;
3114 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3115 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3116 LinkageName = Var->getName();
3117 if (LinkageName == DeclName)
3118 LinkageName = StringRef();
3119 llvm::DIDescriptor DContext =
3120 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
3121 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3122 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3123 Var->hasInternalLinkage(), Var,
3124 getOrCreateStaticDataMemberDeclarationOrNull(D));
3125 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
3128 /// EmitGlobalVariable - Emit information about an objective-c interface.
3129 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3130 ObjCInterfaceDecl *ID) {
3131 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3132 // Create global variable debug descriptor.
3133 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3134 unsigned LineNo = getLineNumber(ID->getLocation());
3136 StringRef Name = ID->getName();
3138 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3139 if (T->isIncompleteArrayType()) {
3141 // CodeGen turns int[] into int[1] so we'll do the same here.
3142 llvm::APInt ConstVal(32, 1);
3143 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3145 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3146 ArrayType::Normal, 0);
3149 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3150 getOrCreateType(T, Unit),
3151 Var->hasInternalLinkage(), Var);
3154 /// EmitGlobalVariable - Emit global variable's debug info.
3155 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3156 llvm::Constant *Init) {
3157 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3158 // Create the descriptor for the variable.
3159 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3160 StringRef Name = VD->getName();
3161 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3162 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3163 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3164 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3165 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3167 // Do not use DIGlobalVariable for enums.
3168 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3170 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3171 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3172 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3173 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3176 llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3177 if (!LexicalBlockStack.empty())
3178 return llvm::DIScope(LexicalBlockStack.back());
3179 return getContextDescriptor(D);
3182 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3183 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3185 DBuilder.createImportedModule(
3186 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3187 getOrCreateNameSpace(UD.getNominatedNamespace()),
3188 getLineNumber(UD.getLocation()));
3191 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3192 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3194 assert(UD.shadow_size() &&
3195 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3196 // Emitting one decl is sufficient - debuggers can detect that this is an
3197 // overloaded name & provide lookup for all the overloads.
3198 const UsingShadowDecl &USD = **UD.shadow_begin();
3199 if (llvm::DIDescriptor Target =
3200 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3201 DBuilder.createImportedDeclaration(
3202 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3203 getLineNumber(USD.getLocation()));
3206 llvm::DIImportedEntity
3207 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3208 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3209 return llvm::DIImportedEntity(0);
3210 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3212 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3213 llvm::DIImportedEntity R(0);
3214 if (const NamespaceAliasDecl *Underlying =
3215 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3216 // This could cache & dedup here rather than relying on metadata deduping.
3217 R = DBuilder.createImportedModule(
3218 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3219 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3222 R = DBuilder.createImportedModule(
3223 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3224 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3225 getLineNumber(NA.getLocation()), NA.getName());
3230 /// getOrCreateNamesSpace - Return namespace descriptor for the given
3233 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3234 NSDecl = NSDecl->getCanonicalDecl();
3235 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
3236 NameSpaceCache.find(NSDecl);
3237 if (I != NameSpaceCache.end())
3238 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
3240 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3241 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3242 llvm::DIDescriptor Context =
3243 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3244 llvm::DINameSpace NS =
3245 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3246 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3250 void CGDebugInfo::finalize() {
3251 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3252 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3253 llvm::DIType Ty, RepTy;
3254 // Verify that the debug info still exists.
3255 if (llvm::Value *V = VI->second)
3256 Ty = llvm::DIType(cast<llvm::MDNode>(V));
3258 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3259 TypeCache.find(VI->first);
3260 if (it != TypeCache.end()) {
3261 // Verify that the debug info still exists.
3262 if (llvm::Value *V = it->second)
3263 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3266 if (Ty && Ty.isForwardDecl() && RepTy)
3267 Ty.replaceAllUsesWith(RepTy);
3270 // We keep our own list of retained types, because we need to look
3271 // up the final type in the type cache.
3272 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3273 RE = RetainedTypes.end(); RI != RE; ++RI)
3274 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3276 DBuilder.finalize();