blob: 14c92e6669b414a655cb02e3fe3dc519cd2c08e6 [file] [log] [blame]
Guy Benyei11169dd2012-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 Blaikie38079fd2013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei11169dd2012-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 Carruthffd55512013-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 Benyei11169dd2012-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 Christopher75e17682013-05-16 00:45:23 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()),
Guy Benyei11169dd2012-12-18 14:30:41 +000046 BlockLiteralGenericSet(false) {
47 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
55void CGDebugInfo::setLocation(SourceLocation Loc) {
56 // If the new location isn't valid return.
57 if (!Loc.isValid()) return;
58
59 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
60
61 // If we've changed files in the middle of a lexical scope go ahead
62 // and create a new lexical scope with file node if it's different
63 // from the one in the scope.
64 if (LexicalBlockStack.empty()) return;
65
66 SourceManager &SM = CGM.getContext().getSourceManager();
67 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
68 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
69
70 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
71 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
72 return;
73
74 llvm::MDNode *LB = LexicalBlockStack.back();
75 llvm::DIScope Scope = llvm::DIScope(LB);
76 if (Scope.isLexicalBlockFile()) {
77 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
78 llvm::DIDescriptor D
79 = DBuilder.createLexicalBlockFile(LBF.getScope(),
80 getOrCreateFile(CurLoc));
81 llvm::MDNode *N = D;
82 LexicalBlockStack.pop_back();
83 LexicalBlockStack.push_back(N);
David Blaikie0a21d0d2013-01-26 22:16:26 +000084 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei11169dd2012-12-18 14:30:41 +000085 llvm::DIDescriptor D
86 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
87 llvm::MDNode *N = D;
88 LexicalBlockStack.pop_back();
89 LexicalBlockStack.push_back(N);
90 }
91}
92
93/// getContextDescriptor - Get context info for the decl.
David Blaikiebfa52742013-04-19 06:56:38 +000094llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei11169dd2012-12-18 14:30:41 +000095 if (!Context)
96 return TheCU;
97
98 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
99 I = RegionMap.find(Context);
100 if (I != RegionMap.end()) {
101 llvm::Value *V = I->second;
David Blaikiebfa52742013-04-19 06:56:38 +0000102 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +0000103 }
104
105 // Check namespace.
106 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000107 return getOrCreateNameSpace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000108
David Blaikiebfa52742013-04-19 06:56:38 +0000109 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
110 if (!RDecl->isDependentType())
111 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei11169dd2012-12-18 14:30:41 +0000112 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000113 return TheCU;
114}
115
116/// getFunctionName - Get function name for the given FunctionDecl. If the
117/// name is constructred on demand (e.g. C++ destructor) then the name
118/// is stored on the side.
119StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
120 assert (FD && "Invalid FunctionDecl!");
121 IdentifierInfo *FII = FD->getIdentifier();
122 FunctionTemplateSpecializationInfo *Info
123 = FD->getTemplateSpecializationInfo();
124 if (!Info && FII)
125 return FII->getName();
126
127 // Otherwise construct human readable name for debug info.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000128 SmallString<128> NS;
129 llvm::raw_svector_ostream OS(NS);
130 FD->printName(OS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000131
132 // Add any template specialization args.
133 if (Info) {
134 const TemplateArgumentList *TArgs = Info->TemplateArguments;
135 const TemplateArgument *Args = TArgs->data();
136 unsigned NumArgs = TArgs->size();
137 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000138 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
139 Policy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000140 }
141
142 // Copy this name on the side and use its reference.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000143 OS.flush();
144 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
145 memcpy(StrPtr, NS.data(), NS.size());
146 return StringRef(StrPtr, NS.size());
Guy Benyei11169dd2012-12-18 14:30:41 +0000147}
148
149StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
150 SmallString<256> MethodName;
151 llvm::raw_svector_ostream OS(MethodName);
152 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
153 const DeclContext *DC = OMD->getDeclContext();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000154 if (const ObjCImplementationDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000155 dyn_cast<const ObjCImplementationDecl>(DC)) {
156 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000157 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 dyn_cast<const ObjCInterfaceDecl>(DC)) {
159 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000160 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000161 dyn_cast<const ObjCCategoryImplDecl>(DC)){
162 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
163 OCD->getIdentifier()->getNameStart() << ')';
164 }
165 OS << ' ' << OMD->getSelector().getAsString() << ']';
166
167 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
168 memcpy(StrPtr, MethodName.begin(), OS.tell());
169 return StringRef(StrPtr, OS.tell());
170}
171
172/// getSelectorName - Return selector name. This is used for debugging
173/// info.
174StringRef CGDebugInfo::getSelectorName(Selector S) {
175 const std::string &SName = S.getAsString();
176 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
177 memcpy(StrPtr, SName.data(), SName.size());
178 return StringRef(StrPtr, SName.size());
179}
180
181/// getClassName - Get class name including template argument list.
Eric Christopherb2a008c2013-05-16 00:45:12 +0000182StringRef
Guy Benyei11169dd2012-12-18 14:30:41 +0000183CGDebugInfo::getClassName(const RecordDecl *RD) {
184 const ClassTemplateSpecializationDecl *Spec
185 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
186 if (!Spec)
187 return RD->getName();
188
189 const TemplateArgument *Args;
190 unsigned NumArgs;
191 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
192 const TemplateSpecializationType *TST =
193 cast<TemplateSpecializationType>(TAW->getType());
194 Args = TST->getArgs();
195 NumArgs = TST->getNumArgs();
196 } else {
197 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
198 Args = TemplateArgs.data();
199 NumArgs = TemplateArgs.size();
200 }
201 StringRef Name = RD->getIdentifier()->getName();
202 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000203 SmallString<128> TemplateArgList;
204 {
205 llvm::raw_svector_ostream OS(TemplateArgList);
206 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
207 Policy);
208 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000209
210 // Copy this name on the side and use its reference.
211 size_t Length = Name.size() + TemplateArgList.size();
212 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
213 memcpy(StrPtr, Name.data(), Name.size());
214 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
215 return StringRef(StrPtr, Length);
216}
217
218/// getOrCreateFile - Get the file debug info descriptor for the input location.
219llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
220 if (!Loc.isValid())
221 // If Location is not valid then use main input file.
222 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
223
224 SourceManager &SM = CGM.getContext().getSourceManager();
225 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
226
227 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
228 // If the location is not valid then use main input file.
229 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
230
231 // Cache the results.
232 const char *fname = PLoc.getFilename();
233 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
234 DIFileCache.find(fname);
235
236 if (it != DIFileCache.end()) {
237 // Verify that the information still exists.
238 if (llvm::Value *V = it->second)
239 return llvm::DIFile(cast<llvm::MDNode>(V));
240 }
241
242 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
243
244 DIFileCache[fname] = F;
245 return F;
246}
247
248/// getOrCreateMainFile - Get the file info for main compile unit.
249llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
250 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
251}
252
253/// getLineNumber - Get line number for the location. If location is invalid
254/// then use current location.
255unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
256 if (Loc.isInvalid() && CurLoc.isInvalid())
257 return 0;
258 SourceManager &SM = CGM.getContext().getSourceManager();
259 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
260 return PLoc.isValid()? PLoc.getLine() : 0;
261}
262
263/// getColumnNumber - Get column number for the location.
Adrian Prantlc7822422013-03-12 20:43:25 +0000264unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000265 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000266 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000267 return 0;
268
269 // If the location is invalid then use the current column.
270 if (Loc.isInvalid() && CurLoc.isInvalid())
271 return 0;
272 SourceManager &SM = CGM.getContext().getSourceManager();
273 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
274 return PLoc.isValid()? PLoc.getColumn() : 0;
275}
276
277StringRef CGDebugInfo::getCurrentDirname() {
278 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
279 return CGM.getCodeGenOpts().DebugCompilationDir;
280
281 if (!CWDName.empty())
282 return CWDName;
283 SmallString<256> CWD;
284 llvm::sys::fs::current_path(CWD);
285 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
286 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
287 return CWDName = StringRef(CompDirnamePtr, CWD.size());
288}
289
290/// CreateCompileUnit - Create new compile unit.
291void CGDebugInfo::CreateCompileUnit() {
292
293 // Get absolute path name.
294 SourceManager &SM = CGM.getContext().getSourceManager();
295 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
296 if (MainFileName.empty())
297 MainFileName = "<unknown>";
298
299 // The main file name provided via the "-main-file-name" option contains just
300 // the file name itself with no path information. This file name may have had
301 // a relative path, so we look into the actual file entry for the main
302 // file to determine the real absolute path for the file.
303 std::string MainFileDir;
304 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
305 MainFileDir = MainFile->getDir()->getName();
306 if (MainFileDir != ".")
307 MainFileName = MainFileDir + "/" + MainFileName;
308 }
309
310 // Save filename string.
311 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
312 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
313 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherf1545832013-02-22 23:50:16 +0000314
315 // Save split dwarf file string.
316 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
317 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
318 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
319 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopherb2a008c2013-05-16 00:45:12 +0000320
Guy Benyei11169dd2012-12-18 14:30:41 +0000321 unsigned LangTag;
322 const LangOptions &LO = CGM.getLangOpts();
323 if (LO.CPlusPlus) {
324 if (LO.ObjC1)
325 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
326 else
327 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
328 } else if (LO.ObjC1) {
329 LangTag = llvm::dwarf::DW_LANG_ObjC;
330 } else if (LO.C99) {
331 LangTag = llvm::dwarf::DW_LANG_C99;
332 } else {
333 LangTag = llvm::dwarf::DW_LANG_C89;
334 }
335
336 std::string Producer = getClangFullVersion();
337
338 // Figure out which version of the ObjC runtime we have.
339 unsigned RuntimeVers = 0;
340 if (LO.ObjC1)
341 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
342
343 // Create new compile unit.
Eric Christopherc0c5d462013-02-21 22:35:08 +0000344 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
345 Producer, LO.Optimize,
Eric Christopherf1545832013-02-22 23:50:16 +0000346 CGM.getCodeGenOpts().DwarfDebugFlags,
347 RuntimeVers, SplitDwarfFilename);
Guy Benyei11169dd2012-12-18 14:30:41 +0000348 // FIXME - Eliminate TheCU.
349 TheCU = llvm::DICompileUnit(DBuilder.getCU());
350}
351
352/// CreateType - Get the Basic type from the cache or create a new
353/// one if necessary.
354llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
355 unsigned Encoding = 0;
356 StringRef BTName;
357 switch (BT->getKind()) {
358#define BUILTIN_TYPE(Id, SingletonId)
359#define PLACEHOLDER_TYPE(Id, SingletonId) \
360 case BuiltinType::Id:
361#include "clang/AST/BuiltinTypes.def"
362 case BuiltinType::Dependent:
363 llvm_unreachable("Unexpected builtin type");
364 case BuiltinType::NullPtr:
365 return DBuilder.
366 createNullPtrType(BT->getName(CGM.getLangOpts()));
367 case BuiltinType::Void:
368 return llvm::DIType();
369 case BuiltinType::ObjCClass:
370 if (ClassTy.Verify())
371 return ClassTy;
372 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
373 "objc_class", TheCU,
374 getOrCreateMainFile(), 0);
375 return ClassTy;
376 case BuiltinType::ObjCId: {
377 // typedef struct objc_class *Class;
378 // typedef struct objc_object {
379 // Class isa;
380 // } *id;
381
382 if (ObjTy.Verify())
383 return ObjTy;
384
385 if (!ClassTy.Verify())
386 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
387 "objc_class", TheCU,
388 getOrCreateMainFile(), 0);
389
390 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000391
Guy Benyei11169dd2012-12-18 14:30:41 +0000392 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
393
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000394 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000395 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
396 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000397
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000398 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
399 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000400 return ObjTy;
401 }
402 case BuiltinType::ObjCSel: {
403 if (SelTy.Verify())
404 return SelTy;
405 SelTy =
406 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
407 "objc_selector", TheCU, getOrCreateMainFile(),
408 0);
409 return SelTy;
410 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000411
412 case BuiltinType::OCLImage1d:
413 return getOrCreateStructPtrType("opencl_image1d_t",
414 OCLImage1dDITy);
415 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000416 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000417 OCLImage1dArrayDITy);
418 case BuiltinType::OCLImage1dBuffer:
419 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
420 OCLImage1dBufferDITy);
421 case BuiltinType::OCLImage2d:
422 return getOrCreateStructPtrType("opencl_image2d_t",
423 OCLImage2dDITy);
424 case BuiltinType::OCLImage2dArray:
425 return getOrCreateStructPtrType("opencl_image2d_array_t",
426 OCLImage2dArrayDITy);
427 case BuiltinType::OCLImage3d:
428 return getOrCreateStructPtrType("opencl_image3d_t",
429 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000430 case BuiltinType::OCLSampler:
431 return DBuilder.createBasicType("opencl_sampler_t",
432 CGM.getContext().getTypeSize(BT),
433 CGM.getContext().getTypeAlign(BT),
434 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000435 case BuiltinType::OCLEvent:
436 return getOrCreateStructPtrType("opencl_event_t",
437 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000438
Guy Benyei11169dd2012-12-18 14:30:41 +0000439 case BuiltinType::UChar:
440 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
441 case BuiltinType::Char_S:
442 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
443 case BuiltinType::Char16:
444 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
445 case BuiltinType::UShort:
446 case BuiltinType::UInt:
447 case BuiltinType::UInt128:
448 case BuiltinType::ULong:
449 case BuiltinType::WChar_U:
450 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
451 case BuiltinType::Short:
452 case BuiltinType::Int:
453 case BuiltinType::Int128:
454 case BuiltinType::Long:
455 case BuiltinType::WChar_S:
456 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
457 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
458 case BuiltinType::Half:
459 case BuiltinType::Float:
460 case BuiltinType::LongDouble:
461 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
462 }
463
464 switch (BT->getKind()) {
465 case BuiltinType::Long: BTName = "long int"; break;
466 case BuiltinType::LongLong: BTName = "long long int"; break;
467 case BuiltinType::ULong: BTName = "long unsigned int"; break;
468 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
469 default:
470 BTName = BT->getName(CGM.getLangOpts());
471 break;
472 }
473 // Bit size, align and offset of the type.
474 uint64_t Size = CGM.getContext().getTypeSize(BT);
475 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000476 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000477 DBuilder.createBasicType(BTName, Size, Align, Encoding);
478 return DbgTy;
479}
480
481llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
482 // Bit size, align and offset of the type.
483 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
484 if (Ty->isComplexIntegerType())
485 Encoding = llvm::dwarf::DW_ATE_lo_user;
486
487 uint64_t Size = CGM.getContext().getTypeSize(Ty);
488 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000489 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000490 DBuilder.createBasicType("complex", Size, Align, Encoding);
491
492 return DbgTy;
493}
494
495/// CreateCVRType - Get the qualified type from the cache or create
496/// a new one if necessary.
497llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
498 QualifierCollector Qc;
499 const Type *T = Qc.strip(Ty);
500
501 // Ignore these qualifiers for now.
502 Qc.removeObjCGCAttr();
503 Qc.removeAddressSpace();
504 Qc.removeObjCLifetime();
505
506 // We will create one Derived type for one qualifier and recurse to handle any
507 // additional ones.
508 unsigned Tag;
509 if (Qc.hasConst()) {
510 Tag = llvm::dwarf::DW_TAG_const_type;
511 Qc.removeConst();
512 } else if (Qc.hasVolatile()) {
513 Tag = llvm::dwarf::DW_TAG_volatile_type;
514 Qc.removeVolatile();
515 } else if (Qc.hasRestrict()) {
516 Tag = llvm::dwarf::DW_TAG_restrict_type;
517 Qc.removeRestrict();
518 } else {
519 assert(Qc.empty() && "Unknown type qualifier for debug info");
520 return getOrCreateType(QualType(T, 0), Unit);
521 }
522
523 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
524
525 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
526 // CVR derived types.
527 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000528
Guy Benyei11169dd2012-12-18 14:30:41 +0000529 return DbgTy;
530}
531
532llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
533 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000534
535 // The frontend treats 'id' as a typedef to an ObjCObjectType,
536 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
537 // debug info, we want to emit 'id' in both cases.
538 if (Ty->isObjCQualifiedIdType())
539 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
540
Guy Benyei11169dd2012-12-18 14:30:41 +0000541 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000542 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000543 Ty->getPointeeType(), Unit);
544 return DbgTy;
545}
546
547llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
548 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000549 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000550 Ty->getPointeeType(), Unit);
551}
552
553// Creates a forward declaration for a RecordDecl in the given context.
554llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
555 llvm::DIDescriptor Ctx) {
556 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
557 unsigned Line = getLineNumber(RD->getLocation());
558 StringRef RDName = getClassName(RD);
559
560 unsigned Tag = 0;
561 if (RD->isStruct() || RD->isInterface())
562 Tag = llvm::dwarf::DW_TAG_structure_type;
563 else if (RD->isUnion())
564 Tag = llvm::dwarf::DW_TAG_union_type;
565 else {
566 assert(RD->isClass());
567 Tag = llvm::dwarf::DW_TAG_class_type;
568 }
569
570 // Create the type.
571 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
572}
573
574// Walk up the context chain and create forward decls for record decls,
575// and normal descriptors for namespaces.
576llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
577 if (!Context)
578 return TheCU;
579
580 // See if we already have the parent.
581 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
582 I = RegionMap.find(Context);
583 if (I != RegionMap.end()) {
584 llvm::Value *V = I->second;
585 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
586 }
Eric Christopherb2a008c2013-05-16 00:45:12 +0000587
Guy Benyei11169dd2012-12-18 14:30:41 +0000588 // Check namespace.
589 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
590 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
591
592 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
593 if (!RD->isDependentType()) {
Eric Christopher0fdcb312013-05-16 00:52:20 +0000594 llvm::DIType Ty =
595 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
596 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000597 return llvm::DIDescriptor(Ty);
598 }
599 }
600 return TheCU;
601}
602
603/// CreatePointeeType - Create Pointee type. If Pointee is a record
604/// then emit record's fwd if debug info size reduction is enabled.
605llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
606 llvm::DIFile Unit) {
Eric Christopher75e17682013-05-16 00:45:23 +0000607 if (DebugKind != CodeGenOptions::LimitedDebugInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000608 return getOrCreateType(PointeeTy, Unit);
609
610 // Limit debug info for the pointee type.
611
612 // If we have an existing type, use that, it's still smaller than creating
613 // a new type.
614 llvm::DIType Ty = getTypeOrNull(PointeeTy);
615 if (Ty.Verify()) return Ty;
616
617 // Handle qualifiers.
618 if (PointeeTy.hasLocalQualifiers())
619 return CreateQualifiedType(PointeeTy, Unit);
620
621 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
622 RecordDecl *RD = RTy->getDecl();
623 llvm::DIDescriptor FDContext =
624 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
625 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
626 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
627 return RetTy;
628 }
629 return getOrCreateType(PointeeTy, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000630}
631
632llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000633 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000634 QualType PointeeTy,
635 llvm::DIFile Unit) {
636 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
637 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
638 return DBuilder.createReferenceType(Tag,
639 CreatePointeeType(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000640
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 // Bit size, align and offset of the type.
642 // Size is always the size of a pointer. We can't use getTypeSize here
643 // because that does not return the correct value for references.
644 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000645 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
647
648 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
649 Size, Align);
650}
651
Eric Christopher0fdcb312013-05-16 00:52:20 +0000652llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
653 llvm::DIType &Cache) {
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000654 if (Cache.Verify())
655 return Cache;
656 Cache =
657 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
658 Name, TheCU, getOrCreateMainFile(),
659 0);
660 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
661 Cache = DBuilder.createPointerType(Cache, Size);
662 return Cache;
663}
664
Guy Benyei11169dd2012-12-18 14:30:41 +0000665llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
666 llvm::DIFile Unit) {
667 if (BlockLiteralGenericSet)
668 return BlockLiteralGeneric;
669
670 SmallVector<llvm::Value *, 8> EltTys;
671 llvm::DIType FieldTy;
672 QualType FType;
673 uint64_t FieldSize, FieldOffset;
674 unsigned FieldAlign;
675 llvm::DIArray Elements;
676 llvm::DIType EltTy, DescTy;
677
678 FieldOffset = 0;
679 FType = CGM.getContext().UnsignedLongTy;
680 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
681 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
682
683 Elements = DBuilder.getOrCreateArray(EltTys);
684 EltTys.clear();
685
686 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
687 unsigned LineNo = getLineNumber(CurLoc);
688
689 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
690 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000691 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000692
693 // Bit size, align and offset of the type.
694 uint64_t Size = CGM.getContext().getTypeSize(Ty);
695
696 DescTy = DBuilder.createPointerType(EltTy, Size);
697
698 FieldOffset = 0;
699 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
700 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
701 FType = CGM.getContext().IntTy;
702 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
703 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
704 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
705 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
706
707 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
708 FieldTy = DescTy;
709 FieldSize = CGM.getContext().getTypeSize(Ty);
710 FieldAlign = CGM.getContext().getTypeAlign(Ty);
711 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
712 LineNo, FieldSize, FieldAlign,
713 FieldOffset, 0, FieldTy);
714 EltTys.push_back(FieldTy);
715
716 FieldOffset += FieldSize;
717 Elements = DBuilder.getOrCreateArray(EltTys);
718
719 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
720 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000721 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000722
723 BlockLiteralGenericSet = true;
724 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
725 return BlockLiteralGeneric;
726}
727
728llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
729 // Typedefs are derived from some other type. If we have a typedef of a
730 // typedef, make sure to emit the whole chain.
731 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
732 if (!Src.Verify())
733 return llvm::DIType();
734 // We don't set size information, but do specify where the typedef was
735 // declared.
736 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
737 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000738
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 llvm::DIDescriptor TypedefContext =
740 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000741
Guy Benyei11169dd2012-12-18 14:30:41 +0000742 return
743 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
744}
745
746llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
747 llvm::DIFile Unit) {
748 SmallVector<llvm::Value *, 16> EltTys;
749
750 // Add the result type at least.
751 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
752
753 // Set up remainder of arguments if there is a prototype.
754 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
755 if (isa<FunctionNoProtoType>(Ty))
756 EltTys.push_back(DBuilder.createUnspecifiedParameter());
757 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
758 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
759 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
760 }
761
762 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
763 return DBuilder.createSubroutineType(Unit, EltTypeArray);
764}
765
766
Guy Benyei11169dd2012-12-18 14:30:41 +0000767llvm::DIType CGDebugInfo::createFieldType(StringRef name,
768 QualType type,
769 uint64_t sizeInBitsOverride,
770 SourceLocation loc,
771 AccessSpecifier AS,
772 uint64_t offsetInBits,
773 llvm::DIFile tunit,
774 llvm::DIDescriptor scope) {
775 llvm::DIType debugType = getOrCreateType(type, tunit);
776
777 // Get the location for the field.
778 llvm::DIFile file = getOrCreateFile(loc);
779 unsigned line = getLineNumber(loc);
780
781 uint64_t sizeInBits = 0;
782 unsigned alignInBits = 0;
783 if (!type->isIncompleteArrayType()) {
784 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
785
786 if (sizeInBitsOverride)
787 sizeInBits = sizeInBitsOverride;
788 }
789
790 unsigned flags = 0;
791 if (AS == clang::AS_private)
792 flags |= llvm::DIDescriptor::FlagPrivate;
793 else if (AS == clang::AS_protected)
794 flags |= llvm::DIDescriptor::FlagProtected;
795
796 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
797 alignInBits, offsetInBits, flags, debugType);
798}
799
Eric Christopher91a31902013-01-16 01:22:32 +0000800/// CollectRecordLambdaFields - Helper for CollectRecordFields.
801void CGDebugInfo::
802CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
803 SmallVectorImpl<llvm::Value *> &elements,
804 llvm::DIType RecordTy) {
805 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
806 // has the name and the location of the variable so we should iterate over
807 // both concurrently.
808 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
809 RecordDecl::field_iterator Field = CXXDecl->field_begin();
810 unsigned fieldno = 0;
811 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
812 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
813 const LambdaExpr::Capture C = *I;
814 if (C.capturesVariable()) {
815 VarDecl *V = C.getCapturedVar();
816 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
817 StringRef VName = V->getName();
818 uint64_t SizeInBitsOverride = 0;
819 if (Field->isBitField()) {
820 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
821 assert(SizeInBitsOverride && "found named 0-width bitfield");
822 }
823 llvm::DIType fieldType
824 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
825 C.getLocation(), Field->getAccess(),
826 layout.getFieldOffset(fieldno), VUnit, RecordTy);
827 elements.push_back(fieldType);
828 } else {
829 // TODO: Need to handle 'this' in some way by probably renaming the
830 // this of the lambda class and having a field member of 'this' or
831 // by using AT_object_pointer for the function and having that be
832 // used as 'this' for semantic references.
833 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
834 FieldDecl *f = *Field;
835 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
836 QualType type = f->getType();
837 llvm::DIType fieldType
838 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
839 layout.getFieldOffset(fieldno), VUnit, RecordTy);
840
841 elements.push_back(fieldType);
842 }
843 }
844}
845
846/// CollectRecordStaticField - Helper for CollectRecordFields.
847void CGDebugInfo::
848CollectRecordStaticField(const VarDecl *Var,
849 SmallVectorImpl<llvm::Value *> &elements,
850 llvm::DIType RecordTy) {
851 // Create the descriptor for the static variable, with or without
852 // constant initializers.
853 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
854 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
855
856 // Do not describe enums as static members.
857 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
858 return;
859
860 unsigned LineNumber = getLineNumber(Var->getLocation());
861 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000862 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000863 if (Var->getInit()) {
864 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000865 if (Value) {
866 if (Value->isInt())
867 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
868 if (Value->isFloat())
869 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
870 }
Eric Christopher91a31902013-01-16 01:22:32 +0000871 }
872
873 unsigned Flags = 0;
874 AccessSpecifier Access = Var->getAccess();
875 if (Access == clang::AS_private)
876 Flags |= llvm::DIDescriptor::FlagPrivate;
877 else if (Access == clang::AS_protected)
878 Flags |= llvm::DIDescriptor::FlagProtected;
879
880 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikied42917f2013-01-20 01:19:17 +0000881 LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000882 elements.push_back(GV);
883 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
884}
885
886/// CollectRecordNormalField - Helper for CollectRecordFields.
887void CGDebugInfo::
888CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
889 llvm::DIFile tunit,
890 SmallVectorImpl<llvm::Value *> &elements,
891 llvm::DIType RecordTy) {
892 StringRef name = field->getName();
893 QualType type = field->getType();
894
895 // Ignore unnamed fields unless they're anonymous structs/unions.
896 if (name.empty() && !type->isRecordType())
897 return;
898
899 uint64_t SizeInBitsOverride = 0;
900 if (field->isBitField()) {
901 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
902 assert(SizeInBitsOverride && "found named 0-width bitfield");
903 }
904
905 llvm::DIType fieldType
906 = createFieldType(name, type, SizeInBitsOverride,
907 field->getLocation(), field->getAccess(),
908 OffsetInBits, tunit, RecordTy);
909
910 elements.push_back(fieldType);
911}
912
Guy Benyei11169dd2012-12-18 14:30:41 +0000913/// CollectRecordFields - A helper function to collect debug info for
914/// record fields. This is used while creating debug info entry for a Record.
915void CGDebugInfo::
916CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
917 SmallVectorImpl<llvm::Value *> &elements,
918 llvm::DIType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000919 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
920
Eric Christopher91a31902013-01-16 01:22:32 +0000921 if (CXXDecl && CXXDecl->isLambda())
922 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
923 else {
924 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000925
Eric Christopher91a31902013-01-16 01:22:32 +0000926 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000927 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000928
929 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei11169dd2012-12-18 14:30:41 +0000930 bool IsMsStruct = record->isMsStruct(CGM.getContext());
931 const FieldDecl *LastFD = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000932
Eric Christopher91a31902013-01-16 01:22:32 +0000933 // Static and non-static members should appear in the same order as
934 // the corresponding declarations in the source program.
935 for (RecordDecl::decl_iterator I = record->decls_begin(),
936 E = record->decls_end(); I != E; ++I)
937 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
938 CollectRecordStaticField(V, elements, RecordTy);
939 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
940 if (IsMsStruct) {
941 // Zero-length bitfields following non-bitfield members are
942 // completely ignored; we don't even count them.
943 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
944 continue;
945 LastFD = field;
Guy Benyei11169dd2012-12-18 14:30:41 +0000946 }
Eric Christopher91a31902013-01-16 01:22:32 +0000947 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
948 tunit, elements, RecordTy);
949
950 // Bump field number for next field.
951 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 }
954}
955
956/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
957/// function type is not updated to include implicit "this" pointer. Use this
958/// routine to get a method type which includes "this" pointer.
959llvm::DIType
960CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
961 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000962 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000963 if (Method->isStatic())
David Blaikie7eb06852013-01-07 23:06:35 +0000964 return getOrCreateType(QualType(Func, 0), Unit);
965 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
966 Func, Unit);
967}
David Blaikie2aaf0652013-01-07 22:24:59 +0000968
David Blaikie7eb06852013-01-07 23:06:35 +0000969llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
970 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000972 llvm::DIArray Args = llvm::DICompositeType(
973 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 assert (Args.getNumElements() && "Invalid number of arguments!");
975
976 SmallVector<llvm::Value *, 16> Elts;
977
978 // First element is always return type. For 'void' functions it is NULL.
979 Elts.push_back(Args.getElement(0));
980
David Blaikie2aaf0652013-01-07 22:24:59 +0000981 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000982 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000983 if (isa<ClassTemplateSpecializationDecl>(RD)) {
984 // Create pointer type directly in this case.
985 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
986 QualType PointeeTy = ThisPtrTy->getPointeeType();
987 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000988 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000989 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
990 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000991 llvm::DIType ThisPtrType =
992 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000993 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
994 // TODO: This and the artificial type below are misleading, the
995 // types aren't artificial the argument is, but the current
996 // metadata doesn't represent that.
997 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
998 Elts.push_back(ThisPtrType);
999 } else {
1000 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1001 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1002 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1003 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 }
1005
1006 // Copy rest of the arguments.
1007 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1008 Elts.push_back(Args.getElement(i));
1009
1010 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1011
1012 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1013}
1014
Eric Christopherb2a008c2013-05-16 00:45:12 +00001015/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001016/// inside a function.
1017static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1018 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1019 return isFunctionLocalClass(NRD);
1020 if (isa<FunctionDecl>(RD->getDeclContext()))
1021 return true;
1022 return false;
1023}
1024
1025/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1026/// a single member function GlobalDecl.
1027llvm::DISubprogram
1028CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1029 llvm::DIFile Unit,
1030 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001031 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001033
Guy Benyei11169dd2012-12-18 14:30:41 +00001034 StringRef MethodName = getFunctionName(Method);
1035 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
1036
1037 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1038 // make sense to give a single ctor/dtor a linkage name.
1039 StringRef MethodLinkageName;
1040 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1041 MethodLinkageName = CGM.getMangledName(Method);
1042
1043 // Get the location for the method.
1044 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1045 unsigned MethodLine = getLineNumber(Method->getLocation());
1046
1047 // Collect virtual method info.
1048 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001049 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001050 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001051
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 if (Method->isVirtual()) {
1053 if (Method->isPure())
1054 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1055 else
1056 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001057
Guy Benyei11169dd2012-12-18 14:30:41 +00001058 // It doesn't make sense to give a virtual destructor a vtable index,
1059 // since a single destructor has two entries in the vtable.
1060 if (!isa<CXXDestructorDecl>(Method))
1061 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1062 ContainingType = RecordTy;
1063 }
1064
1065 unsigned Flags = 0;
1066 if (Method->isImplicit())
1067 Flags |= llvm::DIDescriptor::FlagArtificial;
1068 AccessSpecifier Access = Method->getAccess();
1069 if (Access == clang::AS_private)
1070 Flags |= llvm::DIDescriptor::FlagPrivate;
1071 else if (Access == clang::AS_protected)
1072 Flags |= llvm::DIDescriptor::FlagProtected;
1073 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1074 if (CXXC->isExplicit())
1075 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001076 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001077 dyn_cast<CXXConversionDecl>(Method)) {
1078 if (CXXC->isExplicit())
1079 Flags |= llvm::DIDescriptor::FlagExplicit;
1080 }
1081 if (Method->hasPrototype())
1082 Flags |= llvm::DIDescriptor::FlagPrototyped;
1083
1084 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1085 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001086 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001088 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001089 /* isDefinition=*/ false,
1090 Virtuality, VIndex, ContainingType,
1091 Flags, CGM.getLangOpts().Optimize, NULL,
1092 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001093
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1095
1096 return SP;
1097}
1098
1099/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001100/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001101/// a Record.
1102void CGDebugInfo::
1103CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1104 SmallVectorImpl<llvm::Value *> &EltTys,
1105 llvm::DIType RecordTy) {
1106
1107 // Since we want more than just the individual member decls if we
1108 // have templated functions iterate over every declaration to gather
1109 // the functions.
1110 for(DeclContext::decl_iterator I = RD->decls_begin(),
1111 E = RD->decls_end(); I != E; ++I) {
1112 Decl *D = *I;
1113 if (D->isImplicit() && !D->isUsed())
1114 continue;
1115
1116 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1117 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1118 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1119 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1120 SE = FTD->spec_end(); SI != SE; ++SI)
1121 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1122 RecordTy));
1123 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001124}
Guy Benyei11169dd2012-12-18 14:30:41 +00001125
1126/// CollectCXXFriends - A helper function to collect debug info for
1127/// C++ base classes. This is used while creating debug info entry for
1128/// a Record.
1129void CGDebugInfo::
1130CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1131 SmallVectorImpl<llvm::Value *> &EltTys,
1132 llvm::DIType RecordTy) {
1133 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1134 BE = RD->friend_end(); BI != BE; ++BI) {
1135 if ((*BI)->isUnsupportedFriend())
1136 continue;
1137 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopherb2a008c2013-05-16 00:45:12 +00001138 EltTys.push_back(DBuilder.createFriend(RecordTy,
1139 getOrCreateType(TInfo->getType(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 Unit)));
1141 }
1142}
1143
1144/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001145/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001146/// a Record.
1147void CGDebugInfo::
1148CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1149 SmallVectorImpl<llvm::Value *> &EltTys,
1150 llvm::DIType RecordTy) {
1151
1152 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1153 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1154 BE = RD->bases_end(); BI != BE; ++BI) {
1155 unsigned BFlags = 0;
1156 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001157
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 const CXXRecordDecl *Base =
1159 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001160
Guy Benyei11169dd2012-12-18 14:30:41 +00001161 if (BI->isVirtual()) {
1162 // virtual base offset offset is -ve. The code generator emits dwarf
1163 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001164 BaseOffset =
Guy Benyei11169dd2012-12-18 14:30:41 +00001165 0 - CGM.getVTableContext()
1166 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1167 BFlags = llvm::DIDescriptor::FlagVirtual;
1168 } else
1169 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1170 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1171 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001172
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 AccessSpecifier Access = BI->getAccessSpecifier();
1174 if (Access == clang::AS_private)
1175 BFlags |= llvm::DIDescriptor::FlagPrivate;
1176 else if (Access == clang::AS_protected)
1177 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001178
1179 llvm::DIType DTy =
1180 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001181 getOrCreateType(BI->getType(), Unit),
1182 BaseOffset, BFlags);
1183 EltTys.push_back(DTy);
1184 }
1185}
1186
1187/// CollectTemplateParams - A helper function to collect template parameters.
1188llvm::DIArray CGDebugInfo::
1189CollectTemplateParams(const TemplateParameterList *TPList,
1190 const TemplateArgumentList &TAList,
1191 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001192 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001193 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1194 const TemplateArgument &TA = TAList[i];
1195 const NamedDecl *ND = TPList->getParam(i);
David Blaikie38079fd2013-05-10 21:53:14 +00001196 switch (TA.getKind()) {
1197 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001198 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1199 llvm::DITemplateTypeParameter TTP =
1200 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1201 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001202 } break;
1203 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001204 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1205 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001206 DBuilder.createTemplateValueParameter(
1207 TheCU, ND->getName(), TTy,
1208 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1209 TemplateParams.push_back(TVP);
1210 } break;
1211 case TemplateArgument::Declaration: {
1212 const ValueDecl *D = TA.getAsDecl();
1213 bool InstanceMember = D->isCXXInstanceMember();
1214 QualType T = InstanceMember
1215 ? CGM.getContext().getMemberPointerType(
1216 D->getType(), cast<RecordDecl>(D->getDeclContext())
1217 ->getTypeForDecl())
1218 : CGM.getContext().getPointerType(D->getType());
1219 llvm::DIType TTy = getOrCreateType(T, Unit);
1220 llvm::Value *V = 0;
1221 // Variable pointer template parameters have a value that is the address
1222 // of the variable.
1223 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1224 V = CGM.GetAddrOfGlobalVar(VD);
1225 // Member function pointers have special support for building them, though
1226 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001227 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001228 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1229 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001230 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1231 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001232 // Member data pointers have special handling too to compute the fixed
1233 // offset within the object.
1234 if (isa<FieldDecl>(D)) {
1235 // These five lines (& possibly the above member function pointer
1236 // handling) might be able to be refactored to use similar code in
1237 // CodeGenModule::getMemberPointerConstant
1238 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1239 CharUnits chars =
1240 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1241 V = CGM.getCXXABI().EmitMemberDataPointer(
1242 cast<MemberPointerType>(T.getTypePtr()), chars);
1243 }
1244 llvm::DITemplateValueParameter TVP =
1245 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1246 TemplateParams.push_back(TVP);
1247 } break;
1248 case TemplateArgument::NullPtr: {
1249 QualType T = TA.getNullPtrType();
1250 llvm::DIType TTy = getOrCreateType(T, Unit);
1251 llvm::Value *V = 0;
1252 // Special case member data pointer null values since they're actually -1
1253 // instead of zero.
1254 if (const MemberPointerType *MPT =
1255 dyn_cast<MemberPointerType>(T.getTypePtr()))
1256 // But treat member function pointers as simple zero integers because
1257 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1258 // CodeGen grows handling for values of non-null member function
1259 // pointers then perhaps we could remove this special case and rely on
1260 // EmitNullMemberPointer for member function pointers.
1261 if (MPT->isMemberDataPointer())
1262 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1263 if (!V)
1264 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1265 llvm::DITemplateValueParameter TVP =
1266 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1267 TemplateParams.push_back(TVP);
1268 } break;
1269 case TemplateArgument::Template:
1270 // We could support this with the GCC extension
1271 // DW_TAG_GNU_template_template_param
1272 break;
David Blaikie7e4c8b02013-05-10 22:53:25 +00001273 case TemplateArgument::Pack:
1274 // And this with DW_TAG_GNU_template_parameter_pack
1275 break;
David Blaikie2b93c542013-05-10 23:36:06 +00001276 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001277 case TemplateArgument::Expression:
1278 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001279 case TemplateArgument::Null:
1280 llvm_unreachable(
1281 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001282 }
1283 }
1284 return DBuilder.getOrCreateArray(TemplateParams);
1285}
1286
1287/// CollectFunctionTemplateParams - A helper function to collect debug
1288/// info for function template parameters.
1289llvm::DIArray CGDebugInfo::
1290CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1291 if (FD->getTemplatedKind() ==
1292 FunctionDecl::TK_FunctionTemplateSpecialization) {
1293 const TemplateParameterList *TList =
1294 FD->getTemplateSpecializationInfo()->getTemplate()
1295 ->getTemplateParameters();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001296 return
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1298 }
1299 return llvm::DIArray();
1300}
1301
1302/// CollectCXXTemplateParams - A helper function to collect debug info for
1303/// template parameters.
1304llvm::DIArray CGDebugInfo::
1305CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1306 llvm::DIFile Unit) {
1307 llvm::PointerUnion<ClassTemplateDecl *,
1308 ClassTemplatePartialSpecializationDecl *>
1309 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001310
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1312 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1313 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1314 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1315 return CollectTemplateParams(TPList, TAList, Unit);
1316}
1317
1318/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1319llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1320 if (VTablePtrType.isValid())
1321 return VTablePtrType;
1322
1323 ASTContext &Context = CGM.getContext();
1324
1325 /* Function type */
1326 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1327 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1328 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1329 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1330 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1331 "__vtbl_ptr_type");
1332 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1333 return VTablePtrType;
1334}
1335
1336/// getVTableName - Get vtable name for the given Class.
1337StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1338 // Construct gdb compatible name name.
1339 std::string Name = "_vptr$" + RD->getNameAsString();
1340
1341 // Copy this name on the side and use its reference.
1342 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1343 memcpy(StrPtr, Name.data(), Name.length());
1344 return StringRef(StrPtr, Name.length());
1345}
1346
1347
1348/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1349/// debug info entry in EltTys vector.
1350void CGDebugInfo::
1351CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1352 SmallVectorImpl<llvm::Value *> &EltTys) {
1353 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1354
1355 // If there is a primary base then it will hold vtable info.
1356 if (RL.getPrimaryBase())
1357 return;
1358
1359 // If this class is not dynamic then there is not any vtable info to collect.
1360 if (!RD->isDynamicClass())
1361 return;
1362
1363 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1364 llvm::DIType VPTR
1365 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001366 0, Size, 0, 0,
1367 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001368 getOrCreateVTablePtrType(Unit));
1369 EltTys.push_back(VPTR);
1370}
1371
Eric Christopherb2a008c2013-05-16 00:45:12 +00001372/// getOrCreateRecordType - Emit record type's standalone debug info.
1373llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001375 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1377 return T;
1378}
1379
1380/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1381/// debug info.
1382llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001383 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001384 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001386 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001387 return T;
1388}
1389
1390/// CreateType - get structure or union type.
1391llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1392 RecordDecl *RD = Ty->getDecl();
1393
1394 // Get overall information about the record type for the debug info.
1395 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1396
1397 // Records and classes and unions can all be recursive. To handle them, we
1398 // first generate a debug descriptor for the struct as a forward declaration.
1399 // Then (if it is a definition) we go through and get debug info for all of
1400 // its members. Finally, we create a descriptor for the complete type (which
1401 // may refer to the forward decl if the struct is recursive) and replace all
1402 // uses of the forward declaration with the final definition.
1403
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001404 llvm::DICompositeType FwdDecl(
1405 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1406 assert(FwdDecl.Verify() &&
1407 "The debug type of a RecordType should be a DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001408
1409 if (FwdDecl.isForwardDecl())
1410 return FwdDecl;
1411
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001413 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1415
Adrian Prantla03a85a2013-03-06 22:03:30 +00001416 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1418
1419 // Convert all the elements.
1420 SmallVector<llvm::Value *, 16> EltTys;
1421
1422 // Note: The split of CXXDecl information here is intentional, the
1423 // gdb tests will depend on a certain ordering at printout. The debug
1424 // information offsets are still correct if we merge them all together
1425 // though.
1426 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1427 if (CXXDecl) {
1428 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1429 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1430 }
1431
Eric Christopher91a31902013-01-16 01:22:32 +00001432 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1434 llvm::DIArray TParamsArray;
1435 if (CXXDecl) {
1436 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1437 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1438 if (const ClassTemplateSpecializationDecl *TSpecial
1439 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1440 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1441 }
1442
1443 LexicalBlockStack.pop_back();
1444 RegionMap.erase(Ty->getDecl());
1445
1446 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001447 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00001448
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001449 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1450 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001451}
1452
1453/// CreateType - get objective-c object type.
1454llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1455 llvm::DIFile Unit) {
1456 // Ignore protocols.
1457 return getOrCreateType(Ty->getBaseType(), Unit);
1458}
1459
1460/// CreateType - get objective-c interface type.
1461llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1462 llvm::DIFile Unit) {
1463 ObjCInterfaceDecl *ID = Ty->getDecl();
1464 if (!ID)
1465 return llvm::DIType();
1466
1467 // Get overall information about the record type for the debug info.
1468 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1469 unsigned Line = getLineNumber(ID->getLocation());
1470 unsigned RuntimeLang = TheCU.getLanguage();
1471
1472 // If this is just a forward declaration return a special forward-declaration
1473 // debug type since we won't be able to lay out the entire type.
1474 ObjCInterfaceDecl *Def = ID->getDefinition();
1475 if (!Def) {
1476 llvm::DIType FwdDecl =
1477 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001478 ID->getName(), TheCU, DefUnit, Line,
1479 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 return FwdDecl;
1481 }
1482
1483 ID = Def;
1484
1485 // Bit size, align and offset of the type.
1486 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1487 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1488
1489 unsigned Flags = 0;
1490 if (ID->getImplementation())
1491 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1492
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001493 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001494 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1495 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001496 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001497
1498 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1499 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001500 QualType QualTy = QualType(Ty, 0);
1501 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001502 // Push the struct on region stack.
Guy Benyei11169dd2012-12-18 14:30:41 +00001503
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001504 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1506
1507 // Convert all the elements.
1508 SmallVector<llvm::Value *, 16> EltTys;
1509
1510 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1511 if (SClass) {
1512 llvm::DIType SClassTy =
1513 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1514 if (!SClassTy.isValid())
1515 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001516
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 llvm::DIType InhTag =
1518 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1519 EltTys.push_back(InhTag);
1520 }
1521
1522 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1523 E = ID->prop_end(); I != E; ++I) {
1524 const ObjCPropertyDecl *PD = *I;
1525 SourceLocation Loc = PD->getLocation();
1526 llvm::DIFile PUnit = getOrCreateFile(Loc);
1527 unsigned PLine = getLineNumber(Loc);
1528 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1529 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1530 llvm::MDNode *PropertyNode =
1531 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001532 PUnit, PLine,
Guy Benyei11169dd2012-12-18 14:30:41 +00001533 (Getter && Getter->isImplicit()) ? "" :
1534 getSelectorName(PD->getGetterName()),
1535 (Setter && Setter->isImplicit()) ? "" :
1536 getSelectorName(PD->getSetterName()),
1537 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001538 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001539 EltTys.push_back(PropertyNode);
1540 }
1541
1542 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1543 unsigned FieldNo = 0;
1544 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1545 Field = Field->getNextIvar(), ++FieldNo) {
1546 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1547 if (!FieldTy.isValid())
1548 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001549
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 StringRef FieldName = Field->getName();
1551
1552 // Ignore unnamed fields.
1553 if (FieldName.empty())
1554 continue;
1555
1556 // Get the location for the field.
1557 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1558 unsigned FieldLine = getLineNumber(Field->getLocation());
1559 QualType FType = Field->getType();
1560 uint64_t FieldSize = 0;
1561 unsigned FieldAlign = 0;
1562
1563 if (!FType->isIncompleteArrayType()) {
1564
1565 // Bit size, align and offset of the type.
1566 FieldSize = Field->isBitField()
1567 ? Field->getBitWidthValue(CGM.getContext())
1568 : CGM.getContext().getTypeSize(FType);
1569 FieldAlign = CGM.getContext().getTypeAlign(FType);
1570 }
1571
1572 uint64_t FieldOffset;
1573 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1574 // We don't know the runtime offset of an ivar if we're using the
1575 // non-fragile ABI. For bitfields, use the bit offset into the first
1576 // byte of storage of the bitfield. For other fields, use zero.
1577 if (Field->isBitField()) {
1578 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1579 CGM, ID, Field);
1580 FieldOffset %= CGM.getContext().getCharWidth();
1581 } else {
1582 FieldOffset = 0;
1583 }
1584 } else {
1585 FieldOffset = RL.getFieldOffset(FieldNo);
1586 }
1587
1588 unsigned Flags = 0;
1589 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1590 Flags = llvm::DIDescriptor::FlagProtected;
1591 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1592 Flags = llvm::DIDescriptor::FlagPrivate;
1593
1594 llvm::MDNode *PropertyNode = NULL;
1595 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001596 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001597 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1598 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001599 SourceLocation Loc = PD->getLocation();
1600 llvm::DIFile PUnit = getOrCreateFile(Loc);
1601 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001602 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1603 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1604 PropertyNode =
1605 DBuilder.createObjCProperty(PD->getName(),
1606 PUnit, PLine,
1607 (Getter && Getter->isImplicit()) ? "" :
1608 getSelectorName(PD->getGetterName()),
1609 (Setter && Setter->isImplicit()) ? "" :
1610 getSelectorName(PD->getSetterName()),
1611 PD->getPropertyAttributes(),
1612 getOrCreateType(PD->getType(), PUnit));
1613 }
1614 }
1615 }
1616 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1617 FieldLine, FieldSize, FieldAlign,
1618 FieldOffset, Flags, FieldTy,
1619 PropertyNode);
1620 EltTys.push_back(FieldTy);
1621 }
1622
1623 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001624 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001625
1626 // If the implementation is not yet set, we do not want to mark it
1627 // as complete. An implementation may declare additional
1628 // private ivars that we would miss otherwise.
1629 if (ID->getImplementation() == 0)
1630 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001631
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001633 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001634}
1635
1636llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1637 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1638 int64_t Count = Ty->getNumElements();
1639 if (Count == 0)
1640 // If number of elements are not known then this is an unbounded array.
1641 // Use Count == -1 to express such arrays.
1642 Count = -1;
1643
1644 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1645 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1646
1647 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1648 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1649
1650 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1651}
1652
1653llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1654 llvm::DIFile Unit) {
1655 uint64_t Size;
1656 uint64_t Align;
1657
1658 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1659 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1660 Size = 0;
1661 Align =
1662 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1663 } else if (Ty->isIncompleteArrayType()) {
1664 Size = 0;
1665 if (Ty->getElementType()->isIncompleteType())
1666 Align = 0;
1667 else
1668 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001669 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001670 Size = 0;
1671 Align = 0;
1672 } else {
1673 // Size and align of the whole array, not the element type.
1674 Size = CGM.getContext().getTypeSize(Ty);
1675 Align = CGM.getContext().getTypeAlign(Ty);
1676 }
1677
1678 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1679 // interior arrays, do we care? Why aren't nested arrays represented the
1680 // obvious/recursive way?
1681 SmallVector<llvm::Value *, 8> Subscripts;
1682 QualType EltTy(Ty, 0);
1683 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1684 // If the number of elements is known, then count is that number. Otherwise,
1685 // it's -1. This allows us to represent a subrange with an array of 0
1686 // elements, like this:
1687 //
1688 // struct foo {
1689 // int x[0];
1690 // };
1691 int64_t Count = -1; // Count == -1 is an unbounded array.
1692 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1693 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001694
Guy Benyei11169dd2012-12-18 14:30:41 +00001695 // FIXME: Verify this is right for VLAs.
1696 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1697 EltTy = Ty->getElementType();
1698 }
1699
1700 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1701
Eric Christopherb2a008c2013-05-16 00:45:12 +00001702 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001703 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1704 SubscriptArray);
1705 return DbgTy;
1706}
1707
Eric Christopherb2a008c2013-05-16 00:45:12 +00001708llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001709 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001710 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001711 Ty, Ty->getPointeeType(), Unit);
1712}
1713
Eric Christopherb2a008c2013-05-16 00:45:12 +00001714llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001715 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001716 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001717 Ty, Ty->getPointeeType(), Unit);
1718}
1719
Eric Christopherb2a008c2013-05-16 00:45:12 +00001720llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001722 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1723 if (!Ty->getPointeeType()->isFunctionType())
1724 return DBuilder.createMemberPointerType(
1725 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1726 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1727 CGM.getContext().getPointerType(
1728 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1729 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1730 ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001731}
1732
Eric Christopherb2a008c2013-05-16 00:45:12 +00001733llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001734 llvm::DIFile U) {
1735 // Ignore the atomic wrapping
1736 // FIXME: What is the correct representation?
1737 return getOrCreateType(Ty->getValueType(), U);
1738}
1739
1740/// CreateEnumType - get enumeration type.
1741llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1742 uint64_t Size = 0;
1743 uint64_t Align = 0;
1744 if (!ED->getTypeForDecl()->isIncompleteType()) {
1745 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1746 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1747 }
1748
1749 // If this is just a forward declaration, construct an appropriately
1750 // marked node and just return it.
1751 if (!ED->getDefinition()) {
1752 llvm::DIDescriptor EDContext;
1753 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1754 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1755 unsigned Line = getLineNumber(ED->getLocation());
1756 StringRef EDName = ED->getName();
1757 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1758 EDName, EDContext, DefUnit, Line, 0,
1759 Size, Align);
1760 }
1761
1762 // Create DIEnumerator elements for each enumerator.
1763 SmallVector<llvm::Value *, 16> Enumerators;
1764 ED = ED->getDefinition();
1765 for (EnumDecl::enumerator_iterator
1766 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1767 Enum != EnumEnd; ++Enum) {
1768 Enumerators.push_back(
1769 DBuilder.createEnumerator(Enum->getName(),
1770 Enum->getInitVal().getZExtValue()));
1771 }
1772
1773 // Return a CompositeType for the enum itself.
1774 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1775
1776 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1777 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001778 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001780 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001781 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001782 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001783 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1784 Size, Align, EltArray,
1785 ClassTy);
1786 return DbgTy;
1787}
1788
David Blaikie05491062013-01-21 04:37:12 +00001789static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1790 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001791 do {
David Blaikie05491062013-01-21 04:37:12 +00001792 Quals += T.getLocalQualifiers();
Guy Benyei11169dd2012-12-18 14:30:41 +00001793 QualType LastT = T;
1794 switch (T->getTypeClass()) {
1795 default:
David Blaikie05491062013-01-21 04:37:12 +00001796 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001797 case Type::TemplateSpecialization:
1798 T = cast<TemplateSpecializationType>(T)->desugar();
1799 break;
1800 case Type::TypeOfExpr:
1801 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1802 break;
1803 case Type::TypeOf:
1804 T = cast<TypeOfType>(T)->getUnderlyingType();
1805 break;
1806 case Type::Decltype:
1807 T = cast<DecltypeType>(T)->getUnderlyingType();
1808 break;
1809 case Type::UnaryTransform:
1810 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1811 break;
1812 case Type::Attributed:
1813 T = cast<AttributedType>(T)->getEquivalentType();
1814 break;
1815 case Type::Elaborated:
1816 T = cast<ElaboratedType>(T)->getNamedType();
1817 break;
1818 case Type::Paren:
1819 T = cast<ParenType>(T)->getInnerType();
1820 break;
David Blaikie05491062013-01-21 04:37:12 +00001821 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001822 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 break;
1824 case Type::Auto:
1825 T = cast<AutoType>(T)->getDeducedType();
1826 break;
1827 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001828
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001830 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 } while (true);
1832}
1833
Eric Christopher0fdcb312013-05-16 00:52:20 +00001834/// getType - Get the type from the cache or return null type if it doesn't
1835/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001836llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1837
1838 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001839 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001840
Guy Benyei11169dd2012-12-18 14:30:41 +00001841 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00001842 if (Ty->getTypeClass() == Type::ObjCInterface) {
1843 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1844 if (V)
1845 return llvm::DIType(cast<llvm::MDNode>(V));
1846 else return llvm::DIType();
1847 }
1848
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1850 TypeCache.find(Ty.getAsOpaquePtr());
1851 if (it != TypeCache.end()) {
1852 // Verify that the debug info still exists.
1853 if (llvm::Value *V = it->second)
1854 return llvm::DIType(cast<llvm::MDNode>(V));
1855 }
1856
1857 return llvm::DIType();
1858}
1859
1860/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1861/// doesn't exist.
1862llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1863
1864 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001865 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001866
1867 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001868 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001869 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1870 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00001871 if (it != CompletedTypeCache.end())
1872 V = it->second;
1873 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00001874 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001875 }
1876
Adrian Prantla03a85a2013-03-06 22:03:30 +00001877 // Verify that any cached debug info still exists.
1878 if (V != 0)
1879 return llvm::DIType(cast<llvm::MDNode>(V));
1880
Guy Benyei11169dd2012-12-18 14:30:41 +00001881 return llvm::DIType();
1882}
1883
Adrian Prantl73409ce2013-03-11 18:33:46 +00001884/// getCachedInterfaceTypeOrNull - Get the type from the interface
1885/// cache, unless it needs to regenerated. Otherwise return null.
1886llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1887 // Is there a cached interface that hasn't changed?
1888 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1889 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1890
1891 if (it1 != ObjCInterfaceCache.end())
1892 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1893 if (Checksum(Decl) == it1->second.second)
1894 // Return cached forward declaration.
1895 return it1->second.first;
1896
1897 return 0;
1898}
Guy Benyei11169dd2012-12-18 14:30:41 +00001899
1900/// getOrCreateType - Get the type from the cache or create a new
1901/// one if necessary.
1902llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1903 if (Ty.isNull())
1904 return llvm::DIType();
1905
1906 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001907 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001908
1909 llvm::DIType T = getCompletedTypeOrNull(Ty);
1910
1911 if (T.Verify())
1912 return T;
1913
1914 // Otherwise create the type.
1915 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00001916 void* TyPtr = Ty.getAsOpaquePtr();
1917
1918 // And update the type cache.
1919 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00001920
1921 llvm::DIType TC = getTypeOrNull(Ty);
1922 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00001923 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1924 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1925 // Interface types may have elements added to them by a
1926 // subsequent implementation or extension, so we keep them in
1927 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00001928 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00001929 // declaration that gets RAUW'd in CGDebugInfo::finalize().
1930 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1931 ::iterator it = ObjCInterfaceCache.find(TyPtr);
1932 if (it != ObjCInterfaceCache.end())
1933 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first));
1934 else
1935 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Adrian Prantlc7822422013-03-12 20:43:25 +00001936 Decl->getName(), TheCU, Unit,
1937 getLineNumber(Decl->getLocation()),
1938 TheCU.getLanguage());
Adrian Prantl73409ce2013-03-11 18:33:46 +00001939 // Store the forward declaration in the cache.
1940 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl));
1941
1942 // Register the type for replacement in finalize().
1943 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1944 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00001945 }
1946
Guy Benyei11169dd2012-12-18 14:30:41 +00001947 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00001948 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00001949
1950 return Res;
1951}
1952
Adrian Prantla03a85a2013-03-06 22:03:30 +00001953/// Currently the checksum merely consists of the number of ivars.
1954unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantlc7822422013-03-12 20:43:25 +00001955 *InterfaceDecl) {
Adrian Prantla03a85a2013-03-06 22:03:30 +00001956 unsigned IvarNo = 0;
1957 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1958 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1959 return IvarNo;
1960}
1961
1962ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1963 switch (Ty->getTypeClass()) {
1964 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00001965 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
1966 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00001967 case Type::ObjCInterface:
1968 return cast<ObjCInterfaceType>(Ty)->getDecl();
1969 default:
1970 return 0;
1971 }
1972}
1973
Guy Benyei11169dd2012-12-18 14:30:41 +00001974/// CreateTypeNode - Create a new debug type node.
1975llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1976 // Handle qualifiers, which recursively handles what they refer to.
1977 if (Ty.hasLocalQualifiers())
1978 return CreateQualifiedType(Ty, Unit);
1979
1980 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001981
Guy Benyei11169dd2012-12-18 14:30:41 +00001982 // Work out details of type.
1983 switch (Ty->getTypeClass()) {
1984#define TYPE(Class, Base)
1985#define ABSTRACT_TYPE(Class, Base)
1986#define NON_CANONICAL_TYPE(Class, Base)
1987#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1988#include "clang/AST/TypeNodes.def"
1989 llvm_unreachable("Dependent types cannot show up in debug information");
1990
1991 case Type::ExtVector:
1992 case Type::Vector:
1993 return CreateType(cast<VectorType>(Ty), Unit);
1994 case Type::ObjCObjectPointer:
1995 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1996 case Type::ObjCObject:
1997 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1998 case Type::ObjCInterface:
1999 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2000 case Type::Builtin:
2001 return CreateType(cast<BuiltinType>(Ty));
2002 case Type::Complex:
2003 return CreateType(cast<ComplexType>(Ty));
2004 case Type::Pointer:
2005 return CreateType(cast<PointerType>(Ty), Unit);
2006 case Type::BlockPointer:
2007 return CreateType(cast<BlockPointerType>(Ty), Unit);
2008 case Type::Typedef:
2009 return CreateType(cast<TypedefType>(Ty), Unit);
2010 case Type::Record:
2011 return CreateType(cast<RecordType>(Ty));
2012 case Type::Enum:
2013 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2014 case Type::FunctionProto:
2015 case Type::FunctionNoProto:
2016 return CreateType(cast<FunctionType>(Ty), Unit);
2017 case Type::ConstantArray:
2018 case Type::VariableArray:
2019 case Type::IncompleteArray:
2020 return CreateType(cast<ArrayType>(Ty), Unit);
2021
2022 case Type::LValueReference:
2023 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2024 case Type::RValueReference:
2025 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2026
2027 case Type::MemberPointer:
2028 return CreateType(cast<MemberPointerType>(Ty), Unit);
2029
2030 case Type::Atomic:
2031 return CreateType(cast<AtomicType>(Ty), Unit);
2032
2033 case Type::Attributed:
2034 case Type::TemplateSpecialization:
2035 case Type::Elaborated:
2036 case Type::Paren:
2037 case Type::SubstTemplateTypeParm:
2038 case Type::TypeOfExpr:
2039 case Type::TypeOf:
2040 case Type::Decltype:
2041 case Type::UnaryTransform:
2042 case Type::Auto:
2043 llvm_unreachable("type should have been unwrapped!");
2044 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002045
Guy Benyei11169dd2012-12-18 14:30:41 +00002046 assert(Diag && "Fall through without a diagnostic?");
2047 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2048 "debug information for %0 is not yet supported");
2049 CGM.getDiags().Report(DiagID)
2050 << Diag;
2051 return llvm::DIType();
2052}
2053
2054/// getOrCreateLimitedType - Get the type from the cache or create a new
2055/// limited type if necessary.
2056llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002057 llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002058 if (Ty.isNull())
2059 return llvm::DIType();
2060
2061 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002062 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002063
2064 llvm::DIType T = getTypeOrNull(Ty);
2065
2066 // We may have cached a forward decl when we could have created
2067 // a non-forward decl. Go ahead and create a non-forward decl
2068 // now.
2069 if (T.Verify() && !T.isForwardDecl()) return T;
2070
2071 // Otherwise create the type.
2072 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2073
2074 if (T.Verify() && T.isForwardDecl())
2075 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2076 static_cast<llvm::Value*>(T)));
2077
2078 // And update the type cache.
2079 TypeCache[Ty.getAsOpaquePtr()] = Res;
2080 return Res;
2081}
2082
2083// TODO: Currently used for context chains when limiting debug info.
2084llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2085 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002086
Guy Benyei11169dd2012-12-18 14:30:41 +00002087 // Get overall information about the record type for the debug info.
2088 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2089 unsigned Line = getLineNumber(RD->getLocation());
2090 StringRef RDName = getClassName(RD);
2091
2092 llvm::DIDescriptor RDContext;
Eric Christopher75e17682013-05-16 00:45:23 +00002093 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +00002094 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2095 else
2096 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2097
2098 // If this is just a forward declaration, construct an appropriately
2099 // marked node and just return it.
2100 if (!RD->getDefinition())
2101 return createRecordFwdDecl(RD, RDContext);
2102
2103 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2104 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2105 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie49ae6a72013-03-26 23:47:35 +00002106 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002107
Guy Benyei11169dd2012-12-18 14:30:41 +00002108 if (RD->isUnion())
2109 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002110 Size, Align, 0, llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 else if (RD->isClass()) {
2112 // FIXME: This could be a struct type giving a default visibility different
2113 // than C++ class type, but needs llvm metadata changes first.
2114 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002115 Size, Align, 0, 0, llvm::DIType(),
2116 llvm::DIArray(), llvm::DIType(),
2117 llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002118 } else
2119 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002120 Size, Align, 0, llvm::DIType(),
2121 llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002122
2123 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002124 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002125
2126 if (CXXDecl) {
2127 // A class's primary base or the class itself contains the vtable.
David Blaikie49ae6a72013-03-26 23:47:35 +00002128 llvm::DICompositeType ContainingType;
Guy Benyei11169dd2012-12-18 14:30:41 +00002129 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2130 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2131 // Seek non virtual primary base root.
2132 while (1) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00002133 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2134 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2135 if (PBT && !BRL.isPrimaryBaseVirtual())
2136 PBase = PBT;
2137 else
2138 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002139 }
David Blaikie49ae6a72013-03-26 23:47:35 +00002140 ContainingType = llvm::DICompositeType(
2141 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2142 } else if (CXXDecl->isDynamicClass())
Guy Benyei11169dd2012-12-18 14:30:41 +00002143 ContainingType = RealDecl;
2144
David Blaikie49ae6a72013-03-26 23:47:35 +00002145 RealDecl.setContainingType(ContainingType);
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 }
2147 return llvm::DIType(RealDecl);
2148}
2149
2150/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2151/// declare composite types that haven't been processed yet.
2152llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2153
2154 // Work out details of type.
2155 switch (Ty->getTypeClass()) {
2156#define TYPE(Class, Base)
2157#define ABSTRACT_TYPE(Class, Base)
2158#define NON_CANONICAL_TYPE(Class, Base)
2159#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2160 #include "clang/AST/TypeNodes.def"
2161 llvm_unreachable("Dependent types cannot show up in debug information");
2162
2163 case Type::Record:
2164 return CreateLimitedType(cast<RecordType>(Ty));
2165 default:
2166 return CreateTypeNode(Ty, Unit);
2167 }
2168}
2169
2170/// CreateMemberType - Create new member and increase Offset by FType's size.
2171llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2172 StringRef Name,
2173 uint64_t *Offset) {
2174 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2175 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2176 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2177 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2178 FieldSize, FieldAlign,
2179 *Offset, 0, FieldTy);
2180 *Offset += FieldSize;
2181 return Ty;
2182}
2183
2184/// getFunctionDeclaration - Return debug info descriptor to describe method
2185/// declaration for the given method definition.
2186llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2187 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2188 if (!FD) return llvm::DISubprogram();
2189
2190 // Setup context.
2191 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2192
2193 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2194 MI = SPCache.find(FD->getCanonicalDecl());
2195 if (MI != SPCache.end()) {
2196 llvm::Value *V = MI->second;
2197 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2198 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2199 return SP;
2200 }
2201
2202 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2203 E = FD->redecls_end(); I != E; ++I) {
2204 const FunctionDecl *NextFD = *I;
2205 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2206 MI = SPCache.find(NextFD->getCanonicalDecl());
2207 if (MI != SPCache.end()) {
2208 llvm::Value *V = MI->second;
2209 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2210 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2211 return SP;
2212 }
2213 }
2214 return llvm::DISubprogram();
2215}
2216
2217// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2218// implicit parameter "this".
2219llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2220 QualType FnType,
2221 llvm::DIFile F) {
2222
2223 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2224 return getOrCreateMethodType(Method, F);
2225 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2226 // Add "self" and "_cmd"
2227 SmallVector<llvm::Value *, 16> Elts;
2228
2229 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl7bec9032013-05-10 21:08:31 +00002230 QualType ResultTy = OMethod->hasRelatedResultType()
2231 ? QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)
2232 : OMethod->getResultType();
2233 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002234 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002235 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2236 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2237 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002238 // "_cmd" pointer is always second argument.
2239 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2240 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2241 // Get rest of the arguments.
Eric Christopherb2a008c2013-05-16 00:45:12 +00002242 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002243 PE = OMethod->param_end(); PI != PE; ++PI)
2244 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2245
2246 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2247 return DBuilder.createSubroutineType(F, EltTypeArray);
2248 }
2249 return getOrCreateType(FnType, F);
2250}
2251
2252/// EmitFunctionStart - Constructs the debug code for entering a function.
2253void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2254 llvm::Function *Fn,
2255 CGBuilderTy &Builder) {
2256
2257 StringRef Name;
2258 StringRef LinkageName;
2259
2260 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2261
2262 const Decl *D = GD.getDecl();
2263 // Function may lack declaration in source code if it is created by Clang
2264 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2265 bool HasDecl = (D != 0);
2266 // Use the location of the declaration.
2267 SourceLocation Loc;
2268 if (HasDecl)
2269 Loc = D->getLocation();
2270
2271 unsigned Flags = 0;
2272 llvm::DIFile Unit = getOrCreateFile(Loc);
2273 llvm::DIDescriptor FDContext(Unit);
2274 llvm::DIArray TParamsArray;
2275 if (!HasDecl) {
2276 // Use llvm function name.
2277 Name = Fn->getName();
2278 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2279 // If there is a DISubprogram for this function available then use it.
2280 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2281 FI = SPCache.find(FD->getCanonicalDecl());
2282 if (FI != SPCache.end()) {
2283 llvm::Value *V = FI->second;
2284 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2285 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2286 llvm::MDNode *SPN = SP;
2287 LexicalBlockStack.push_back(SPN);
2288 RegionMap[D] = llvm::WeakVH(SP);
2289 return;
2290 }
2291 }
2292 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002293 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 if (FD->hasPrototype()) {
2295 LinkageName = CGM.getMangledName(GD);
2296 Flags |= llvm::DIDescriptor::FlagPrototyped;
2297 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002298 // No need to replicate the linkage name if it isn't different from the
2299 // subprogram name, no need to have it at all unless coverage is enabled or
2300 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002301 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002302 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2303 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002304 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 LinkageName = StringRef();
2306
Eric Christopher75e17682013-05-16 00:45:23 +00002307 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 if (const NamespaceDecl *NSDecl =
2309 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2310 FDContext = getOrCreateNameSpace(NSDecl);
2311 else if (const RecordDecl *RDecl =
2312 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2313 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2314
2315 // Collect template parameters.
2316 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2317 }
2318 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2319 Name = getObjCMethodName(OMD);
2320 Flags |= llvm::DIDescriptor::FlagPrototyped;
2321 } else {
2322 // Use llvm function name.
2323 Name = Fn->getName();
2324 Flags |= llvm::DIDescriptor::FlagPrototyped;
2325 }
2326 if (!Name.empty() && Name[0] == '\01')
2327 Name = Name.substr(1);
2328
2329 unsigned LineNo = getLineNumber(Loc);
2330 if (!HasDecl || D->isImplicit())
2331 Flags |= llvm::DIDescriptor::FlagArtificial;
2332
2333 llvm::DIType DIFnType;
2334 llvm::DISubprogram SPDecl;
2335 if (HasDecl &&
Eric Christopher75e17682013-05-16 00:45:23 +00002336 DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002337 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2338 SPDecl = getFunctionDeclaration(D);
2339 } else {
2340 // Create fake but valid subroutine type. Otherwise
2341 // llvm::DISubprogram::Verify() would return false, and
2342 // subprogram DIE will miss DW_AT_decl_file and
2343 // DW_AT_decl_line fields.
2344 SmallVector<llvm::Value*, 16> Elts;
2345 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2346 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2347 }
2348 llvm::DISubprogram SP;
2349 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2350 LineNo, DIFnType,
2351 Fn->hasInternalLinkage(), true/*definition*/,
2352 getLineNumber(CurLoc), Flags,
2353 CGM.getLangOpts().Optimize,
2354 Fn, TParamsArray, SPDecl);
2355
2356 // Push function on region stack.
2357 llvm::MDNode *SPN = SP;
2358 LexicalBlockStack.push_back(SPN);
2359 if (HasDecl)
2360 RegionMap[D] = llvm::WeakVH(SP);
2361}
2362
2363/// EmitLocation - Emit metadata to indicate a change in line/column
2364/// information in the source file.
Adrian Prantlc7822422013-03-12 20:43:25 +00002365void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2366 bool ForceColumnInfo) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002367
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 // Update our current location
2369 setLocation(Loc);
2370
2371 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2372
2373 // Don't bother if things are the same as last time.
2374 SourceManager &SM = CGM.getContext().getSourceManager();
2375 if (CurLoc == PrevLoc ||
2376 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2377 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002378 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2379 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2380 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002382
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 // Update last state.
2384 PrevLoc = CurLoc;
2385
2386 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002387 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2388 (getLineNumber(CurLoc),
2389 getColumnNumber(CurLoc, ForceColumnInfo),
2390 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002391}
2392
2393/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2394/// the stack.
2395void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2396 llvm::DIDescriptor D =
2397 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2398 llvm::DIDescriptor() :
2399 llvm::DIDescriptor(LexicalBlockStack.back()),
2400 getOrCreateFile(CurLoc),
2401 getLineNumber(CurLoc),
2402 getColumnNumber(CurLoc));
2403 llvm::MDNode *DN = D;
2404 LexicalBlockStack.push_back(DN);
2405}
2406
2407/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2408/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002409void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2410 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 // Set our current location.
2412 setLocation(Loc);
2413
2414 // Create a new lexical block and push it on the stack.
2415 CreateLexicalBlock(Loc);
2416
2417 // Emit a line table change for the current location inside the new scope.
2418 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2419 getColumnNumber(Loc),
2420 LexicalBlockStack.back()));
2421}
2422
2423/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2424/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002425void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2426 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2428
2429 // Provide an entry in the line table for the end of the block.
2430 EmitLocation(Builder, Loc);
2431
2432 LexicalBlockStack.pop_back();
2433}
2434
2435/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2436void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2437 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2438 unsigned RCount = FnBeginRegionCount.back();
2439 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2440
2441 // Pop all regions for this function.
2442 while (LexicalBlockStack.size() != RCount)
2443 EmitLexicalBlockEnd(Builder, CurLoc);
2444 FnBeginRegionCount.pop_back();
2445}
2446
Eric Christopherb2a008c2013-05-16 00:45:12 +00002447// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002448// See BuildByRefType.
2449llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2450 uint64_t *XOffset) {
2451
2452 SmallVector<llvm::Value *, 5> EltTys;
2453 QualType FType;
2454 uint64_t FieldSize, FieldOffset;
2455 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002456
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002458 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002459
2460 FieldOffset = 0;
2461 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2462 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2463 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2464 FType = CGM.getContext().IntTy;
2465 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2466 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2467
2468 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2469 if (HasCopyAndDispose) {
2470 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2471 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2472 &FieldOffset));
2473 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2474 &FieldOffset));
2475 }
2476 bool HasByrefExtendedLayout;
2477 Qualifiers::ObjCLifetime Lifetime;
2478 if (CGM.getContext().getByrefLifetime(Type,
2479 Lifetime, HasByrefExtendedLayout)
2480 && HasByrefExtendedLayout)
2481 EltTys.push_back(CreateMemberType(Unit, FType,
2482 "__byref_variable_layout",
2483 &FieldOffset));
Eric Christopherb2a008c2013-05-16 00:45:12 +00002484
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2486 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002487 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002488 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2490 CharUnits AlignedOffsetInBytes
2491 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2492 CharUnits NumPaddingBytes
2493 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002494
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 if (NumPaddingBytes.isPositive()) {
2496 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2497 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2498 pad, ArrayType::Normal, 0);
2499 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2500 }
2501 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002502
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 FType = Type;
2504 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2505 FieldSize = CGM.getContext().getTypeSize(FType);
2506 FieldAlign = CGM.getContext().toBits(Align);
2507
Eric Christopherb2a008c2013-05-16 00:45:12 +00002508 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2510 0, FieldSize, FieldAlign,
2511 FieldOffset, 0, FieldTy);
2512 EltTys.push_back(FieldTy);
2513 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002514
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002516
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002518
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002520 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002521}
2522
2523/// EmitDeclare - Emit local variable declaration debug info.
2524void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002525 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002527 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2529
2530 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2531 llvm::DIType Ty;
2532 uint64_t XOffset = 0;
2533 if (VD->hasAttr<BlocksAttr>())
2534 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002535 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 Ty = getOrCreateType(VD->getType(), Unit);
2537
2538 // If there is no debug info for this type then do not emit debug info
2539 // for this variable.
2540 if (!Ty)
2541 return;
2542
2543 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2544 // If Storage is an aggregate returned as 'sret' then let debugger know
2545 // about this.
2546 if (Arg->hasStructRetAttr())
2547 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2548 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2549 // If an aggregate variable has non trivial destructor or non trivial copy
2550 // constructor than it is pass indirectly. Let debug info know about this
2551 // by using reference of the aggregate type as a argument type.
2552 if (Record->hasNonTrivialCopyConstructor() ||
2553 !Record->hasTrivialDestructor())
Eric Christopher0fdcb312013-05-16 00:52:20 +00002554 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type,
2555 Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 }
2557 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002558
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 // Get location information.
2560 unsigned Line = getLineNumber(VD->getLocation());
2561 unsigned Column = getColumnNumber(VD->getLocation());
2562 unsigned Flags = 0;
2563 if (VD->isImplicit())
2564 Flags |= llvm::DIDescriptor::FlagArtificial;
2565 // If this is the first argument and it is implicit then
2566 // give it an object pointer flag.
2567 // FIXME: There has to be a better way to do this, but for static
2568 // functions there won't be an implicit param at arg1 and
2569 // otherwise it is 'self' or 'this'.
2570 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2571 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2572
2573 llvm::MDNode *Scope = LexicalBlockStack.back();
2574
2575 StringRef Name = VD->getName();
2576 if (!Name.empty()) {
2577 if (VD->hasAttr<BlocksAttr>()) {
2578 CharUnits offset = CharUnits::fromQuantity(32);
2579 SmallVector<llvm::Value *, 9> addr;
2580 llvm::Type *Int64Ty = CGM.Int64Ty;
2581 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2582 // offset of __forwarding field
2583 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002584 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2586 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2587 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2588 // offset of x field
2589 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2590 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2591
2592 // Create the descriptor for the variable.
2593 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002594 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 llvm::DIDescriptor(Scope),
2596 VD->getName(), Unit, Line, Ty,
2597 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002598
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 // Insert an llvm.dbg.declare into the current block.
2600 llvm::Instruction *Call =
2601 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2602 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2603 return;
Adrian Prantlab067ae2013-04-30 22:45:09 +00002604 } else if (isa<VariableArrayType>(VD->getType())) {
2605 // These are "complex" variables in that they need an op_deref.
2606 // Create the descriptor for the variable.
2607 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2608 llvm::DIBuilder::OpDeref);
2609 llvm::DIVariable D =
2610 DBuilder.createComplexVariable(Tag,
2611 llvm::DIDescriptor(Scope),
2612 Name, Unit, Line, Ty,
2613 Addr, ArgNo);
2614
2615 // Insert an llvm.dbg.declare into the current block.
2616 llvm::Instruction *Call =
2617 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2618 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2619 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002621 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2622 // If VD is an anonymous union then Storage represents value for
2623 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002625 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 for (RecordDecl::field_iterator I = RD->field_begin(),
2627 E = RD->field_end();
2628 I != E; ++I) {
2629 FieldDecl *Field = *I;
2630 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2631 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002632
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 // Ignore unnamed fields. Do not ignore unnamed records.
2634 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2635 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002636
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 // Use VarDecl's Tag, Scope and Line number.
2638 llvm::DIVariable D =
2639 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002640 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 CGM.getLangOpts().Optimize, Flags,
2642 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002643
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 // Insert an llvm.dbg.declare into the current block.
2645 llvm::Instruction *Call =
2646 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2647 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2648 }
David Blaikie219c7d92013-01-05 20:03:07 +00002649 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 }
2651 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002652
2653 // Create the descriptor for the variable.
2654 llvm::DIVariable D =
2655 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2656 Name, Unit, Line, Ty,
2657 CGM.getLangOpts().Optimize, Flags, ArgNo);
2658
2659 // Insert an llvm.dbg.declare into the current block.
2660 llvm::Instruction *Call =
2661 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2662 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002663}
2664
2665void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2666 llvm::Value *Storage,
2667 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002668 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2670}
2671
Adrian Prantlde17db32013-03-29 19:20:29 +00002672/// Look up the completed type for a self pointer in the TypeCache and
2673/// create a copy of it with the ObjectPointer and Artificial flags
2674/// set. If the type is not cached, a new one is created. This should
2675/// never happen though, since creating a type for the implicit self
2676/// argument implies that we already parsed the interface definition
2677/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002678llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2679 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002680 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2681 if (CachedTy.Verify()) Ty = CachedTy;
2682 else DEBUG(llvm::dbgs() << "No cached type for self.");
2683 return DBuilder.createObjectPointerType(Ty);
2684}
2685
Guy Benyei11169dd2012-12-18 14:30:41 +00002686void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2687 llvm::Value *Storage,
2688 CGBuilderTy &Builder,
2689 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002690 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002692
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 if (Builder.GetInsertBlock() == 0)
2694 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002695
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002697
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 uint64_t XOffset = 0;
2699 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2700 llvm::DIType Ty;
2701 if (isByRef)
2702 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002703 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 Ty = getOrCreateType(VD->getType(), Unit);
2705
2706 // Self is passed along as an implicit non-arg variable in a
2707 // block. Mark it as the object pointer.
2708 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002709 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002710
2711 // Get location information.
2712 unsigned Line = getLineNumber(VD->getLocation());
2713 unsigned Column = getColumnNumber(VD->getLocation());
2714
2715 const llvm::DataLayout &target = CGM.getDataLayout();
2716
2717 CharUnits offset = CharUnits::fromQuantity(
2718 target.getStructLayout(blockInfo.StructureType)
2719 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2720
2721 SmallVector<llvm::Value *, 9> addr;
2722 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002723 if (isa<llvm::AllocaInst>(Storage))
2724 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2726 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2727 if (isByRef) {
2728 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2729 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2730 // offset of __forwarding field
2731 offset = CGM.getContext()
2732 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2733 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2734 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2735 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2736 // offset of x field
2737 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2738 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2739 }
2740
2741 // Create the descriptor for the variable.
2742 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002743 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 llvm::DIDescriptor(LexicalBlockStack.back()),
2745 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002746
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 // Insert an llvm.dbg.declare into the current block.
2748 llvm::Instruction *Call =
2749 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2750 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2751 LexicalBlockStack.back()));
2752}
2753
2754/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2755/// variable declaration.
2756void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2757 unsigned ArgNo,
2758 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002759 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2761}
2762
2763namespace {
2764 struct BlockLayoutChunk {
2765 uint64_t OffsetInBits;
2766 const BlockDecl::Capture *Capture;
2767 };
2768 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2769 return l.OffsetInBits < r.OffsetInBits;
2770 }
2771}
2772
2773void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002774 llvm::Value *Arg,
2775 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002777 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 ASTContext &C = CGM.getContext();
2779 const BlockDecl *blockDecl = block.getBlockDecl();
2780
2781 // Collect some general information about the block's location.
2782 SourceLocation loc = blockDecl->getCaretLocation();
2783 llvm::DIFile tunit = getOrCreateFile(loc);
2784 unsigned line = getLineNumber(loc);
2785 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002786
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 // Build the debug-info type for the block literal.
2788 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2789
2790 const llvm::StructLayout *blockLayout =
2791 CGM.getDataLayout().getStructLayout(block.StructureType);
2792
2793 SmallVector<llvm::Value*, 16> fields;
2794 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2795 blockLayout->getElementOffsetInBits(0),
2796 tunit, tunit));
2797 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2798 blockLayout->getElementOffsetInBits(1),
2799 tunit, tunit));
2800 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2801 blockLayout->getElementOffsetInBits(2),
2802 tunit, tunit));
2803 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2804 blockLayout->getElementOffsetInBits(3),
2805 tunit, tunit));
2806 fields.push_back(createFieldType("__descriptor",
2807 C.getPointerType(block.NeedsCopyDispose ?
2808 C.getBlockDescriptorExtendedType() :
2809 C.getBlockDescriptorType()),
2810 0, loc, AS_public,
2811 blockLayout->getElementOffsetInBits(4),
2812 tunit, tunit));
2813
2814 // We want to sort the captures by offset, not because DWARF
2815 // requires this, but because we're paranoid about debuggers.
2816 SmallVector<BlockLayoutChunk, 8> chunks;
2817
2818 // 'this' capture.
2819 if (blockDecl->capturesCXXThis()) {
2820 BlockLayoutChunk chunk;
2821 chunk.OffsetInBits =
2822 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2823 chunk.Capture = 0;
2824 chunks.push_back(chunk);
2825 }
2826
2827 // Variable captures.
2828 for (BlockDecl::capture_const_iterator
2829 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2830 i != e; ++i) {
2831 const BlockDecl::Capture &capture = *i;
2832 const VarDecl *variable = capture.getVariable();
2833 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2834
2835 // Ignore constant captures.
2836 if (captureInfo.isConstant())
2837 continue;
2838
2839 BlockLayoutChunk chunk;
2840 chunk.OffsetInBits =
2841 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2842 chunk.Capture = &capture;
2843 chunks.push_back(chunk);
2844 }
2845
2846 // Sort by offset.
2847 llvm::array_pod_sort(chunks.begin(), chunks.end());
2848
2849 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2850 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2851 uint64_t offsetInBits = i->OffsetInBits;
2852 const BlockDecl::Capture *capture = i->Capture;
2853
2854 // If we have a null capture, this must be the C++ 'this' capture.
2855 if (!capture) {
2856 const CXXMethodDecl *method =
2857 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2858 QualType type = method->getThisType(C);
2859
2860 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2861 offsetInBits, tunit, tunit));
2862 continue;
2863 }
2864
2865 const VarDecl *variable = capture->getVariable();
2866 StringRef name = variable->getName();
2867
2868 llvm::DIType fieldType;
2869 if (capture->isByRef()) {
2870 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2871
2872 // FIXME: this creates a second copy of this type!
2873 uint64_t xoffset;
2874 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2875 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2876 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2877 ptrInfo.first, ptrInfo.second,
2878 offsetInBits, 0, fieldType);
2879 } else {
2880 fieldType = createFieldType(name, variable->getType(), 0,
2881 loc, AS_public, offsetInBits, tunit, tunit);
2882 }
2883 fields.push_back(fieldType);
2884 }
2885
2886 SmallString<36> typeName;
2887 llvm::raw_svector_ostream(typeName)
2888 << "__block_literal_" << CGM.getUniqueBlockCount();
2889
2890 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2891
2892 llvm::DIType type =
2893 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2894 CGM.getContext().toBits(block.BlockSize),
2895 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00002896 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2898
2899 // Get overall information about the block.
2900 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2901 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00002902
2903 // Create the descriptor for the parameter.
2904 llvm::DIVariable debugVar =
2905 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002906 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00002907 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00002908 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002909 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2910
Adrian Prantl616bef42013-03-14 21:52:59 +00002911 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00002912 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00002913 llvm::Instruction *DbgVal =
2914 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002915 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00002916 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2917 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00002918
Adrian Prantl616bef42013-03-14 21:52:59 +00002919 // Insert an llvm.dbg.declare into the current block.
2920 llvm::Instruction *DbgDecl =
2921 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2922 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002923}
2924
Eric Christopher91a31902013-01-16 01:22:32 +00002925/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2926/// a static data member of a class, find its corresponding in-class
2927/// declaration.
2928llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2929 if (cast<VarDecl>(D)->isStaticDataMember()) {
2930 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2931 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2932 if (MI != StaticDataMemberCache.end())
2933 // Verify the info still exists.
2934 if (llvm::Value *V = MI->second)
2935 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2936 }
2937 return llvm::DIDerivedType();
2938}
2939
Guy Benyei11169dd2012-12-18 14:30:41 +00002940/// EmitGlobalVariable - Emit information about a global variable.
2941void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2942 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00002943 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 // Create global variable debug descriptor.
2945 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2946 unsigned LineNo = getLineNumber(D->getLocation());
2947
2948 setLocation(D->getLocation());
2949
2950 QualType T = D->getType();
2951 if (T->isIncompleteArrayType()) {
2952
2953 // CodeGen turns int[] into int[1] so we'll do the same here.
2954 llvm::APInt ConstVal(32, 1);
2955 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2956
2957 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2958 ArrayType::Normal, 0);
2959 }
2960 StringRef DeclName = D->getName();
2961 StringRef LinkageName;
2962 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2963 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2964 LinkageName = Var->getName();
2965 if (LinkageName == DeclName)
2966 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002967 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikiedb352812013-05-15 23:46:19 +00002969 DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher91a31902013-01-16 01:22:32 +00002971 Var->hasInternalLinkage(), Var,
2972 getStaticDataMemberDeclaration(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002973}
2974
2975/// EmitGlobalVariable - Emit information about an objective-c interface.
2976void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2977 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00002978 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 // Create global variable debug descriptor.
2980 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2981 unsigned LineNo = getLineNumber(ID->getLocation());
2982
2983 StringRef Name = ID->getName();
2984
2985 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2986 if (T->isIncompleteArrayType()) {
2987
2988 // CodeGen turns int[] into int[1] so we'll do the same here.
2989 llvm::APInt ConstVal(32, 1);
2990 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2991
2992 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2993 ArrayType::Normal, 0);
2994 }
2995
2996 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2997 getOrCreateType(T, Unit),
2998 Var->hasInternalLinkage(), Var);
2999}
3000
3001/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003002void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003004 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003005 // Create the descriptor for the variable.
3006 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3007 StringRef Name = VD->getName();
3008 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3009 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3010 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3011 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3012 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3013 }
3014 // Do not use DIGlobalVariable for enums.
3015 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3016 return;
David Blaikiedb352812013-05-15 23:46:19 +00003017 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 getLineNumber(VD->getLocation()),
Eric Christopher91a31902013-01-16 01:22:32 +00003019 Ty, true, Init,
3020 getStaticDataMemberDeclaration(VD));
Guy Benyei11169dd2012-12-18 14:30:41 +00003021}
3022
David Blaikie9f88fe82013-04-22 06:13:21 +00003023void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiedb352812013-05-15 23:46:19 +00003024 llvm::DIScope Scope =
3025 LexicalBlockStack.empty()
3026 ? getContextDescriptor(cast<Decl>(UD.getDeclContext()))
3027 : llvm::DIScope(LexicalBlockStack.back());
David Blaikie9f88fe82013-04-22 06:13:21 +00003028 DBuilder.createImportedModule(
David Blaikiedb352812013-05-15 23:46:19 +00003029 Scope, getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003030 getLineNumber(UD.getLocation()));
3031}
3032
Guy Benyei11169dd2012-12-18 14:30:41 +00003033/// getOrCreateNamesSpace - Return namespace descriptor for the given
3034/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003035llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003036CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00003037 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 NameSpaceCache.find(NSDecl);
3039 if (I != NameSpaceCache.end())
3040 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003041
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3043 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003044 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3046 llvm::DINameSpace NS =
3047 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3048 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3049 return NS;
3050}
3051
3052void CGDebugInfo::finalize() {
3053 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3054 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3055 llvm::DIType Ty, RepTy;
3056 // Verify that the debug info still exists.
3057 if (llvm::Value *V = VI->second)
3058 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003059
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3061 TypeCache.find(VI->first);
3062 if (it != TypeCache.end()) {
3063 // Verify that the debug info still exists.
3064 if (llvm::Value *V = it->second)
3065 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3066 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003067
Adrian Prantl0f6df002013-03-29 19:20:35 +00003068 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003071
3072 // We keep our own list of retained types, because we need to look
3073 // up the final type in the type cache.
3074 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3075 RE = RetainedTypes.end(); RI != RE; ++RI)
3076 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3077
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 DBuilder.finalize();
3079}