blob: f735df5a29383f44df72d28746c5c3d32800896a [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie9dfd2432013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000017#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"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000032#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"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher688cf5b2013-07-14 21:12:44 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000046 CreateCompileUnit();
47}
48
49CGDebugInfo::~CGDebugInfo() {
50 assert(LexicalBlockStack.empty() &&
51 "Region stack mismatch, stack not empty!");
52}
53
54void CGDebugInfo::setLocation(SourceLocation Loc) {
55 // If the new location isn't valid return.
Adrian Prantl5f4554f2013-07-18 00:27:56 +000056 if (Loc.isInvalid()) return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000057
58 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
59
60 // If we've changed files in the middle of a lexical scope go ahead
61 // and create a new lexical scope with file node if it's different
62 // from the one in the scope.
63 if (LexicalBlockStack.empty()) return;
64
65 SourceManager &SM = CGM.getContext().getSourceManager();
66 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
67 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
68
69 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
70 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
71 return;
72
73 llvm::MDNode *LB = LexicalBlockStack.back();
74 llvm::DIScope Scope = llvm::DIScope(LB);
75 if (Scope.isLexicalBlockFile()) {
76 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
77 llvm::DIDescriptor D
78 = DBuilder.createLexicalBlockFile(LBF.getScope(),
79 getOrCreateFile(CurLoc));
80 llvm::MDNode *N = D;
81 LexicalBlockStack.pop_back();
82 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +000083 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000084 llvm::DIDescriptor D
85 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
86 llvm::MDNode *N = D;
87 LexicalBlockStack.pop_back();
88 LexicalBlockStack.push_back(N);
89 }
90}
91
92/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +000093llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000094 if (!Context)
95 return TheCU;
96
97 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
98 I = RegionMap.find(Context);
99 if (I != RegionMap.end()) {
100 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000101 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000102 }
103
104 // Check namespace.
105 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000106 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000107
David Blaikiebb000792013-04-19 06:56:38 +0000108 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
109 if (!RDecl->isDependentType())
110 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000111 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000112 return TheCU;
113}
114
115/// getFunctionName - Get function name for the given FunctionDecl. If the
116/// name is constructred on demand (e.g. C++ destructor) then the name
117/// is stored on the side.
118StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
119 assert (FD && "Invalid FunctionDecl!");
120 IdentifierInfo *FII = FD->getIdentifier();
121 FunctionTemplateSpecializationInfo *Info
122 = FD->getTemplateSpecializationInfo();
123 if (!Info && FII)
124 return FII->getName();
125
126 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000127 SmallString<128> NS;
128 llvm::raw_svector_ostream OS(NS);
129 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000130
131 // Add any template specialization args.
132 if (Info) {
133 const TemplateArgumentList *TArgs = Info->TemplateArguments;
134 const TemplateArgument *Args = TArgs->data();
135 unsigned NumArgs = TArgs->size();
136 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000137 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
138 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000139 }
140
141 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000142 OS.flush();
143 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
144 memcpy(StrPtr, NS.data(), NS.size());
145 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000146}
147
148StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
149 SmallString<256> MethodName;
150 llvm::raw_svector_ostream OS(MethodName);
151 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
152 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000153 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000154 dyn_cast<const ObjCImplementationDecl>(DC)) {
155 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000156 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000157 dyn_cast<const ObjCInterfaceDecl>(DC)) {
158 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000159 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000160 dyn_cast<const ObjCCategoryImplDecl>(DC)){
161 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
162 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000163 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000164 // We can extract the type of the class from the self pointer.
165 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
166 QualType ClassTy =
167 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
168 ClassTy.print(OS, PrintingPolicy(LangOptions()));
169 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000170 }
171 OS << ' ' << OMD->getSelector().getAsString() << ']';
172
173 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
174 memcpy(StrPtr, MethodName.begin(), OS.tell());
175 return StringRef(StrPtr, OS.tell());
176}
177
178/// getSelectorName - Return selector name. This is used for debugging
179/// info.
180StringRef CGDebugInfo::getSelectorName(Selector S) {
181 const std::string &SName = S.getAsString();
182 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
183 memcpy(StrPtr, SName.data(), SName.size());
184 return StringRef(StrPtr, SName.size());
185}
186
187/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000188StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000189CGDebugInfo::getClassName(const RecordDecl *RD) {
190 const ClassTemplateSpecializationDecl *Spec
191 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
192 if (!Spec)
193 return RD->getName();
194
195 const TemplateArgument *Args;
196 unsigned NumArgs;
197 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
198 const TemplateSpecializationType *TST =
199 cast<TemplateSpecializationType>(TAW->getType());
200 Args = TST->getArgs();
201 NumArgs = TST->getNumArgs();
202 } else {
203 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
204 Args = TemplateArgs.data();
205 NumArgs = TemplateArgs.size();
206 }
207 StringRef Name = RD->getIdentifier()->getName();
208 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000209 SmallString<128> TemplateArgList;
210 {
211 llvm::raw_svector_ostream OS(TemplateArgList);
212 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
213 Policy);
214 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000215
216 // Copy this name on the side and use its reference.
217 size_t Length = Name.size() + TemplateArgList.size();
218 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
219 memcpy(StrPtr, Name.data(), Name.size());
220 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
221 return StringRef(StrPtr, Length);
222}
223
224/// getOrCreateFile - Get the file debug info descriptor for the input location.
225llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
226 if (!Loc.isValid())
227 // If Location is not valid then use main input file.
228 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
229
230 SourceManager &SM = CGM.getContext().getSourceManager();
231 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
232
233 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
234 // If the location is not valid then use main input file.
235 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
236
237 // Cache the results.
238 const char *fname = PLoc.getFilename();
239 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
240 DIFileCache.find(fname);
241
242 if (it != DIFileCache.end()) {
243 // Verify that the information still exists.
244 if (llvm::Value *V = it->second)
245 return llvm::DIFile(cast<llvm::MDNode>(V));
246 }
247
248 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
249
250 DIFileCache[fname] = F;
251 return F;
252}
253
254/// getOrCreateMainFile - Get the file info for main compile unit.
255llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
256 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
257}
258
259/// getLineNumber - Get line number for the location. If location is invalid
260/// then use current location.
261unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
262 if (Loc.isInvalid() && CurLoc.isInvalid())
263 return 0;
264 SourceManager &SM = CGM.getContext().getSourceManager();
265 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
266 return PLoc.isValid()? PLoc.getLine() : 0;
267}
268
269/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000270unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000271 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000272 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000273 return 0;
274
275 // If the location is invalid then use the current column.
276 if (Loc.isInvalid() && CurLoc.isInvalid())
277 return 0;
278 SourceManager &SM = CGM.getContext().getSourceManager();
279 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
280 return PLoc.isValid()? PLoc.getColumn() : 0;
281}
282
283StringRef CGDebugInfo::getCurrentDirname() {
284 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
285 return CGM.getCodeGenOpts().DebugCompilationDir;
286
287 if (!CWDName.empty())
288 return CWDName;
289 SmallString<256> CWD;
290 llvm::sys::fs::current_path(CWD);
291 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
292 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
293 return CWDName = StringRef(CompDirnamePtr, CWD.size());
294}
295
296/// CreateCompileUnit - Create new compile unit.
297void CGDebugInfo::CreateCompileUnit() {
298
299 // Get absolute path name.
300 SourceManager &SM = CGM.getContext().getSourceManager();
301 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
302 if (MainFileName.empty())
303 MainFileName = "<unknown>";
304
305 // The main file name provided via the "-main-file-name" option contains just
306 // the file name itself with no path information. This file name may have had
307 // a relative path, so we look into the actual file entry for the main
308 // file to determine the real absolute path for the file.
309 std::string MainFileDir;
310 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
311 MainFileDir = MainFile->getDir()->getName();
312 if (MainFileDir != ".")
313 MainFileName = MainFileDir + "/" + MainFileName;
314 }
315
316 // Save filename string.
317 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
318 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
319 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000320
321 // Save split dwarf file string.
322 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
323 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
324 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
325 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopher6537f082013-05-16 00:45:12 +0000326
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000327 unsigned LangTag;
328 const LangOptions &LO = CGM.getLangOpts();
329 if (LO.CPlusPlus) {
330 if (LO.ObjC1)
331 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
332 else
333 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
334 } else if (LO.ObjC1) {
335 LangTag = llvm::dwarf::DW_LANG_ObjC;
336 } else if (LO.C99) {
337 LangTag = llvm::dwarf::DW_LANG_C99;
338 } else {
339 LangTag = llvm::dwarf::DW_LANG_C89;
340 }
341
342 std::string Producer = getClangFullVersion();
343
344 // Figure out which version of the ObjC runtime we have.
345 unsigned RuntimeVers = 0;
346 if (LO.ObjC1)
347 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
348
349 // Create new compile unit.
Eric Christopherbe5f1be2013-02-21 22:35:08 +0000350 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
351 Producer, LO.Optimize,
Eric Christopherff971d72013-02-22 23:50:16 +0000352 CGM.getCodeGenOpts().DwarfDebugFlags,
353 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000354 // FIXME - Eliminate TheCU.
355 TheCU = llvm::DICompileUnit(DBuilder.getCU());
356}
357
358/// CreateType - Get the Basic type from the cache or create a new
359/// one if necessary.
360llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
361 unsigned Encoding = 0;
362 StringRef BTName;
363 switch (BT->getKind()) {
364#define BUILTIN_TYPE(Id, SingletonId)
365#define PLACEHOLDER_TYPE(Id, SingletonId) \
366 case BuiltinType::Id:
367#include "clang/AST/BuiltinTypes.def"
368 case BuiltinType::Dependent:
369 llvm_unreachable("Unexpected builtin type");
370 case BuiltinType::NullPtr:
Peter Collingbourne24118f52013-06-27 22:51:01 +0000371 return DBuilder.createNullPtrType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000372 case BuiltinType::Void:
373 return llvm::DIType();
374 case BuiltinType::ObjCClass:
Manman Renb6b0a712013-07-02 19:01:53 +0000375 if (ClassTy.isType())
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000376 return ClassTy;
377 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
378 "objc_class", TheCU,
379 getOrCreateMainFile(), 0);
380 return ClassTy;
381 case BuiltinType::ObjCId: {
382 // typedef struct objc_class *Class;
383 // typedef struct objc_object {
384 // Class isa;
385 // } *id;
386
Manman Renb6b0a712013-07-02 19:01:53 +0000387 if (ObjTy.isCompositeType())
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000388 return ObjTy;
389
Manman Renb6b0a712013-07-02 19:01:53 +0000390 if (!ClassTy.isType())
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000391 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
392 "objc_class", TheCU,
393 getOrCreateMainFile(), 0);
394
395 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000396
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000397 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
398
Eric Christopherf068c922013-04-02 22:59:11 +0000399 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000400 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
401 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000402
Eric Christopherf068c922013-04-02 22:59:11 +0000403 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
404 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000405 return ObjTy;
406 }
407 case BuiltinType::ObjCSel: {
Manman Renb6b0a712013-07-02 19:01:53 +0000408 if (SelTy.isType())
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000409 return SelTy;
410 SelTy =
411 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
412 "objc_selector", TheCU, getOrCreateMainFile(),
413 0);
414 return SelTy;
415 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000416
417 case BuiltinType::OCLImage1d:
418 return getOrCreateStructPtrType("opencl_image1d_t",
419 OCLImage1dDITy);
420 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000421 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000422 OCLImage1dArrayDITy);
423 case BuiltinType::OCLImage1dBuffer:
424 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
425 OCLImage1dBufferDITy);
426 case BuiltinType::OCLImage2d:
427 return getOrCreateStructPtrType("opencl_image2d_t",
428 OCLImage2dDITy);
429 case BuiltinType::OCLImage2dArray:
430 return getOrCreateStructPtrType("opencl_image2d_array_t",
431 OCLImage2dArrayDITy);
432 case BuiltinType::OCLImage3d:
433 return getOrCreateStructPtrType("opencl_image3d_t",
434 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000435 case BuiltinType::OCLSampler:
436 return DBuilder.createBasicType("opencl_sampler_t",
437 CGM.getContext().getTypeSize(BT),
438 CGM.getContext().getTypeAlign(BT),
439 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000440 case BuiltinType::OCLEvent:
441 return getOrCreateStructPtrType("opencl_event_t",
442 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000443
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000444 case BuiltinType::UChar:
445 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
446 case BuiltinType::Char_S:
447 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
448 case BuiltinType::Char16:
449 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
450 case BuiltinType::UShort:
451 case BuiltinType::UInt:
452 case BuiltinType::UInt128:
453 case BuiltinType::ULong:
454 case BuiltinType::WChar_U:
455 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
456 case BuiltinType::Short:
457 case BuiltinType::Int:
458 case BuiltinType::Int128:
459 case BuiltinType::Long:
460 case BuiltinType::WChar_S:
461 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
462 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
463 case BuiltinType::Half:
464 case BuiltinType::Float:
465 case BuiltinType::LongDouble:
466 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
467 }
468
469 switch (BT->getKind()) {
470 case BuiltinType::Long: BTName = "long int"; break;
471 case BuiltinType::LongLong: BTName = "long long int"; break;
472 case BuiltinType::ULong: BTName = "long unsigned int"; break;
473 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
474 default:
475 BTName = BT->getName(CGM.getLangOpts());
476 break;
477 }
478 // Bit size, align and offset of the type.
479 uint64_t Size = CGM.getContext().getTypeSize(BT);
480 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000481 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000482 DBuilder.createBasicType(BTName, Size, Align, Encoding);
483 return DbgTy;
484}
485
486llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
487 // Bit size, align and offset of the type.
488 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
489 if (Ty->isComplexIntegerType())
490 Encoding = llvm::dwarf::DW_ATE_lo_user;
491
492 uint64_t Size = CGM.getContext().getTypeSize(Ty);
493 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000494 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000495 DBuilder.createBasicType("complex", Size, Align, Encoding);
496
497 return DbgTy;
498}
499
500/// CreateCVRType - Get the qualified type from the cache or create
501/// a new one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +0000502llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
503 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000504 QualifierCollector Qc;
505 const Type *T = Qc.strip(Ty);
506
507 // Ignore these qualifiers for now.
508 Qc.removeObjCGCAttr();
509 Qc.removeAddressSpace();
510 Qc.removeObjCLifetime();
511
512 // We will create one Derived type for one qualifier and recurse to handle any
513 // additional ones.
514 unsigned Tag;
515 if (Qc.hasConst()) {
516 Tag = llvm::dwarf::DW_TAG_const_type;
517 Qc.removeConst();
518 } else if (Qc.hasVolatile()) {
519 Tag = llvm::dwarf::DW_TAG_volatile_type;
520 Qc.removeVolatile();
521 } else if (Qc.hasRestrict()) {
522 Tag = llvm::dwarf::DW_TAG_restrict_type;
523 Qc.removeRestrict();
524 } else {
525 assert(Qc.empty() && "Unknown type qualifier for debug info");
526 return getOrCreateType(QualType(T, 0), Unit);
527 }
528
Eric Christopher56b108a2013-06-07 22:54:39 +0000529 llvm::DIType FromTy =
530 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000531
532 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
533 // CVR derived types.
534 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000535
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000536 return DbgTy;
537}
538
539llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
540 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000541
542 // The frontend treats 'id' as a typedef to an ObjCObjectType,
543 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
544 // debug info, we want to emit 'id' in both cases.
545 if (Ty->isObjCQualifiedIdType())
546 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
547
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000548 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000549 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000550 Ty->getPointeeType(), Unit);
551 return DbgTy;
552}
553
554llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
555 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000556 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000557 Ty->getPointeeType(), Unit);
558}
559
560// Creates a forward declaration for a RecordDecl in the given context.
561llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
562 llvm::DIDescriptor Ctx) {
563 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
564 unsigned Line = getLineNumber(RD->getLocation());
565 StringRef RDName = getClassName(RD);
566
567 unsigned Tag = 0;
568 if (RD->isStruct() || RD->isInterface())
569 Tag = llvm::dwarf::DW_TAG_structure_type;
570 else if (RD->isUnion())
571 Tag = llvm::dwarf::DW_TAG_union_type;
572 else {
573 assert(RD->isClass());
574 Tag = llvm::dwarf::DW_TAG_class_type;
575 }
576
577 // Create the type.
578 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
579}
580
581// Walk up the context chain and create forward decls for record decls,
582// and normal descriptors for namespaces.
583llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
584 if (!Context)
585 return TheCU;
586
587 // See if we already have the parent.
588 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
589 I = RegionMap.find(Context);
590 if (I != RegionMap.end()) {
591 llvm::Value *V = I->second;
592 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
593 }
Eric Christopher6537f082013-05-16 00:45:12 +0000594
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000595 // Check namespace.
596 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
597 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
598
599 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
600 if (!RD->isDependentType()) {
Eric Christopherf0890c42013-05-16 00:52:20 +0000601 llvm::DIType Ty =
602 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
603 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000604 return llvm::DIDescriptor(Ty);
605 }
606 }
607 return TheCU;
608}
609
David Blaikieb0f77b02013-05-24 21:33:22 +0000610/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000611/// then emit record's fwd if debug info size reduction is enabled.
David Blaikieb0f77b02013-05-24 21:33:22 +0000612llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(QualType PointeeTy,
613 llvm::DIFile Unit) {
David Blaikie9faebd22013-05-20 04:58:53 +0000614 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000615 return getOrCreateType(PointeeTy, Unit);
David Blaikie5f6e2f42013-06-05 05:32:23 +0000616 return getOrCreateType(PointeeTy, Unit, true);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000617}
618
619llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000620 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000621 QualType PointeeTy,
622 llvm::DIFile Unit) {
623 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
624 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikieb0f77b02013-05-24 21:33:22 +0000625 return DBuilder.createReferenceType(
626 Tag, getOrCreateTypeDeclaration(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000627
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000628 // Bit size, align and offset of the type.
629 // Size is always the size of a pointer. We can't use getTypeSize here
630 // because that does not return the correct value for references.
631 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000632 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000633 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
634
David Blaikieb0f77b02013-05-24 21:33:22 +0000635 return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000636 Size, Align);
637}
638
Eric Christopherf0890c42013-05-16 00:52:20 +0000639llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
640 llvm::DIType &Cache) {
Manman Renb6b0a712013-07-02 19:01:53 +0000641 if (Cache.isType())
Guy Benyeib13621d2012-12-18 14:38:23 +0000642 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000643 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
644 TheCU, getOrCreateMainFile(), 0);
645 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
646 Cache = DBuilder.createPointerType(Cache, Size);
647 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000648}
649
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000650llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
651 llvm::DIFile Unit) {
Eric Christopher688cf5b2013-07-14 21:12:44 +0000652 if (BlockLiteralGeneric.isType())
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000653 return BlockLiteralGeneric;
654
655 SmallVector<llvm::Value *, 8> EltTys;
656 llvm::DIType FieldTy;
657 QualType FType;
658 uint64_t FieldSize, FieldOffset;
659 unsigned FieldAlign;
660 llvm::DIArray Elements;
661 llvm::DIType EltTy, DescTy;
662
663 FieldOffset = 0;
664 FType = CGM.getContext().UnsignedLongTy;
665 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
666 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
667
668 Elements = DBuilder.getOrCreateArray(EltTys);
669 EltTys.clear();
670
671 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
672 unsigned LineNo = getLineNumber(CurLoc);
673
674 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
675 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000676 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000677
678 // Bit size, align and offset of the type.
679 uint64_t Size = CGM.getContext().getTypeSize(Ty);
680
681 DescTy = DBuilder.createPointerType(EltTy, Size);
682
683 FieldOffset = 0;
684 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
685 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
686 FType = CGM.getContext().IntTy;
687 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
688 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
689 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
690 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
691
692 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
693 FieldTy = DescTy;
694 FieldSize = CGM.getContext().getTypeSize(Ty);
695 FieldAlign = CGM.getContext().getTypeAlign(Ty);
696 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
697 LineNo, FieldSize, FieldAlign,
698 FieldOffset, 0, FieldTy);
699 EltTys.push_back(FieldTy);
700
701 FieldOffset += FieldSize;
702 Elements = DBuilder.getOrCreateArray(EltTys);
703
704 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
705 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000706 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000707
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000708 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
709 return BlockLiteralGeneric;
710}
711
David Blaikie5f6e2f42013-06-05 05:32:23 +0000712llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
713 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000714 // Typedefs are derived from some other type. If we have a typedef of a
715 // typedef, make sure to emit the whole chain.
David Blaikieb0f77b02013-05-24 21:33:22 +0000716 llvm::DIType Src =
David Blaikie5f6e2f42013-06-05 05:32:23 +0000717 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Manman Renb6b0a712013-07-02 19:01:53 +0000718 if (!Src.isType())
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000719 return llvm::DIType();
720 // We don't set size information, but do specify where the typedef was
721 // declared.
722 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
723 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000724
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000725 llvm::DIDescriptor TypedefContext =
726 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000727
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000728 return
729 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
730}
731
732llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
733 llvm::DIFile Unit) {
734 SmallVector<llvm::Value *, 16> EltTys;
735
736 // Add the result type at least.
737 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
738
739 // Set up remainder of arguments if there is a prototype.
740 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
741 if (isa<FunctionNoProtoType>(Ty))
742 EltTys.push_back(DBuilder.createUnspecifiedParameter());
743 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
744 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
745 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
746 }
747
748 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
749 return DBuilder.createSubroutineType(Unit, EltTypeArray);
750}
751
752
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000753llvm::DIType CGDebugInfo::createFieldType(StringRef name,
754 QualType type,
755 uint64_t sizeInBitsOverride,
756 SourceLocation loc,
757 AccessSpecifier AS,
758 uint64_t offsetInBits,
759 llvm::DIFile tunit,
760 llvm::DIDescriptor scope) {
761 llvm::DIType debugType = getOrCreateType(type, tunit);
762
763 // Get the location for the field.
764 llvm::DIFile file = getOrCreateFile(loc);
765 unsigned line = getLineNumber(loc);
766
767 uint64_t sizeInBits = 0;
768 unsigned alignInBits = 0;
769 if (!type->isIncompleteArrayType()) {
770 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
771
772 if (sizeInBitsOverride)
773 sizeInBits = sizeInBitsOverride;
774 }
775
776 unsigned flags = 0;
777 if (AS == clang::AS_private)
778 flags |= llvm::DIDescriptor::FlagPrivate;
779 else if (AS == clang::AS_protected)
780 flags |= llvm::DIDescriptor::FlagProtected;
781
782 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
783 alignInBits, offsetInBits, flags, debugType);
784}
785
Eric Christopher0395de32013-01-16 01:22:32 +0000786/// CollectRecordLambdaFields - Helper for CollectRecordFields.
787void CGDebugInfo::
788CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
789 SmallVectorImpl<llvm::Value *> &elements,
790 llvm::DIType RecordTy) {
791 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
792 // has the name and the location of the variable so we should iterate over
793 // both concurrently.
794 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
795 RecordDecl::field_iterator Field = CXXDecl->field_begin();
796 unsigned fieldno = 0;
797 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
798 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
799 const LambdaExpr::Capture C = *I;
800 if (C.capturesVariable()) {
801 VarDecl *V = C.getCapturedVar();
802 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
803 StringRef VName = V->getName();
804 uint64_t SizeInBitsOverride = 0;
805 if (Field->isBitField()) {
806 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
807 assert(SizeInBitsOverride && "found named 0-width bitfield");
808 }
809 llvm::DIType fieldType
810 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
811 C.getLocation(), Field->getAccess(),
812 layout.getFieldOffset(fieldno), VUnit, RecordTy);
813 elements.push_back(fieldType);
814 } else {
815 // TODO: Need to handle 'this' in some way by probably renaming the
816 // this of the lambda class and having a field member of 'this' or
817 // by using AT_object_pointer for the function and having that be
818 // used as 'this' for semantic references.
819 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
820 FieldDecl *f = *Field;
821 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
822 QualType type = f->getType();
823 llvm::DIType fieldType
824 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
825 layout.getFieldOffset(fieldno), VUnit, RecordTy);
826
827 elements.push_back(fieldType);
828 }
829 }
830}
831
832/// CollectRecordStaticField - Helper for CollectRecordFields.
833void CGDebugInfo::
834CollectRecordStaticField(const VarDecl *Var,
835 SmallVectorImpl<llvm::Value *> &elements,
836 llvm::DIType RecordTy) {
837 // Create the descriptor for the static variable, with or without
838 // constant initializers.
839 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
840 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
841
842 // Do not describe enums as static members.
843 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
844 return;
845
846 unsigned LineNumber = getLineNumber(Var->getLocation());
847 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000848 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000849 if (Var->getInit()) {
850 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000851 if (Value) {
852 if (Value->isInt())
853 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
854 if (Value->isFloat())
855 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
856 }
Eric Christopher0395de32013-01-16 01:22:32 +0000857 }
858
859 unsigned Flags = 0;
860 AccessSpecifier Access = Var->getAccess();
861 if (Access == clang::AS_private)
862 Flags |= llvm::DIDescriptor::FlagPrivate;
863 else if (Access == clang::AS_protected)
864 Flags |= llvm::DIDescriptor::FlagProtected;
865
866 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000867 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000868 elements.push_back(GV);
869 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
870}
871
872/// CollectRecordNormalField - Helper for CollectRecordFields.
873void CGDebugInfo::
874CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
875 llvm::DIFile tunit,
876 SmallVectorImpl<llvm::Value *> &elements,
877 llvm::DIType RecordTy) {
878 StringRef name = field->getName();
879 QualType type = field->getType();
880
881 // Ignore unnamed fields unless they're anonymous structs/unions.
882 if (name.empty() && !type->isRecordType())
883 return;
884
885 uint64_t SizeInBitsOverride = 0;
886 if (field->isBitField()) {
887 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
888 assert(SizeInBitsOverride && "found named 0-width bitfield");
889 }
890
891 llvm::DIType fieldType
892 = createFieldType(name, type, SizeInBitsOverride,
893 field->getLocation(), field->getAccess(),
894 OffsetInBits, tunit, RecordTy);
895
896 elements.push_back(fieldType);
897}
898
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000899/// CollectRecordFields - A helper function to collect debug info for
900/// record fields. This is used while creating debug info entry for a Record.
901void CGDebugInfo::
902CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
903 SmallVectorImpl<llvm::Value *> &elements,
904 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000905 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
906
Eric Christopher0395de32013-01-16 01:22:32 +0000907 if (CXXDecl && CXXDecl->isLambda())
908 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
909 else {
910 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000911
Eric Christopher0395de32013-01-16 01:22:32 +0000912 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000913 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000914
Eric Christopher0395de32013-01-16 01:22:32 +0000915 // Static and non-static members should appear in the same order as
916 // the corresponding declarations in the source program.
917 for (RecordDecl::decl_iterator I = record->decls_begin(),
918 E = record->decls_end(); I != E; ++I)
919 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
920 CollectRecordStaticField(V, elements, RecordTy);
921 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000922 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
923 tunit, elements, RecordTy);
924
925 // Bump field number for next field.
926 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000927 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000928 }
929}
930
931/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
932/// function type is not updated to include implicit "this" pointer. Use this
933/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000934llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000935CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
936 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000937 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000938 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000939 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000940 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
941 Func, Unit);
942}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000943
David Blaikie9a845292013-05-22 23:22:42 +0000944llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000945 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000946 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000947 llvm::DIArray Args = llvm::DICompositeType(
948 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000949 assert (Args.getNumElements() && "Invalid number of arguments!");
950
951 SmallVector<llvm::Value *, 16> Elts;
952
953 // First element is always return type. For 'void' functions it is NULL.
954 Elts.push_back(Args.getElement(0));
955
David Blaikie67f8b5e2013-01-07 22:24:59 +0000956 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000957 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000958 if (isa<ClassTemplateSpecializationDecl>(RD)) {
959 // Create pointer type directly in this case.
960 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
961 QualType PointeeTy = ThisPtrTy->getPointeeType();
962 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000963 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000964 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
965 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +0000966 llvm::DIType ThisPtrType =
967 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000968 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
969 // TODO: This and the artificial type below are misleading, the
970 // types aren't artificial the argument is, but the current
971 // metadata doesn't represent that.
972 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
973 Elts.push_back(ThisPtrType);
974 } else {
975 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
976 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
977 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
978 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000979 }
980
981 // Copy rest of the arguments.
982 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
983 Elts.push_back(Args.getElement(i));
984
985 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
986
987 return DBuilder.createSubroutineType(Unit, EltTypeArray);
988}
989
Eric Christopher6537f082013-05-16 00:45:12 +0000990/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000991/// inside a function.
992static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
993 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
994 return isFunctionLocalClass(NRD);
995 if (isa<FunctionDecl>(RD->getDeclContext()))
996 return true;
997 return false;
998}
999
1000/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1001/// a single member function GlobalDecl.
1002llvm::DISubprogram
1003CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1004 llvm::DIFile Unit,
1005 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001006 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001007 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001008
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001009 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001010 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001011
1012 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1013 // make sense to give a single ctor/dtor a linkage name.
1014 StringRef MethodLinkageName;
1015 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1016 MethodLinkageName = CGM.getMangledName(Method);
1017
1018 // Get the location for the method.
1019 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1020 unsigned MethodLine = getLineNumber(Method->getLocation());
1021
1022 // Collect virtual method info.
1023 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001024 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001025 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001026
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001027 if (Method->isVirtual()) {
1028 if (Method->isPure())
1029 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1030 else
1031 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001032
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001033 // It doesn't make sense to give a virtual destructor a vtable index,
1034 // since a single destructor has two entries in the vtable.
1035 if (!isa<CXXDestructorDecl>(Method))
1036 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1037 ContainingType = RecordTy;
1038 }
1039
1040 unsigned Flags = 0;
1041 if (Method->isImplicit())
1042 Flags |= llvm::DIDescriptor::FlagArtificial;
1043 AccessSpecifier Access = Method->getAccess();
1044 if (Access == clang::AS_private)
1045 Flags |= llvm::DIDescriptor::FlagPrivate;
1046 else if (Access == clang::AS_protected)
1047 Flags |= llvm::DIDescriptor::FlagProtected;
1048 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1049 if (CXXC->isExplicit())
1050 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001051 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001052 dyn_cast<CXXConversionDecl>(Method)) {
1053 if (CXXC->isExplicit())
1054 Flags |= llvm::DIDescriptor::FlagExplicit;
1055 }
1056 if (Method->hasPrototype())
1057 Flags |= llvm::DIDescriptor::FlagPrototyped;
1058
1059 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1060 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001061 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001062 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001063 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001064 /* isDefinition=*/ false,
1065 Virtuality, VIndex, ContainingType,
1066 Flags, CGM.getLangOpts().Optimize, NULL,
1067 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001068
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001069 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1070
1071 return SP;
1072}
1073
1074/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001075/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001076/// a Record.
1077void CGDebugInfo::
1078CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1079 SmallVectorImpl<llvm::Value *> &EltTys,
1080 llvm::DIType RecordTy) {
1081
1082 // Since we want more than just the individual member decls if we
1083 // have templated functions iterate over every declaration to gather
1084 // the functions.
1085 for(DeclContext::decl_iterator I = RD->decls_begin(),
1086 E = RD->decls_end(); I != E; ++I) {
1087 Decl *D = *I;
1088 if (D->isImplicit() && !D->isUsed())
1089 continue;
1090
1091 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1092 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1093 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1094 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1095 SE = FTD->spec_end(); SI != SE; ++SI)
1096 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1097 RecordTy));
1098 }
Eric Christopher6537f082013-05-16 00:45:12 +00001099}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001100
1101/// CollectCXXFriends - A helper function to collect debug info for
1102/// C++ base classes. This is used while creating debug info entry for
1103/// a Record.
1104void CGDebugInfo::
1105CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1106 SmallVectorImpl<llvm::Value *> &EltTys,
1107 llvm::DIType RecordTy) {
1108 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1109 BE = RD->friend_end(); BI != BE; ++BI) {
1110 if ((*BI)->isUnsupportedFriend())
1111 continue;
1112 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001113 EltTys.push_back(DBuilder.createFriend(RecordTy,
1114 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001115 Unit)));
1116 }
1117}
1118
1119/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001120/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001121/// a Record.
1122void CGDebugInfo::
1123CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1124 SmallVectorImpl<llvm::Value *> &EltTys,
1125 llvm::DIType RecordTy) {
1126
1127 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1128 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1129 BE = RD->bases_end(); BI != BE; ++BI) {
1130 unsigned BFlags = 0;
1131 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001132
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001133 const CXXRecordDecl *Base =
1134 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001135
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001136 if (BI->isVirtual()) {
1137 // virtual base offset offset is -ve. The code generator emits dwarf
1138 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001139 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001140 0 - CGM.getVTableContext()
1141 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1142 BFlags = llvm::DIDescriptor::FlagVirtual;
1143 } else
1144 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1145 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1146 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001147
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001148 AccessSpecifier Access = BI->getAccessSpecifier();
1149 if (Access == clang::AS_private)
1150 BFlags |= llvm::DIDescriptor::FlagPrivate;
1151 else if (Access == clang::AS_protected)
1152 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001153
1154 llvm::DIType DTy =
1155 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001156 getOrCreateType(BI->getType(), Unit),
1157 BaseOffset, BFlags);
1158 EltTys.push_back(DTy);
1159 }
1160}
1161
1162/// CollectTemplateParams - A helper function to collect template parameters.
1163llvm::DIArray CGDebugInfo::
1164CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001165 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001166 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001167 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001168 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1169 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001170 StringRef Name;
1171 if (TPList)
1172 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001173 switch (TA.getKind()) {
1174 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001175 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1176 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001177 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001178 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001179 } break;
1180 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001181 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1182 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001183 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001184 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001185 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1186 TemplateParams.push_back(TVP);
1187 } break;
1188 case TemplateArgument::Declaration: {
1189 const ValueDecl *D = TA.getAsDecl();
1190 bool InstanceMember = D->isCXXInstanceMember();
1191 QualType T = InstanceMember
1192 ? CGM.getContext().getMemberPointerType(
1193 D->getType(), cast<RecordDecl>(D->getDeclContext())
1194 ->getTypeForDecl())
1195 : CGM.getContext().getPointerType(D->getType());
1196 llvm::DIType TTy = getOrCreateType(T, Unit);
1197 llvm::Value *V = 0;
1198 // Variable pointer template parameters have a value that is the address
1199 // of the variable.
1200 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1201 V = CGM.GetAddrOfGlobalVar(VD);
1202 // Member function pointers have special support for building them, though
1203 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001204 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001205 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1206 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001207 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1208 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001209 // Member data pointers have special handling too to compute the fixed
1210 // offset within the object.
1211 if (isa<FieldDecl>(D)) {
1212 // These five lines (& possibly the above member function pointer
1213 // handling) might be able to be refactored to use similar code in
1214 // CodeGenModule::getMemberPointerConstant
1215 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1216 CharUnits chars =
1217 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1218 V = CGM.getCXXABI().EmitMemberDataPointer(
1219 cast<MemberPointerType>(T.getTypePtr()), chars);
1220 }
1221 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001222 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001223 TemplateParams.push_back(TVP);
1224 } break;
1225 case TemplateArgument::NullPtr: {
1226 QualType T = TA.getNullPtrType();
1227 llvm::DIType TTy = getOrCreateType(T, Unit);
1228 llvm::Value *V = 0;
1229 // Special case member data pointer null values since they're actually -1
1230 // instead of zero.
1231 if (const MemberPointerType *MPT =
1232 dyn_cast<MemberPointerType>(T.getTypePtr()))
1233 // But treat member function pointers as simple zero integers because
1234 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1235 // CodeGen grows handling for values of non-null member function
1236 // pointers then perhaps we could remove this special case and rely on
1237 // EmitNullMemberPointer for member function pointers.
1238 if (MPT->isMemberDataPointer())
1239 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1240 if (!V)
1241 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1242 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001243 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001244 TemplateParams.push_back(TVP);
1245 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001246 case TemplateArgument::Template: {
1247 llvm::DITemplateValueParameter TVP =
1248 DBuilder.createTemplateTemplateParameter(
1249 TheCU, Name, llvm::DIType(),
1250 TA.getAsTemplate().getAsTemplateDecl()
1251 ->getQualifiedNameAsString());
1252 TemplateParams.push_back(TVP);
1253 } break;
1254 case TemplateArgument::Pack: {
1255 llvm::DITemplateValueParameter TVP =
1256 DBuilder.createTemplateParameterPack(
1257 TheCU, Name, llvm::DIType(),
1258 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1259 TemplateParams.push_back(TVP);
1260 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001261 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001262 case TemplateArgument::Expression:
1263 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001264 case TemplateArgument::Null:
1265 llvm_unreachable(
1266 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001267 }
1268 }
1269 return DBuilder.getOrCreateArray(TemplateParams);
1270}
1271
1272/// CollectFunctionTemplateParams - A helper function to collect debug
1273/// info for function template parameters.
1274llvm::DIArray CGDebugInfo::
1275CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1276 if (FD->getTemplatedKind() ==
1277 FunctionDecl::TK_FunctionTemplateSpecialization) {
1278 const TemplateParameterList *TList =
1279 FD->getTemplateSpecializationInfo()->getTemplate()
1280 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001281 return CollectTemplateParams(
1282 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001283 }
1284 return llvm::DIArray();
1285}
1286
1287/// CollectCXXTemplateParams - A helper function to collect debug info for
1288/// template parameters.
1289llvm::DIArray CGDebugInfo::
1290CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1291 llvm::DIFile Unit) {
1292 llvm::PointerUnion<ClassTemplateDecl *,
1293 ClassTemplatePartialSpecializationDecl *>
1294 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001295
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001296 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1297 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1298 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1299 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001300 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001301}
1302
1303/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1304llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1305 if (VTablePtrType.isValid())
1306 return VTablePtrType;
1307
1308 ASTContext &Context = CGM.getContext();
1309
1310 /* Function type */
1311 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1312 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1313 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1314 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1315 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1316 "__vtbl_ptr_type");
1317 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1318 return VTablePtrType;
1319}
1320
1321/// getVTableName - Get vtable name for the given Class.
1322StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1323 // Construct gdb compatible name name.
1324 std::string Name = "_vptr$" + RD->getNameAsString();
1325
1326 // Copy this name on the side and use its reference.
1327 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1328 memcpy(StrPtr, Name.data(), Name.length());
1329 return StringRef(StrPtr, Name.length());
1330}
1331
1332
1333/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1334/// debug info entry in EltTys vector.
1335void CGDebugInfo::
1336CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1337 SmallVectorImpl<llvm::Value *> &EltTys) {
1338 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1339
1340 // If there is a primary base then it will hold vtable info.
1341 if (RL.getPrimaryBase())
1342 return;
1343
1344 // If this class is not dynamic then there is not any vtable info to collect.
1345 if (!RD->isDynamicClass())
1346 return;
1347
1348 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1349 llvm::DIType VPTR
1350 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001351 0, Size, 0, 0,
1352 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001353 getOrCreateVTablePtrType(Unit));
1354 EltTys.push_back(VPTR);
1355}
1356
Eric Christopher6537f082013-05-16 00:45:12 +00001357/// getOrCreateRecordType - Emit record type's standalone debug info.
1358llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001359 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001360 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001361 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1362 return T;
1363}
1364
1365/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1366/// debug info.
1367llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001368 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001369 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001370 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001371 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001372 return T;
1373}
1374
1375/// CreateType - get structure or union type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001376llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001377 RecordDecl *RD = Ty->getDecl();
Adrian Prantl776bfa12013-06-18 23:32:21 +00001378 // Limited debug info should only remove struct definitions that can
1379 // safely be replaced by a forward declaration in the source code.
David Blaikie658cd2c2013-07-13 21:08:14 +00001380 if (DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration &&
1381 !RD->isCompleteDefinitionRequired()) {
Adrian Prantl776bfa12013-06-18 23:32:21 +00001382 // FIXME: This implementation is problematic; there are some test
1383 // cases where we violate the above principle, such as
1384 // test/CodeGen/debug-info-records.c .
David Blaikie5f6e2f42013-06-05 05:32:23 +00001385 llvm::DIDescriptor FDContext =
1386 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1387 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1388 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1389 return RetTy;
1390 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001391
1392 // Get overall information about the record type for the debug info.
1393 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1394
1395 // Records and classes and unions can all be recursive. To handle them, we
1396 // first generate a debug descriptor for the struct as a forward declaration.
1397 // Then (if it is a definition) we go through and get debug info for all of
1398 // its members. Finally, we create a descriptor for the complete type (which
1399 // may refer to the forward decl if the struct is recursive) and replace all
1400 // uses of the forward declaration with the final definition.
1401
Eric Christopherf068c922013-04-02 22:59:11 +00001402 llvm::DICompositeType FwdDecl(
1403 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001404 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001405 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001406
1407 if (FwdDecl.isForwardDecl())
1408 return FwdDecl;
1409
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001410 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001411 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001412 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1413
Adrian Prantl4919de62013-03-06 22:03:30 +00001414 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001415 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1416
1417 // Convert all the elements.
1418 SmallVector<llvm::Value *, 16> EltTys;
1419
1420 // Note: The split of CXXDecl information here is intentional, the
1421 // gdb tests will depend on a certain ordering at printout. The debug
1422 // information offsets are still correct if we merge them all together
1423 // though.
1424 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1425 if (CXXDecl) {
1426 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1427 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1428 }
1429
Eric Christopher0395de32013-01-16 01:22:32 +00001430 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001431 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1432 llvm::DIArray TParamsArray;
1433 if (CXXDecl) {
1434 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1435 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1436 if (const ClassTemplateSpecializationDecl *TSpecial
1437 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1438 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1439 }
1440
1441 LexicalBlockStack.pop_back();
1442 RegionMap.erase(Ty->getDecl());
1443
1444 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001445 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001446
Eric Christopherf068c922013-04-02 22:59:11 +00001447 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1448 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001449}
1450
1451/// CreateType - get objective-c object type.
1452llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1453 llvm::DIFile Unit) {
1454 // Ignore protocols.
1455 return getOrCreateType(Ty->getBaseType(), Unit);
1456}
1457
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001458
1459/// \return true if Getter has the default name for the property PD.
1460static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1461 const ObjCMethodDecl *Getter) {
1462 assert(PD);
1463 if (!Getter)
1464 return true;
1465
1466 assert(Getter->getDeclName().isObjCZeroArgSelector());
1467 return PD->getName() ==
1468 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1469}
1470
1471/// \return true if Setter has the default name for the property PD.
1472static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1473 const ObjCMethodDecl *Setter) {
1474 assert(PD);
1475 if (!Setter)
1476 return true;
1477
1478 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001479 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001480 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1481}
1482
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001483/// CreateType - get objective-c interface type.
1484llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1485 llvm::DIFile Unit) {
1486 ObjCInterfaceDecl *ID = Ty->getDecl();
1487 if (!ID)
1488 return llvm::DIType();
1489
1490 // Get overall information about the record type for the debug info.
1491 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1492 unsigned Line = getLineNumber(ID->getLocation());
1493 unsigned RuntimeLang = TheCU.getLanguage();
1494
1495 // If this is just a forward declaration return a special forward-declaration
1496 // debug type since we won't be able to lay out the entire type.
1497 ObjCInterfaceDecl *Def = ID->getDefinition();
1498 if (!Def) {
1499 llvm::DIType FwdDecl =
1500 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001501 ID->getName(), TheCU, DefUnit, Line,
1502 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001503 return FwdDecl;
1504 }
1505
1506 ID = Def;
1507
1508 // Bit size, align and offset of the type.
1509 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1510 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1511
1512 unsigned Flags = 0;
1513 if (ID->getImplementation())
1514 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1515
Eric Christopherf068c922013-04-02 22:59:11 +00001516 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001517 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1518 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001519 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001520
1521 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1522 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001523 QualType QualTy = QualType(Ty, 0);
1524 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001525
Eric Christopherd3003dc2013-07-14 21:00:07 +00001526 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001527 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001528 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1529
1530 // Convert all the elements.
1531 SmallVector<llvm::Value *, 16> EltTys;
1532
1533 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1534 if (SClass) {
1535 llvm::DIType SClassTy =
1536 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1537 if (!SClassTy.isValid())
1538 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001539
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001540 llvm::DIType InhTag =
1541 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1542 EltTys.push_back(InhTag);
1543 }
1544
Eric Christopherd3003dc2013-07-14 21:00:07 +00001545 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001546 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1547 E = ID->prop_end(); I != E; ++I) {
1548 const ObjCPropertyDecl *PD = *I;
1549 SourceLocation Loc = PD->getLocation();
1550 llvm::DIFile PUnit = getOrCreateFile(Loc);
1551 unsigned PLine = getLineNumber(Loc);
1552 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1553 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1554 llvm::MDNode *PropertyNode =
1555 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001556 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001557 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001558 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001559 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001560 getSelectorName(PD->getSetterName()),
1561 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001562 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001563 EltTys.push_back(PropertyNode);
1564 }
1565
1566 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1567 unsigned FieldNo = 0;
1568 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1569 Field = Field->getNextIvar(), ++FieldNo) {
1570 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1571 if (!FieldTy.isValid())
1572 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001573
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001574 StringRef FieldName = Field->getName();
1575
1576 // Ignore unnamed fields.
1577 if (FieldName.empty())
1578 continue;
1579
1580 // Get the location for the field.
1581 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1582 unsigned FieldLine = getLineNumber(Field->getLocation());
1583 QualType FType = Field->getType();
1584 uint64_t FieldSize = 0;
1585 unsigned FieldAlign = 0;
1586
1587 if (!FType->isIncompleteArrayType()) {
1588
1589 // Bit size, align and offset of the type.
1590 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001591 ? Field->getBitWidthValue(CGM.getContext())
1592 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001593 FieldAlign = CGM.getContext().getTypeAlign(FType);
1594 }
1595
1596 uint64_t FieldOffset;
1597 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1598 // We don't know the runtime offset of an ivar if we're using the
1599 // non-fragile ABI. For bitfields, use the bit offset into the first
1600 // byte of storage of the bitfield. For other fields, use zero.
1601 if (Field->isBitField()) {
1602 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1603 CGM, ID, Field);
1604 FieldOffset %= CGM.getContext().getCharWidth();
1605 } else {
1606 FieldOffset = 0;
1607 }
1608 } else {
1609 FieldOffset = RL.getFieldOffset(FieldNo);
1610 }
1611
1612 unsigned Flags = 0;
1613 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1614 Flags = llvm::DIDescriptor::FlagProtected;
1615 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1616 Flags = llvm::DIDescriptor::FlagPrivate;
1617
1618 llvm::MDNode *PropertyNode = NULL;
1619 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001620 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001621 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1622 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001623 SourceLocation Loc = PD->getLocation();
1624 llvm::DIFile PUnit = getOrCreateFile(Loc);
1625 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001626 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1627 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1628 PropertyNode =
1629 DBuilder.createObjCProperty(PD->getName(),
1630 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001631 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001632 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001633 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001634 getSelectorName(PD->getSetterName()),
1635 PD->getPropertyAttributes(),
1636 getOrCreateType(PD->getType(), PUnit));
1637 }
1638 }
1639 }
1640 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1641 FieldLine, FieldSize, FieldAlign,
1642 FieldOffset, Flags, FieldTy,
1643 PropertyNode);
1644 EltTys.push_back(FieldTy);
1645 }
1646
1647 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001648 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001649
1650 // If the implementation is not yet set, we do not want to mark it
1651 // as complete. An implementation may declare additional
1652 // private ivars that we would miss otherwise.
1653 if (ID->getImplementation() == 0)
1654 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001655
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001656 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001657 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001658}
1659
1660llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1661 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1662 int64_t Count = Ty->getNumElements();
1663 if (Count == 0)
1664 // If number of elements are not known then this is an unbounded array.
1665 // Use Count == -1 to express such arrays.
1666 Count = -1;
1667
1668 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1669 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1670
1671 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1672 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1673
1674 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1675}
1676
1677llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1678 llvm::DIFile Unit) {
1679 uint64_t Size;
1680 uint64_t Align;
1681
1682 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1683 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1684 Size = 0;
1685 Align =
1686 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1687 } else if (Ty->isIncompleteArrayType()) {
1688 Size = 0;
1689 if (Ty->getElementType()->isIncompleteType())
1690 Align = 0;
1691 else
1692 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001693 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001694 Size = 0;
1695 Align = 0;
1696 } else {
1697 // Size and align of the whole array, not the element type.
1698 Size = CGM.getContext().getTypeSize(Ty);
1699 Align = CGM.getContext().getTypeAlign(Ty);
1700 }
1701
1702 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1703 // interior arrays, do we care? Why aren't nested arrays represented the
1704 // obvious/recursive way?
1705 SmallVector<llvm::Value *, 8> Subscripts;
1706 QualType EltTy(Ty, 0);
1707 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1708 // If the number of elements is known, then count is that number. Otherwise,
1709 // it's -1. This allows us to represent a subrange with an array of 0
1710 // elements, like this:
1711 //
1712 // struct foo {
1713 // int x[0];
1714 // };
1715 int64_t Count = -1; // Count == -1 is an unbounded array.
1716 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1717 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001718
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001719 // FIXME: Verify this is right for VLAs.
1720 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1721 EltTy = Ty->getElementType();
1722 }
1723
1724 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1725
Eric Christopher6537f082013-05-16 00:45:12 +00001726 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001727 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1728 SubscriptArray);
1729 return DbgTy;
1730}
1731
Eric Christopher6537f082013-05-16 00:45:12 +00001732llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001733 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001734 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001735 Ty, Ty->getPointeeType(), Unit);
1736}
1737
Eric Christopher6537f082013-05-16 00:45:12 +00001738llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001739 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001740 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001741 Ty, Ty->getPointeeType(), Unit);
1742}
1743
Eric Christopher6537f082013-05-16 00:45:12 +00001744llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001745 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001746 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1747 if (!Ty->getPointeeType()->isFunctionType())
1748 return DBuilder.createMemberPointerType(
David Blaikieb0f77b02013-05-24 21:33:22 +00001749 getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001750 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1751 CGM.getContext().getPointerType(
1752 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1753 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1754 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001755}
1756
Eric Christopher6537f082013-05-16 00:45:12 +00001757llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001758 llvm::DIFile U) {
1759 // Ignore the atomic wrapping
1760 // FIXME: What is the correct representation?
1761 return getOrCreateType(Ty->getValueType(), U);
1762}
1763
1764/// CreateEnumType - get enumeration type.
1765llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1766 uint64_t Size = 0;
1767 uint64_t Align = 0;
1768 if (!ED->getTypeForDecl()->isIncompleteType()) {
1769 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1770 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1771 }
1772
1773 // If this is just a forward declaration, construct an appropriately
1774 // marked node and just return it.
1775 if (!ED->getDefinition()) {
1776 llvm::DIDescriptor EDContext;
1777 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1778 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1779 unsigned Line = getLineNumber(ED->getLocation());
1780 StringRef EDName = ED->getName();
1781 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1782 EDName, EDContext, DefUnit, Line, 0,
1783 Size, Align);
1784 }
1785
1786 // Create DIEnumerator elements for each enumerator.
1787 SmallVector<llvm::Value *, 16> Enumerators;
1788 ED = ED->getDefinition();
1789 for (EnumDecl::enumerator_iterator
1790 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1791 Enum != EnumEnd; ++Enum) {
1792 Enumerators.push_back(
1793 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001794 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001795 }
1796
1797 // Return a CompositeType for the enum itself.
1798 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1799
1800 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1801 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001802 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001803 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001804 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001805 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001806 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001807 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1808 Size, Align, EltArray,
1809 ClassTy);
1810 return DbgTy;
1811}
1812
David Blaikie4b12be62013-01-21 04:37:12 +00001813static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1814 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001815 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001816 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001817 QualType LastT = T;
1818 switch (T->getTypeClass()) {
1819 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001820 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001821 case Type::TemplateSpecialization:
1822 T = cast<TemplateSpecializationType>(T)->desugar();
1823 break;
1824 case Type::TypeOfExpr:
1825 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1826 break;
1827 case Type::TypeOf:
1828 T = cast<TypeOfType>(T)->getUnderlyingType();
1829 break;
1830 case Type::Decltype:
1831 T = cast<DecltypeType>(T)->getUnderlyingType();
1832 break;
1833 case Type::UnaryTransform:
1834 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1835 break;
1836 case Type::Attributed:
1837 T = cast<AttributedType>(T)->getEquivalentType();
1838 break;
1839 case Type::Elaborated:
1840 T = cast<ElaboratedType>(T)->getNamedType();
1841 break;
1842 case Type::Paren:
1843 T = cast<ParenType>(T)->getInnerType();
1844 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001845 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001846 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001847 break;
1848 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001849 QualType DT = cast<AutoType>(T)->getDeducedType();
1850 if (DT.isNull())
1851 return T;
1852 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001853 break;
1854 }
Eric Christopher6537f082013-05-16 00:45:12 +00001855
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001856 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001857 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858 } while (true);
1859}
1860
Eric Christopherf0890c42013-05-16 00:52:20 +00001861/// getType - Get the type from the cache or return null type if it doesn't
1862/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001863llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1864
1865 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001866 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001867
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001868 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001869 if (Ty->getTypeClass() == Type::ObjCInterface) {
1870 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1871 if (V)
1872 return llvm::DIType(cast<llvm::MDNode>(V));
1873 else return llvm::DIType();
1874 }
1875
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001876 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1877 TypeCache.find(Ty.getAsOpaquePtr());
1878 if (it != TypeCache.end()) {
1879 // Verify that the debug info still exists.
1880 if (llvm::Value *V = it->second)
1881 return llvm::DIType(cast<llvm::MDNode>(V));
1882 }
1883
1884 return llvm::DIType();
1885}
1886
1887/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1888/// doesn't exist.
1889llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1890
1891 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001892 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001893
1894 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001895 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001896 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1897 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001898 if (it != CompletedTypeCache.end())
1899 V = it->second;
1900 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001901 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001902 }
1903
Adrian Prantl4919de62013-03-06 22:03:30 +00001904 // Verify that any cached debug info still exists.
David Blaikieeab6a362013-06-21 00:40:50 +00001905 if (V != 0)
1906 return llvm::DIType(cast<llvm::MDNode>(V));
Adrian Prantl4919de62013-03-06 22:03:30 +00001907
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001908 return llvm::DIType();
1909}
1910
David Blaikieeab6a362013-06-21 00:40:50 +00001911void CGDebugInfo::completeFwdDecl(const RecordDecl &RD) {
1912 // In limited debug info we only want to do this if the complete type was
1913 // required.
1914 if (DebugKind <= CodeGenOptions::LimitedDebugInfo)
1915 return;
1916
David Blaikie076f51f2013-06-21 00:59:44 +00001917 QualType QTy = CGM.getContext().getRecordType(&RD);
1918 llvm::DIType T = getTypeOrNull(QTy);
David Blaikieeab6a362013-06-21 00:40:50 +00001919
Manman Renb6b0a712013-07-02 19:01:53 +00001920 if (T.isType() && T.isForwardDecl())
David Blaikie076f51f2013-06-21 00:59:44 +00001921 getOrCreateType(QTy, getOrCreateFile(RD.getLocation()));
David Blaikieeab6a362013-06-21 00:40:50 +00001922}
1923
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001924/// getCachedInterfaceTypeOrNull - Get the type from the interface
1925/// cache, unless it needs to regenerated. Otherwise return null.
1926llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1927 // Is there a cached interface that hasn't changed?
1928 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1929 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1930
1931 if (it1 != ObjCInterfaceCache.end())
1932 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1933 if (Checksum(Decl) == it1->second.second)
1934 // Return cached forward declaration.
1935 return it1->second.first;
1936
1937 return 0;
1938}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001939
1940/// getOrCreateType - Get the type from the cache or create a new
1941/// one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +00001942llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
1943 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001944 if (Ty.isNull())
1945 return llvm::DIType();
1946
1947 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001948 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001949
1950 llvm::DIType T = getCompletedTypeOrNull(Ty);
1951
Manman Renb6b0a712013-07-02 19:01:53 +00001952 if (T.isType()) {
David Blaikief0c31d92013-06-21 21:03:11 +00001953 // If we're looking for a definition, make sure we have definitions of any
1954 // underlying types.
1955 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
1956 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
1957 if (Ty.hasLocalQualifiers())
1958 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001959 return T;
David Blaikief0c31d92013-06-21 21:03:11 +00001960 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001961
1962 // Otherwise create the type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001963 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001964 void* TyPtr = Ty.getAsOpaquePtr();
1965
1966 // And update the type cache.
1967 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001968
1969 llvm::DIType TC = getTypeOrNull(Ty);
Manman Renb6b0a712013-07-02 19:01:53 +00001970 if (TC.isType() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001971 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1972 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1973 // Interface types may have elements added to them by a
1974 // subsequent implementation or extension, so we keep them in
1975 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001976 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001977 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00001978 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
1979 if (V.first)
1980 return llvm::DIType(cast<llvm::MDNode>(V.first));
1981 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1982 Decl->getName(), TheCU, Unit,
1983 getLineNumber(Decl->getLocation()),
1984 TheCU.getLanguage());
1985 // Store the forward declaration in the cache.
1986 V.first = TC;
1987 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001988
David Blaikiee2eb89a2013-05-21 18:29:40 +00001989 // Register the type for replacement in finalize().
1990 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1991
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001992 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001993 }
1994
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001995 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001996 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001997
1998 return Res;
1999}
2000
Adrian Prantlb5a50072013-06-07 01:10:41 +00002001/// Currently the checksum of an interface includes the number of
2002/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002003unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002004 // The assumption is that the number of ivars can only increase
2005 // monotonically, so it is safe to just use their current number as
2006 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002007 unsigned Sum = 0;
2008 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2009 Ivar != 0; Ivar = Ivar->getNextIvar())
2010 ++Sum;
2011
2012 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002013}
2014
2015ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2016 switch (Ty->getTypeClass()) {
2017 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002018 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2019 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002020 case Type::ObjCInterface:
2021 return cast<ObjCInterfaceType>(Ty)->getDecl();
2022 default:
2023 return 0;
2024 }
2025}
2026
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002027/// CreateTypeNode - Create a new debug type node.
Eric Christopher56b108a2013-06-07 22:54:39 +00002028llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2029 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002030 // Handle qualifiers, which recursively handles what they refer to.
2031 if (Ty.hasLocalQualifiers())
David Blaikie5f6e2f42013-06-05 05:32:23 +00002032 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002033
2034 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002035
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002036 // Work out details of type.
2037 switch (Ty->getTypeClass()) {
2038#define TYPE(Class, Base)
2039#define ABSTRACT_TYPE(Class, Base)
2040#define NON_CANONICAL_TYPE(Class, Base)
2041#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2042#include "clang/AST/TypeNodes.def"
2043 llvm_unreachable("Dependent types cannot show up in debug information");
2044
2045 case Type::ExtVector:
2046 case Type::Vector:
2047 return CreateType(cast<VectorType>(Ty), Unit);
2048 case Type::ObjCObjectPointer:
2049 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2050 case Type::ObjCObject:
2051 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2052 case Type::ObjCInterface:
2053 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2054 case Type::Builtin:
2055 return CreateType(cast<BuiltinType>(Ty));
2056 case Type::Complex:
2057 return CreateType(cast<ComplexType>(Ty));
2058 case Type::Pointer:
2059 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002060 case Type::Decayed:
2061 // Decayed types are just pointers in LLVM and DWARF.
2062 return CreateType(
2063 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002064 case Type::BlockPointer:
2065 return CreateType(cast<BlockPointerType>(Ty), Unit);
2066 case Type::Typedef:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002067 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002068 case Type::Record:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002069 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002070 case Type::Enum:
2071 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2072 case Type::FunctionProto:
2073 case Type::FunctionNoProto:
2074 return CreateType(cast<FunctionType>(Ty), Unit);
2075 case Type::ConstantArray:
2076 case Type::VariableArray:
2077 case Type::IncompleteArray:
2078 return CreateType(cast<ArrayType>(Ty), Unit);
2079
2080 case Type::LValueReference:
2081 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2082 case Type::RValueReference:
2083 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2084
2085 case Type::MemberPointer:
2086 return CreateType(cast<MemberPointerType>(Ty), Unit);
2087
2088 case Type::Atomic:
2089 return CreateType(cast<AtomicType>(Ty), Unit);
2090
2091 case Type::Attributed:
2092 case Type::TemplateSpecialization:
2093 case Type::Elaborated:
2094 case Type::Paren:
2095 case Type::SubstTemplateTypeParm:
2096 case Type::TypeOfExpr:
2097 case Type::TypeOf:
2098 case Type::Decltype:
2099 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002100 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002101 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002102 case Type::Auto:
2103 Diag = "auto";
2104 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002105 }
Eric Christopher6537f082013-05-16 00:45:12 +00002106
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002107 assert(Diag && "Fall through without a diagnostic?");
2108 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2109 "debug information for %0 is not yet supported");
2110 CGM.getDiags().Report(DiagID)
2111 << Diag;
2112 return llvm::DIType();
2113}
2114
2115/// getOrCreateLimitedType - Get the type from the cache or create a new
2116/// limited type if necessary.
2117llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002118 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002119 if (Ty.isNull())
2120 return llvm::DIType();
2121
2122 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002123 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002124
2125 llvm::DIType T = getTypeOrNull(Ty);
2126
2127 // We may have cached a forward decl when we could have created
2128 // a non-forward decl. Go ahead and create a non-forward decl
2129 // now.
Manman Renb6b0a712013-07-02 19:01:53 +00002130 if (T.isType() && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002131
2132 // Otherwise create the type.
2133 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2134
Manman Renb6b0a712013-07-02 19:01:53 +00002135 if (T.isType() && T.isForwardDecl())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002136 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2137 static_cast<llvm::Value*>(T)));
2138
2139 // And update the type cache.
2140 TypeCache[Ty.getAsOpaquePtr()] = Res;
2141 return Res;
2142}
2143
2144// TODO: Currently used for context chains when limiting debug info.
2145llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2146 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002147
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002148 // Get overall information about the record type for the debug info.
2149 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2150 unsigned Line = getLineNumber(RD->getLocation());
2151 StringRef RDName = getClassName(RD);
2152
2153 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002154 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002155 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2156 else
2157 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2158
2159 // If this is just a forward declaration, construct an appropriately
2160 // marked node and just return it.
2161 if (!RD->getDefinition())
2162 return createRecordFwdDecl(RD, RDContext);
2163
2164 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2165 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2166 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002167 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002168
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002169 if (RD->isUnion())
2170 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002171 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002172 else if (RD->isClass()) {
2173 // FIXME: This could be a struct type giving a default visibility different
2174 // than C++ class type, but needs llvm metadata changes first.
2175 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002176 Size, Align, 0, 0, llvm::DIType(),
2177 llvm::DIArray(), llvm::DIType(),
2178 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002179 } else
2180 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002181 Size, Align, 0, llvm::DIType(),
2182 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002183
2184 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002185 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002186
2187 if (CXXDecl) {
2188 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002189 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002190 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2191 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2192 // Seek non virtual primary base root.
2193 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002194 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2195 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2196 if (PBT && !BRL.isPrimaryBaseVirtual())
2197 PBase = PBT;
2198 else
2199 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002200 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002201 ContainingType = llvm::DICompositeType(
2202 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2203 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002204 ContainingType = RealDecl;
2205
David Blaikie2fcadbe2013-03-26 23:47:35 +00002206 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002207 }
2208 return llvm::DIType(RealDecl);
2209}
2210
2211/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2212/// declare composite types that haven't been processed yet.
2213llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2214
2215 // Work out details of type.
2216 switch (Ty->getTypeClass()) {
2217#define TYPE(Class, Base)
2218#define ABSTRACT_TYPE(Class, Base)
2219#define NON_CANONICAL_TYPE(Class, Base)
2220#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2221 #include "clang/AST/TypeNodes.def"
2222 llvm_unreachable("Dependent types cannot show up in debug information");
2223
2224 case Type::Record:
2225 return CreateLimitedType(cast<RecordType>(Ty));
2226 default:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002227 return CreateTypeNode(Ty, Unit, false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002228 }
2229}
2230
2231/// CreateMemberType - Create new member and increase Offset by FType's size.
2232llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2233 StringRef Name,
2234 uint64_t *Offset) {
2235 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2236 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2237 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2238 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2239 FieldSize, FieldAlign,
2240 *Offset, 0, FieldTy);
2241 *Offset += FieldSize;
2242 return Ty;
2243}
2244
David Blaikie9faebd22013-05-20 04:58:53 +00002245llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2246 // We only need a declaration (not a definition) of the type - so use whatever
2247 // we would otherwise do to get a type for a pointee. (forward declarations in
2248 // limited debug info, full definitions (if the type definition is available)
2249 // in unlimited debug info)
2250 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2251 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
David Blaikieb0f77b02013-05-24 21:33:22 +00002252 return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2253 DefUnit);
David Blaikie9faebd22013-05-20 04:58:53 +00002254 }
2255 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2256 // This doesn't handle providing declarations (for functions or variables) for
2257 // entities without definitions in this TU, nor when the definition proceeds
2258 // the call to this function.
2259 // FIXME: This should be split out into more specific maps with support for
2260 // emitting forward declarations and merging definitions with declarations,
2261 // the same way as we do for types.
2262 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2263 DeclCache.find(D->getCanonicalDecl());
2264 if (I == DeclCache.end())
2265 return llvm::DIDescriptor();
2266 llvm::Value *V = I->second;
2267 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2268}
2269
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002270/// getFunctionDeclaration - Return debug info descriptor to describe method
2271/// declaration for the given method definition.
2272llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002273 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2274 return llvm::DISubprogram();
2275
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002276 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2277 if (!FD) return llvm::DISubprogram();
2278
2279 // Setup context.
2280 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2281
2282 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2283 MI = SPCache.find(FD->getCanonicalDecl());
2284 if (MI != SPCache.end()) {
2285 llvm::Value *V = MI->second;
2286 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002287 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002288 return SP;
2289 }
2290
2291 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2292 E = FD->redecls_end(); I != E; ++I) {
2293 const FunctionDecl *NextFD = *I;
2294 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2295 MI = SPCache.find(NextFD->getCanonicalDecl());
2296 if (MI != SPCache.end()) {
2297 llvm::Value *V = MI->second;
2298 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002299 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002300 return SP;
2301 }
2302 }
2303 return llvm::DISubprogram();
2304}
2305
2306// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2307// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002308llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2309 QualType FnType,
2310 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002311 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2312 // Create fake but valid subroutine type. Otherwise
2313 // llvm::DISubprogram::Verify() would return false, and
2314 // subprogram DIE will miss DW_AT_decl_file and
2315 // DW_AT_decl_line fields.
2316 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002317
2318 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2319 return getOrCreateMethodType(Method, F);
2320 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2321 // Add "self" and "_cmd"
2322 SmallVector<llvm::Value *, 16> Elts;
2323
2324 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002325 QualType ResultTy = OMethod->getResultType();
2326
2327 // Replace the instancetype keyword with the actual type.
2328 if (ResultTy == CGM.getContext().getObjCInstanceType())
2329 ResultTy = CGM.getContext().getPointerType(
2330 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2331
Adrian Prantl566a9c32013-05-10 21:08:31 +00002332 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002333 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002334 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2335 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2336 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002337 // "_cmd" pointer is always second argument.
2338 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2339 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2340 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002341 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002342 PE = OMethod->param_end(); PI != PE; ++PI)
2343 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2344
2345 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2346 return DBuilder.createSubroutineType(F, EltTypeArray);
2347 }
David Blaikie9a845292013-05-22 23:22:42 +00002348 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002349}
2350
2351/// EmitFunctionStart - Constructs the debug code for entering a function.
2352void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2353 llvm::Function *Fn,
2354 CGBuilderTy &Builder) {
2355
2356 StringRef Name;
2357 StringRef LinkageName;
2358
2359 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2360
2361 const Decl *D = GD.getDecl();
2362 // Function may lack declaration in source code if it is created by Clang
2363 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2364 bool HasDecl = (D != 0);
2365 // Use the location of the declaration.
2366 SourceLocation Loc;
2367 if (HasDecl)
2368 Loc = D->getLocation();
2369
2370 unsigned Flags = 0;
2371 llvm::DIFile Unit = getOrCreateFile(Loc);
2372 llvm::DIDescriptor FDContext(Unit);
2373 llvm::DIArray TParamsArray;
2374 if (!HasDecl) {
2375 // Use llvm function name.
2376 Name = Fn->getName();
2377 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2378 // If there is a DISubprogram for this function available then use it.
2379 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2380 FI = SPCache.find(FD->getCanonicalDecl());
2381 if (FI != SPCache.end()) {
2382 llvm::Value *V = FI->second;
2383 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2384 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2385 llvm::MDNode *SPN = SP;
2386 LexicalBlockStack.push_back(SPN);
2387 RegionMap[D] = llvm::WeakVH(SP);
2388 return;
2389 }
2390 }
2391 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002392 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002393 if (FD->hasPrototype()) {
2394 LinkageName = CGM.getMangledName(GD);
2395 Flags |= llvm::DIDescriptor::FlagPrototyped;
2396 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002397 // No need to replicate the linkage name if it isn't different from the
2398 // subprogram name, no need to have it at all unless coverage is enabled or
2399 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002400 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002401 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2402 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002403 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002404 LinkageName = StringRef();
2405
Eric Christopher13c97672013-05-16 00:45:23 +00002406 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002407 if (const NamespaceDecl *NSDecl =
2408 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2409 FDContext = getOrCreateNameSpace(NSDecl);
2410 else if (const RecordDecl *RDecl =
2411 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2412 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2413
2414 // Collect template parameters.
2415 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2416 }
2417 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2418 Name = getObjCMethodName(OMD);
2419 Flags |= llvm::DIDescriptor::FlagPrototyped;
2420 } else {
2421 // Use llvm function name.
2422 Name = Fn->getName();
2423 Flags |= llvm::DIDescriptor::FlagPrototyped;
2424 }
2425 if (!Name.empty() && Name[0] == '\01')
2426 Name = Name.substr(1);
2427
2428 unsigned LineNo = getLineNumber(Loc);
2429 if (!HasDecl || D->isImplicit())
2430 Flags |= llvm::DIDescriptor::FlagArtificial;
2431
David Blaikie23e66db2013-06-22 00:09:36 +00002432 llvm::DISubprogram SP = DBuilder.createFunction(
2433 FDContext, Name, LinkageName, Unit, LineNo,
2434 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2435 true /*definition*/, getLineNumber(CurLoc), Flags,
2436 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002437 if (HasDecl)
2438 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002439
2440 // Push function on region stack.
2441 llvm::MDNode *SPN = SP;
2442 LexicalBlockStack.push_back(SPN);
2443 if (HasDecl)
2444 RegionMap[D] = llvm::WeakVH(SP);
2445}
2446
2447/// EmitLocation - Emit metadata to indicate a change in line/column
2448/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002449void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2450 bool ForceColumnInfo) {
Eric Christopher6537f082013-05-16 00:45:12 +00002451
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002452 // Update our current location
2453 setLocation(Loc);
2454
2455 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2456
2457 // Don't bother if things are the same as last time.
2458 SourceManager &SM = CGM.getContext().getSourceManager();
2459 if (CurLoc == PrevLoc ||
2460 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2461 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002462 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2463 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2464 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002465 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002466
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002467 // Update last state.
2468 PrevLoc = CurLoc;
2469
2470 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002471 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2472 (getLineNumber(CurLoc),
2473 getColumnNumber(CurLoc, ForceColumnInfo),
2474 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002475}
2476
2477/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2478/// the stack.
2479void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2480 llvm::DIDescriptor D =
2481 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2482 llvm::DIDescriptor() :
2483 llvm::DIDescriptor(LexicalBlockStack.back()),
2484 getOrCreateFile(CurLoc),
2485 getLineNumber(CurLoc),
2486 getColumnNumber(CurLoc));
2487 llvm::MDNode *DN = D;
2488 LexicalBlockStack.push_back(DN);
2489}
2490
2491/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2492/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002493void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2494 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002495 // Set our current location.
2496 setLocation(Loc);
2497
2498 // Create a new lexical block and push it on the stack.
2499 CreateLexicalBlock(Loc);
2500
2501 // Emit a line table change for the current location inside the new scope.
2502 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2503 getColumnNumber(Loc),
2504 LexicalBlockStack.back()));
2505}
2506
2507/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2508/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002509void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2510 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002511 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2512
2513 // Provide an entry in the line table for the end of the block.
2514 EmitLocation(Builder, Loc);
2515
2516 LexicalBlockStack.pop_back();
2517}
2518
2519/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2520void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2521 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2522 unsigned RCount = FnBeginRegionCount.back();
2523 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2524
2525 // Pop all regions for this function.
2526 while (LexicalBlockStack.size() != RCount)
2527 EmitLexicalBlockEnd(Builder, CurLoc);
2528 FnBeginRegionCount.pop_back();
2529}
2530
Eric Christopher6537f082013-05-16 00:45:12 +00002531// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002532// See BuildByRefType.
2533llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2534 uint64_t *XOffset) {
2535
2536 SmallVector<llvm::Value *, 5> EltTys;
2537 QualType FType;
2538 uint64_t FieldSize, FieldOffset;
2539 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002540
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002541 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002542 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002543
2544 FieldOffset = 0;
2545 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2546 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2547 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2548 FType = CGM.getContext().IntTy;
2549 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2550 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2551
2552 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2553 if (HasCopyAndDispose) {
2554 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2555 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2556 &FieldOffset));
2557 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2558 &FieldOffset));
2559 }
2560 bool HasByrefExtendedLayout;
2561 Qualifiers::ObjCLifetime Lifetime;
2562 if (CGM.getContext().getByrefLifetime(Type,
2563 Lifetime, HasByrefExtendedLayout)
2564 && HasByrefExtendedLayout)
2565 EltTys.push_back(CreateMemberType(Unit, FType,
2566 "__byref_variable_layout",
2567 &FieldOffset));
Eric Christopher6537f082013-05-16 00:45:12 +00002568
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002569 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2570 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002571 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002572 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002573 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2574 CharUnits AlignedOffsetInBytes
2575 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2576 CharUnits NumPaddingBytes
2577 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002578
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002579 if (NumPaddingBytes.isPositive()) {
2580 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2581 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2582 pad, ArrayType::Normal, 0);
2583 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2584 }
2585 }
Eric Christopher6537f082013-05-16 00:45:12 +00002586
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002587 FType = Type;
2588 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2589 FieldSize = CGM.getContext().getTypeSize(FType);
2590 FieldAlign = CGM.getContext().toBits(Align);
2591
Eric Christopher6537f082013-05-16 00:45:12 +00002592 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002593 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2594 0, FieldSize, FieldAlign,
2595 FieldOffset, 0, FieldTy);
2596 EltTys.push_back(FieldTy);
2597 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002598
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002599 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002600
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002601 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002602
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002603 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002604 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002605}
2606
2607/// EmitDeclare - Emit local variable declaration debug info.
2608void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002609 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002610 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002611 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002612 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2613
2614 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2615 llvm::DIType Ty;
2616 uint64_t XOffset = 0;
2617 if (VD->hasAttr<BlocksAttr>())
2618 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002619 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002620 Ty = getOrCreateType(VD->getType(), Unit);
2621
2622 // If there is no debug info for this type then do not emit debug info
2623 // for this variable.
2624 if (!Ty)
2625 return;
2626
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002627 // Get location information.
2628 unsigned Line = getLineNumber(VD->getLocation());
2629 unsigned Column = getColumnNumber(VD->getLocation());
2630 unsigned Flags = 0;
2631 if (VD->isImplicit())
2632 Flags |= llvm::DIDescriptor::FlagArtificial;
2633 // If this is the first argument and it is implicit then
2634 // give it an object pointer flag.
2635 // FIXME: There has to be a better way to do this, but for static
2636 // functions there won't be an implicit param at arg1 and
2637 // otherwise it is 'self' or 'this'.
2638 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2639 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002640 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002641 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2642 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002643 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002644
2645 llvm::MDNode *Scope = LexicalBlockStack.back();
2646
2647 StringRef Name = VD->getName();
2648 if (!Name.empty()) {
2649 if (VD->hasAttr<BlocksAttr>()) {
2650 CharUnits offset = CharUnits::fromQuantity(32);
2651 SmallVector<llvm::Value *, 9> addr;
2652 llvm::Type *Int64Ty = CGM.Int64Ty;
2653 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2654 // offset of __forwarding field
2655 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002656 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002657 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2658 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2659 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2660 // offset of x field
2661 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2662 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2663
2664 // Create the descriptor for the variable.
2665 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002666 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002667 llvm::DIDescriptor(Scope),
2668 VD->getName(), Unit, Line, Ty,
2669 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002670
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002671 // Insert an llvm.dbg.declare into the current block.
2672 llvm::Instruction *Call =
2673 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2674 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2675 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002676 }
David Blaikie436653b2013-01-05 05:58:35 +00002677 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2678 // If VD is an anonymous union then Storage represents value for
2679 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002680 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002681 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002682 for (RecordDecl::field_iterator I = RD->field_begin(),
2683 E = RD->field_end();
2684 I != E; ++I) {
2685 FieldDecl *Field = *I;
2686 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2687 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002688
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002689 // Ignore unnamed fields. Do not ignore unnamed records.
2690 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2691 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002692
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002693 // Use VarDecl's Tag, Scope and Line number.
2694 llvm::DIVariable D =
2695 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002696 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002697 CGM.getLangOpts().Optimize, Flags,
2698 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002699
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002700 // Insert an llvm.dbg.declare into the current block.
2701 llvm::Instruction *Call =
2702 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2703 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2704 }
David Blaikied8180cf2013-01-05 20:03:07 +00002705 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002706 }
2707 }
David Blaikie436653b2013-01-05 05:58:35 +00002708
2709 // Create the descriptor for the variable.
2710 llvm::DIVariable D =
2711 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2712 Name, Unit, Line, Ty,
2713 CGM.getLangOpts().Optimize, Flags, ArgNo);
2714
2715 // Insert an llvm.dbg.declare into the current block.
2716 llvm::Instruction *Call =
2717 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2718 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002719}
2720
2721void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2722 llvm::Value *Storage,
2723 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002724 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002725 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2726}
2727
Adrian Prantle86fcc42013-03-29 19:20:29 +00002728/// Look up the completed type for a self pointer in the TypeCache and
2729/// create a copy of it with the ObjectPointer and Artificial flags
2730/// set. If the type is not cached, a new one is created. This should
2731/// never happen though, since creating a type for the implicit self
2732/// argument implies that we already parsed the interface definition
2733/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002734llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2735 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002736 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Manman Renb6b0a712013-07-02 19:01:53 +00002737 if (CachedTy.isType()) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002738 else DEBUG(llvm::dbgs() << "No cached type for self.");
2739 return DBuilder.createObjectPointerType(Ty);
2740}
2741
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002742void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2743 llvm::Value *Storage,
2744 CGBuilderTy &Builder,
2745 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002746 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002747 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002748
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002749 if (Builder.GetInsertBlock() == 0)
2750 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002751
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002752 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002753
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002754 uint64_t XOffset = 0;
2755 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2756 llvm::DIType Ty;
2757 if (isByRef)
2758 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002759 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002760 Ty = getOrCreateType(VD->getType(), Unit);
2761
2762 // Self is passed along as an implicit non-arg variable in a
2763 // block. Mark it as the object pointer.
2764 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002765 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002766
2767 // Get location information.
2768 unsigned Line = getLineNumber(VD->getLocation());
2769 unsigned Column = getColumnNumber(VD->getLocation());
2770
2771 const llvm::DataLayout &target = CGM.getDataLayout();
2772
2773 CharUnits offset = CharUnits::fromQuantity(
2774 target.getStructLayout(blockInfo.StructureType)
2775 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2776
2777 SmallVector<llvm::Value *, 9> addr;
2778 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002779 if (isa<llvm::AllocaInst>(Storage))
2780 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002781 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2782 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2783 if (isByRef) {
2784 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2785 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2786 // offset of __forwarding field
2787 offset = CGM.getContext()
2788 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2789 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2790 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2791 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2792 // offset of x field
2793 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2794 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2795 }
2796
2797 // Create the descriptor for the variable.
2798 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002799 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002800 llvm::DIDescriptor(LexicalBlockStack.back()),
2801 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002802
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002803 // Insert an llvm.dbg.declare into the current block.
2804 llvm::Instruction *Call =
2805 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2806 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2807 LexicalBlockStack.back()));
2808}
2809
2810/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2811/// variable declaration.
2812void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2813 unsigned ArgNo,
2814 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002815 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002816 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2817}
2818
2819namespace {
2820 struct BlockLayoutChunk {
2821 uint64_t OffsetInBits;
2822 const BlockDecl::Capture *Capture;
2823 };
2824 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2825 return l.OffsetInBits < r.OffsetInBits;
2826 }
2827}
2828
2829void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002830 llvm::Value *Arg,
2831 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002832 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002833 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002834 ASTContext &C = CGM.getContext();
2835 const BlockDecl *blockDecl = block.getBlockDecl();
2836
2837 // Collect some general information about the block's location.
2838 SourceLocation loc = blockDecl->getCaretLocation();
2839 llvm::DIFile tunit = getOrCreateFile(loc);
2840 unsigned line = getLineNumber(loc);
2841 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002842
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002843 // Build the debug-info type for the block literal.
2844 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2845
2846 const llvm::StructLayout *blockLayout =
2847 CGM.getDataLayout().getStructLayout(block.StructureType);
2848
2849 SmallVector<llvm::Value*, 16> fields;
2850 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2851 blockLayout->getElementOffsetInBits(0),
2852 tunit, tunit));
2853 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2854 blockLayout->getElementOffsetInBits(1),
2855 tunit, tunit));
2856 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2857 blockLayout->getElementOffsetInBits(2),
2858 tunit, tunit));
2859 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2860 blockLayout->getElementOffsetInBits(3),
2861 tunit, tunit));
2862 fields.push_back(createFieldType("__descriptor",
2863 C.getPointerType(block.NeedsCopyDispose ?
2864 C.getBlockDescriptorExtendedType() :
2865 C.getBlockDescriptorType()),
2866 0, loc, AS_public,
2867 blockLayout->getElementOffsetInBits(4),
2868 tunit, tunit));
2869
2870 // We want to sort the captures by offset, not because DWARF
2871 // requires this, but because we're paranoid about debuggers.
2872 SmallVector<BlockLayoutChunk, 8> chunks;
2873
2874 // 'this' capture.
2875 if (blockDecl->capturesCXXThis()) {
2876 BlockLayoutChunk chunk;
2877 chunk.OffsetInBits =
2878 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2879 chunk.Capture = 0;
2880 chunks.push_back(chunk);
2881 }
2882
2883 // Variable captures.
2884 for (BlockDecl::capture_const_iterator
2885 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2886 i != e; ++i) {
2887 const BlockDecl::Capture &capture = *i;
2888 const VarDecl *variable = capture.getVariable();
2889 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2890
2891 // Ignore constant captures.
2892 if (captureInfo.isConstant())
2893 continue;
2894
2895 BlockLayoutChunk chunk;
2896 chunk.OffsetInBits =
2897 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2898 chunk.Capture = &capture;
2899 chunks.push_back(chunk);
2900 }
2901
2902 // Sort by offset.
2903 llvm::array_pod_sort(chunks.begin(), chunks.end());
2904
2905 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2906 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2907 uint64_t offsetInBits = i->OffsetInBits;
2908 const BlockDecl::Capture *capture = i->Capture;
2909
2910 // If we have a null capture, this must be the C++ 'this' capture.
2911 if (!capture) {
2912 const CXXMethodDecl *method =
2913 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2914 QualType type = method->getThisType(C);
2915
2916 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2917 offsetInBits, tunit, tunit));
2918 continue;
2919 }
2920
2921 const VarDecl *variable = capture->getVariable();
2922 StringRef name = variable->getName();
2923
2924 llvm::DIType fieldType;
2925 if (capture->isByRef()) {
2926 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2927
2928 // FIXME: this creates a second copy of this type!
2929 uint64_t xoffset;
2930 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2931 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2932 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2933 ptrInfo.first, ptrInfo.second,
2934 offsetInBits, 0, fieldType);
2935 } else {
2936 fieldType = createFieldType(name, variable->getType(), 0,
2937 loc, AS_public, offsetInBits, tunit, tunit);
2938 }
2939 fields.push_back(fieldType);
2940 }
2941
2942 SmallString<36> typeName;
2943 llvm::raw_svector_ostream(typeName)
2944 << "__block_literal_" << CGM.getUniqueBlockCount();
2945
2946 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2947
2948 llvm::DIType type =
2949 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2950 CGM.getContext().toBits(block.BlockSize),
2951 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002952 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002953 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2954
2955 // Get overall information about the block.
2956 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2957 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002958
2959 // Create the descriptor for the parameter.
2960 llvm::DIVariable debugVar =
2961 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00002962 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002963 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002964 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002965 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2966
Adrian Prantlbea407c2013-03-14 21:52:59 +00002967 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002968 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002969 llvm::Instruction *DbgVal =
2970 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002971 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002972 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2973 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002974
Adrian Prantlbea407c2013-03-14 21:52:59 +00002975 // Insert an llvm.dbg.declare into the current block.
2976 llvm::Instruction *DbgDecl =
2977 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2978 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002979}
2980
Eric Christopher0395de32013-01-16 01:22:32 +00002981/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2982/// a static data member of a class, find its corresponding in-class
2983/// declaration.
2984llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2985 if (cast<VarDecl>(D)->isStaticDataMember()) {
2986 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2987 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2988 if (MI != StaticDataMemberCache.end())
2989 // Verify the info still exists.
2990 if (llvm::Value *V = MI->second)
2991 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2992 }
2993 return llvm::DIDerivedType();
2994}
2995
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002996/// EmitGlobalVariable - Emit information about a global variable.
2997void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2998 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00002999 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003000 // Create global variable debug descriptor.
3001 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3002 unsigned LineNo = getLineNumber(D->getLocation());
3003
3004 setLocation(D->getLocation());
3005
3006 QualType T = D->getType();
3007 if (T->isIncompleteArrayType()) {
3008
3009 // CodeGen turns int[] into int[1] so we'll do the same here.
3010 llvm::APInt ConstVal(32, 1);
3011 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3012
3013 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3014 ArrayType::Normal, 0);
3015 }
3016 StringRef DeclName = D->getName();
3017 StringRef LinkageName;
3018 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3019 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3020 LinkageName = Var->getName();
3021 if (LinkageName == DeclName)
3022 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003023 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003024 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christopher56b108a2013-06-07 22:54:39 +00003025 llvm::DIGlobalVariable GV =
3026 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, Unit,
3027 LineNo, getOrCreateType(T, Unit),
3028 Var->hasInternalLinkage(), Var,
3029 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003030 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003031}
3032
3033/// EmitGlobalVariable - Emit information about an objective-c interface.
3034void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3035 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003036 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003037 // Create global variable debug descriptor.
3038 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3039 unsigned LineNo = getLineNumber(ID->getLocation());
3040
3041 StringRef Name = ID->getName();
3042
3043 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3044 if (T->isIncompleteArrayType()) {
3045
3046 // CodeGen turns int[] into int[1] so we'll do the same here.
3047 llvm::APInt ConstVal(32, 1);
3048 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3049
3050 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3051 ArrayType::Normal, 0);
3052 }
3053
3054 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3055 getOrCreateType(T, Unit),
3056 Var->hasInternalLinkage(), Var);
3057}
3058
3059/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003060void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003061 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003062 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003063 // Create the descriptor for the variable.
3064 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3065 StringRef Name = VD->getName();
3066 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3067 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3068 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3069 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3070 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3071 }
3072 // Do not use DIGlobalVariable for enums.
3073 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3074 return;
Eric Christopher56b108a2013-06-07 22:54:39 +00003075 llvm::DIGlobalVariable GV =
3076 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
3077 getLineNumber(VD->getLocation()), Ty, true,
3078 Init, getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003079 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3080}
3081
3082llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3083 if (!LexicalBlockStack.empty())
3084 return llvm::DIScope(LexicalBlockStack.back());
3085 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003086}
3087
David Blaikie957dac52013-04-22 06:13:21 +00003088void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003089 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3090 return;
David Blaikie957dac52013-04-22 06:13:21 +00003091 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003092 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3093 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003094 getLineNumber(UD.getLocation()));
3095}
3096
David Blaikie9faebd22013-05-20 04:58:53 +00003097void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3098 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3099 return;
3100 assert(UD.shadow_size() &&
3101 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3102 // Emitting one decl is sufficient - debuggers can detect that this is an
3103 // overloaded name & provide lookup for all the overloads.
3104 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003105 if (llvm::DIDescriptor Target =
3106 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003107 DBuilder.createImportedDeclaration(
3108 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3109 getLineNumber(USD.getLocation()));
3110}
3111
David Blaikiefc46ebc2013-05-20 22:50:41 +00003112llvm::DIImportedEntity
3113CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3114 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3115 return llvm::DIImportedEntity(0);
3116 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3117 if (VH)
3118 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3119 llvm::DIImportedEntity R(0);
3120 if (const NamespaceAliasDecl *Underlying =
3121 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3122 // This could cache & dedup here rather than relying on metadata deduping.
3123 R = DBuilder.createImportedModule(
3124 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3125 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3126 NA.getName());
3127 else
3128 R = DBuilder.createImportedModule(
3129 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3130 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3131 getLineNumber(NA.getLocation()), NA.getName());
3132 VH = R;
3133 return R;
3134}
3135
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003136/// getOrCreateNamesSpace - Return namespace descriptor for the given
3137/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003138llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003139CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003140 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003141 NameSpaceCache.find(NSDecl);
3142 if (I != NameSpaceCache.end())
3143 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003144
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003145 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3146 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003147 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003148 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3149 llvm::DINameSpace NS =
3150 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3151 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3152 return NS;
3153}
3154
3155void CGDebugInfo::finalize() {
3156 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3157 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3158 llvm::DIType Ty, RepTy;
3159 // Verify that the debug info still exists.
3160 if (llvm::Value *V = VI->second)
3161 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003162
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003163 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3164 TypeCache.find(VI->first);
3165 if (it != TypeCache.end()) {
3166 // Verify that the debug info still exists.
3167 if (llvm::Value *V = it->second)
3168 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3169 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003170
Manman Renb6b0a712013-07-02 19:01:53 +00003171 if (Ty.isType() && Ty.isForwardDecl() && RepTy.isType())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003172 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003173 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003174
3175 // We keep our own list of retained types, because we need to look
3176 // up the final type in the type cache.
3177 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3178 RE = RetainedTypes.end(); RI != RE; ++RI)
3179 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3180
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003181 DBuilder.finalize();
3182}